grafana/public/app/plugins/datasource/elasticsearch/query_ctrl.ts

88 lines
2.2 KiB
TypeScript
Raw Normal View History

2017-12-20 19:33:33 +08:00
import './bucket_agg';
import './metric_agg';
2017-12-20 19:33:33 +08:00
import angular from 'angular';
import _ from 'lodash';
import * as queryDef from './query_def';
import { QueryCtrl } from 'app/plugins/sdk';
export class ElasticQueryCtrl extends QueryCtrl {
2017-12-20 19:33:33 +08:00
static templateUrl = 'partials/query.editor.html';
esVersion: any;
rawQueryOld: string;
/** @ngInject */
constructor($scope, $injector, private $rootScope, private uiSegmentSrv) {
super($scope, $injector);
this.esVersion = this.datasource.esVersion;
this.queryUpdated();
}
getFields(type) {
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 newJson = angular.toJson(this.datasource.queryBuilder.build(this.target), true);
2017-06-16 03:56:24 +08:00
if (this.rawQueryOld && newJson !== this.rawQueryOld) {
this.refresh();
}
2017-06-16 03:56:24 +08:00
this.rawQueryOld = newJson;
2017-12-20 19:33:33 +08:00
this.$rootScope.appEvent('elastic-query-updated');
}
getCollapsedText() {
const metricAggs = this.target.metrics;
const bucketAggs = this.target.bucketAggs;
const metricAggTypes = queryDef.getMetricAggTypes(this.esVersion);
const bucketAggTypes = queryDef.bucketAggTypes;
let text = '';
2016-04-27 16:16:04 +08:00
if (this.target.query) {
2017-12-20 19:33:33 +08:00
text += 'Query: ' + this.target.query + ', ';
2016-04-27 16:16:04 +08:00
}
2017-12-20 19:33:33 +08:00
text += 'Metrics: ';
2016-04-27 16:16:04 +08:00
_.each(metricAggs, (metric, index) => {
const aggDef = _.find(metricAggTypes, { value: metric.type });
2017-12-20 19:33:33 +08:00
text += aggDef.text + '(';
2016-04-27 16:16:04 +08:00
if (aggDef.requiresField) {
text += metric.field;
}
2017-12-20 19:33:33 +08:00
text += '), ';
2016-04-27 16:16:04 +08:00
});
_.each(bucketAggs, (bucketAgg, index) => {
if (index === 0) {
2017-12-20 19:33:33 +08:00
text += ' Group by: ';
2016-04-27 16:16:04 +08:00
}
const aggDef = _.find(bucketAggTypes, { value: bucketAgg.type });
2017-12-20 19:33:33 +08:00
text += aggDef.text + '(';
2016-04-27 16:16:04 +08:00
if (aggDef.requiresField) {
text += bucketAgg.field;
}
2017-12-20 19:33:33 +08:00
text += '), ';
2016-04-27 16:16:04 +08:00
});
if (this.target.alias) {
2017-12-20 19:33:33 +08:00
text += 'Alias: ' + this.target.alias;
2016-04-27 16:16:04 +08:00
}
return text;
}
handleQueryError(err) {
2017-12-20 19:33:33 +08:00
this.error = err.message || 'Failed to issue metric query';
return [];
}
}