<commit_before>import './bucket_agg';
import './metric_agg';
import './pipeline_variables';

import angular, { auto } from 'angular';
import _ from 'lodash';
import * as queryDef from './query_def';
import { QueryCtrl } from 'app/plugins/sdk';
import { ElasticsearchAggregation } from './types';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { CoreEvents } from 'app/types';

export class ElasticQueryCtrl extends QueryCtrl {
  static templateUrl = 'partials/query.editor.html';

  esVersion: any;
  rawQueryOld: string;

  /** @ngInject */
  constructor(
    $scope: any,
    $injector: auto.IInjectorService,
    private $rootScope: GrafanaRootScope,
    private uiSegmentSrv: any
  ) {
    super($scope, $injector);

    this.esVersion = this.datasource.esVersion;

    this.target = this.target || {};
    this.target.metrics = this.target.metrics || [queryDef.defaultMetricAgg()];
    this.target.bucketAggs = this.target.bucketAggs || [queryDef.defaultBucketAgg()];

    if (this.target.bucketAggs.length === 0) {
      const metric = this.target.metrics[0];
      if (!metric || metric.type !== 'raw_document') {
        this.target.bucketAggs = [queryDef.defaultBucketAgg()];
      }
      this.refresh();
    }

    this.queryUpdated();
  }

  getFields(type: any) {
    const jsonStr = angular.toJson({ find: 'fields', type: type });
    return this.datasource
      .metricFindQuery(jsonStr)
      .then(this.uiSegmentSrv.transformToSegments(false))
      .catch(this.handleQueryError.bind(this));
  }

  queryUpdated() {
    // As Raw Data and Raw Document have the same request, we need to run refresh if they are updated
    const isPossiblyRawDataSwitch = this.target.metrics.some(
      (metric: any) => metric.type === 'raw_data' || metric.type === 'raw_document'
    );
    const newJson = angular.toJson(this.datasource.queryBuilder.build(this.target), true);
    if (this.rawQueryOld && newJson !== this.rawQueryOld) {
      this.refresh();
    } else if (isPossiblyRawDataSwitch) {
      this.refresh();
    }

    this.rawQueryOld = newJson;
    this.$rootScope.appEvent(CoreEvents.elasticQueryUpdated);
  }

  getCollapsedText() {
    const metricAggs: ElasticsearchAggregation[] = this.target.metrics;
    const bucketAggs = this.target.bucketAggs;
    const metricAggTypes = queryDef.getMetricAggTypes(this.esVersion);
    const bucketAggTypes = queryDef.bucketAggTypes;
    let text = '';

    if (this.target.query) {
      text += 'Query: ' + this.target.query + ', ';
    }

    text += 'Metrics: ';

    _.each(metricAggs, (metric, index) => {
      const aggDef: any = _.find(metricAggTypes, { value: metric.type });
      text += aggDef.text + '(';
      if (aggDef.requiresField) {
        text += metric.field;
      }
      if (aggDef.supportsMultipleBucketPaths) {
        text += metric.settings.script.replace(new RegExp('params.', 'g'), '');<commit_msg>Fix matrics comparison to know when to refresh (#26382)<commit_after>import './bucket_agg';
import './metric_agg';
import './pipeline_variables';

import angular, { auto } from 'angular';
import _ from 'lodash';
import * as queryDef from './query_def';
import { QueryCtrl } from 'app/plugins/sdk';
import { ElasticsearchAggregation } from './types';
import { GrafanaRootScope } from 'app/routes/GrafanaCtrl';
import { CoreEvents } from 'app/types';

export class ElasticQueryCtrl extends QueryCtrl {
  static templateUrl = 'partials/query.editor.html';

  esVersion: any;
  rawQueryOld: string;
  targetMetricsOld: string;

  /** @ngInject */
  constructor(
    $scope: any,
    $injector: auto.IInjectorService,
    private $rootScope: GrafanaRootScope,
    private uiSegmentSrv: any
  ) {
    super($scope, $injector);

    this.esVersion = this.datasource.esVersion;

    this.target = this.target || {};
    this.target.metrics = this.target.metrics || [queryDef.defaultMetricAgg()];
    this.target.bucketAggs = this.target.bucketAggs || [queryDef.defaultBucketAgg()];

    if (this.target.bucketAggs.length === 0) {
      const metric = this.target.metrics[0];
      if (!metric || metric.type !== 'raw_document') {
        this.target.bucketAggs = [queryDef.defaultBucketAgg()];
      }
      this.refresh();
    }

    this.queryUpdated();
  }

  getFields(type: any) {
    const jsonStr = angular.toJson({ find: 'fields', type: type });
    return this.datasource
      .metricFindQuery(jsonStr)
      .then(this.uiSegmentSrv.transformToSegments(false))
      .catch(this.handleQueryError.bind(this));
  }

  queryUpdated() {
    const newJsonTargetMetrics = angular.toJson(this.target.metrics);
    const newJsonRawQuery = angular.toJson(this.datasource.queryBuilder.build(this.target), true);
    if (
      (this.rawQueryOld && newJsonRawQuery !== this.rawQueryOld) ||
      (this.targetMetricsOld && newJsonTargetMetrics !== this.targetMetricsOld)
    ) {
      this.refresh();
    }

    this.rawQueryOld = newJsonRawQuery;
    this.targetMetricsOld = newJsonTargetMetrics;
    this.$rootScope.appEvent(CoreEvents.elasticQueryUpdated);
  }

  getCollapsedText() {
    const metricAggs: ElasticsearchAggregation[] = this.target.metrics;
    const bucketAggs = this.target.bucketAggs;
    const metricAggTypes = queryDef.getMetricAggTypes(this.esVersion);
    const bucketAggTypes = queryDef.bucketAggTypes;
    let text = '';

    if (this.target.query) {
      text += 'Query: ' + this.target.query + ', ';
    }

    text += 'Metrics: ';

    _.each(metricAggs, (metric, index) => {
      const aggDef: any = _.find(metricAggTypes, { value: metric.type });
      text += aggDef.text + '(';
      if (aggDef.requiresField) {
        text += metric.field;
      }
      if (aggDef.supportsMultipleBucketPaths) {
        text += metric.settings.script.replace(new RegExp('params.', 'g'), '');
{'fraction_non_alphanumeric': 0.13944291609353507, 'fraction_numerical': 0.001547455295735901, 'mean_word_length': 3.4711760184473484, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '413994', 'n_tokens_mistral': 1855, 'n_tokens_neox': 1787, 'n_words': 362}