Commit 7aa753a2 by Torkel Ödegaard

tech: migrating elasticsearch to typescript

parent 487c475a
......@@ -42,6 +42,7 @@ function (angular, _, coreModule, config) {
var pluginDef = dsConfig.meta;
System.import(pluginDef.module).then(function(plugin) {
console.log(plugin);
// check if its in cache now
if (self.datasources[name]) {
deferred.resolve(self.datasources[name]);
......
......@@ -2,7 +2,7 @@ import {describe, beforeEach, it, sinon, expect, angularMocks} from 'test/lib/co
import _ from 'lodash';
import {HistoryListCtrl} from 'app/features/dashboard/history/history';
import { versions, compare, restore } from 'test/mocks/history-mocks';
import {versions, compare, restore} from './history_mocks';
describe('HistoryListCtrl', function() {
var RESTORE_ID = 4;
......
define([],
function() {
'use strict';
return {
versions: function() {
export function versions() {
return [{
id: 4,
dashboardId: 1,
......@@ -45,11 +41,13 @@ define([],
createdBy: 'admin',
message: '',
}];
},
compare: function(type) {
}
export function compare(type) {
return type === 'basic' ? '<div></div>' : '<pre><code></code></pre>';
},
restore: function(version, restoredFrom) {
}
export function restore(version, restoredFrom?) {
return {
dashboard: {
meta: {
......@@ -192,6 +190,4 @@ define([],
message: 'Dashboard restored to version ' + version,
version: version
};
},
};
});
}
......@@ -2,7 +2,7 @@ import {describe, beforeEach, it, expect, angularMocks} from 'test/lib/common';
import helpers from 'test/specs/helpers';
import '../history/history_srv';
import {versions, restore} from 'test/mocks/history-mocks';
import {versions, restore} from './history_mocks';
describe('historySrv', function() {
var ctx = new helpers.ServiceTestContext();
......
declare var ElasticDatasource: any;
export {ElasticDatasource};
define([
'angular',
'lodash',
'moment',
'app/core/utils/kbn',
'./query_builder',
'./index_pattern',
'./elastic_response',
'./query_ctrl',
],
function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticResponse) {
'use strict';
ElasticResponse = ElasticResponse.ElasticResponse;
///<reference path="../../../headers/common.d.ts" />
import angular from 'angular';
import _ from 'lodash';
import moment from 'moment';
import {ElasticQueryBuilder} from './query_builder';
import {IndexPattern} from './index_pattern';
import {ElasticResponse} from './elastic_response';
export class ElasticDatasource {
basicAuth: string;
withCredentials: boolean;
url: string;
name: string;
index: string;
timeField: string;
esVersion: number;
interval: string;
queryBuilder: ElasticQueryBuilder;
indexPattern: IndexPattern;
/** @ngInject */
function ElasticDatasource(instanceSettings, $q, backendSrv, templateSrv, timeSrv) {
constructor(instanceSettings, private $q, private backendSrv, private templateSrv, private timeSrv) {
this.basicAuth = instanceSettings.basicAuth;
this.withCredentials = instanceSettings.withCredentials;
this.url = instanceSettings.url;
......@@ -28,9 +34,10 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
timeField: this.timeField,
esVersion: this.esVersion,
});
}
this._request = function(method, url, data) {
var options = {
private request(method, url, data?) {
var options: any = {
url: this.url + "/" + url,
method: method,
data: data
......@@ -45,33 +52,33 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
};
}
return backendSrv.datasourceRequest(options);
};
return this.backendSrv.datasourceRequest(options);
}
this._get = function(url) {
var range = timeSrv.timeRange();
private get(url) {
var range = this.timeSrv.timeRange();
var index_list = this.indexPattern.getIndexList(range.from.valueOf(), range.to.valueOf());
if (_.isArray(index_list) && index_list.length) {
return this._request('GET', index_list[0] + url).then(function(results) {
return this.request('GET', index_list[0] + url).then(function(results) {
results.data.$$config = results.config;
return results.data;
});
} else {
return this._request('GET', this.indexPattern.getIndexForToday() + url).then(function(results) {
return this.request('GET', this.indexPattern.getIndexForToday() + url).then(function(results) {
results.data.$$config = results.config;
return results.data;
});
}
};
}
this._post = function(url, data) {
return this._request('POST', url, data).then(function(results) {
private post(url, data) {
return this.request('POST', url, data).then(function(results) {
results.data.$$config = results.config;
return results.data;
});
};
}
this.annotationQuery = function(options) {
annotationQuery(options) {
var annotation = options.annotation;
var timeField = annotation.timeField || '@timestamp';
var queryString = annotation.query || '*';
......@@ -86,7 +93,7 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
format: "epoch_millis",
};
var queryInterpolated = templateSrv.replace(queryString, {}, 'lucene');
var queryInterpolated = this.templateSrv.replace(queryString, {}, 'lucene');
var query = {
"bool": {
"filter": [
......@@ -110,7 +117,7 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
data["fields"] = [timeField, "_source"];
}
var header = {search_type: "query_then_fetch", "ignore_unavailable": true};
var header: any = {search_type: "query_then_fetch", "ignore_unavailable": true};
// old elastic annotations had index specified on them
if (annotation.index) {
......@@ -121,7 +128,7 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
var payload = angular.toJson(header) + '\n' + angular.toJson(data) + '\n';
return this._post('_msearch', payload).then(function(res) {
return this.post('_msearch', payload).then(res => {
var list = [];
var hits = res.responses[0].hits.hits;
......@@ -169,8 +176,8 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
});
};
this.testDatasource = function() {
timeSrv.setTime({ from: 'now-1m', to: 'now' }, true);
testDatasource() {
this.timeSrv.setTime({ from: 'now-1m', to: 'now' }, true);
// validate that the index exist and has date field
return this.getFields({type: 'date'}).then(function(dateFields) {
var timeField = _.find(dateFields, {text: this.timeField});
......@@ -190,27 +197,29 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
return { status: "error", message: err.status };
}
});
};
}
this.getQueryHeader = function(searchType, timeFrom, timeTo) {
var header = {search_type: searchType, "ignore_unavailable": true};
header.index = this.indexPattern.getIndexList(timeFrom, timeTo);
return angular.toJson(header);
};
getQueryHeader(searchType, timeFrom, timeTo) {
return angular.toJson({
search_type: searchType,
"ignore_unavailable": true,
index: this.indexPattern.getIndexList(timeFrom, timeTo),
});
}
this.query = function(options) {
query(options) {
var payload = "";
var target;
var sentTargets = [];
// add global adhoc filters to timeFilter
var adhocFilters = templateSrv.getAdhocFilters(this.name);
var adhocFilters = this.templateSrv.getAdhocFilters(this.name);
for (var i = 0; i < options.targets.length; i++) {
target = options.targets[i];
if (target.hide) {continue;}
var queryString = templateSrv.replace(target.query || '*', options.scopedVars, 'lucene');
var queryString = this.templateSrv.replace(target.query || '*', options.scopedVars, 'lucene');
var queryObj = this.queryBuilder.build(target, adhocFilters, queryString);
var esQuery = angular.toJson(queryObj);
......@@ -223,20 +232,20 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
}
if (sentTargets.length === 0) {
return $q.when([]);
return this.$q.when([]);
}
payload = payload.replace(/\$timeFrom/g, options.range.from.valueOf());
payload = payload.replace(/\$timeTo/g, options.range.to.valueOf());
payload = templateSrv.replace(payload, options.scopedVars);
payload = this.templateSrv.replace(payload, options.scopedVars);
return this._post('_msearch', payload).then(function(res) {
return this.post('_msearch', payload).then(function(res) {
return new ElasticResponse(sentTargets, res).getTimeSeries();
});
};
this.getFields = function(query) {
return this._get('/_mapping').then(function(result) {
getFields(query) {
return this.get('/_mapping').then(function(result) {
var typeMap = {
'float': 'number',
......@@ -313,10 +322,10 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
return value;
});
});
};
}
this.getTerms = function(queryDef) {
var range = timeSrv.timeRange();
getTerms(queryDef) {
var range = this.timeSrv.timeRange();
var searchType = this.esVersion >= 5 ? 'query_then_fetch' : 'count' ;
var header = this.getQueryHeader(searchType, range.from, range.to);
var esQuery = angular.toJson(this.queryBuilder.getTermsQuery(queryDef));
......@@ -325,7 +334,7 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
esQuery = esQuery.replace(/\$timeTo/g, range.to.valueOf());
esQuery = header + '\n' + esQuery + '\n';
return this._post('_msearch?search_type=' + searchType, esQuery).then(function(res) {
return this.post('_msearch?search_type=' + searchType, esQuery).then(function(res) {
if (!res.responses[0].aggregations) {
return [];
}
......@@ -338,35 +347,30 @@ function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticRes
};
});
});
};
}
this.metricFindQuery = function(query) {
metricFindQuery(query) {
query = angular.fromJson(query);
if (!query) {
return $q.when([]);
return this.$q.when([]);
}
if (query.find === 'fields') {
query.field = templateSrv.replace(query.field, {}, 'lucene');
query.field = this.templateSrv.replace(query.field, {}, 'lucene');
return this.getFields(query);
}
if (query.find === 'terms') {
query.query = templateSrv.replace(query.query || '*', {}, 'lucene');
query.query = this.templateSrv.replace(query.query || '*', {}, 'lucene');
return this.getTerms(query);
}
};
}
this.getTagKeys = function() {
getTagKeys() {
return this.getFields({});
};
}
this.getTagValues = function(options) {
getTagValues(options) {
return this.getTerms({field: options.key, query: '*'});
};
}
return {
ElasticDatasource: ElasticDatasource
};
});
}
///<reference path="../../../headers/common.d.ts" />
import _ from 'lodash';
import queryDef from "./query_def";
import * as queryDef from "./query_def";
import TableModel from 'app/core/table_model';
export function ElasticResponse(targets, response) {
export class ElasticResponse {
constructor(private targets, private response) {
this.targets = targets;
this.response = response;
}
}
ElasticResponse.prototype.processMetrics = function(esAgg, target, seriesList, props) {
processMetrics(esAgg, target, seriesList, props) {
var metric, y, i, newSeries, bucket, value;
for (y = 0; y < target.metrics.length; y++) {
......@@ -94,9 +96,9 @@ ElasticResponse.prototype.processMetrics = function(esAgg, target, seriesList, p
}
}
}
};
}
ElasticResponse.prototype.processAggregationDocs = function(esAgg, aggDef, target, table, props) {
processAggregationDocs(esAgg, aggDef, target, table, props) {
// add columns
if (table.columns.length === 0) {
for (let propKey of _.keys(props)) {
......@@ -124,7 +126,7 @@ ElasticResponse.prototype.processAggregationDocs = function(esAgg, aggDef, targe
for (let metric of target.metrics) {
switch (metric.type) {
case "count": {
addMetricValue(values, this._getMetricName(metric.type), bucket.doc_count);
addMetricValue(values, this.getMetricName(metric.type), bucket.doc_count);
break;
}
case 'extended_stats': {
......@@ -138,12 +140,12 @@ ElasticResponse.prototype.processAggregationDocs = function(esAgg, aggDef, targe
stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;
stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower;
addMetricValue(values, this._getMetricName(statName), stats[statName]);
addMetricValue(values, this.getMetricName(statName), stats[statName]);
}
break;
}
default: {
let metricName = this._getMetricName(metric.type);
let metricName = this.getMetricName(metric.type);
let otherMetrics = _.filter(target.metrics, {type: metric.type});
// if more of the same metric type include field field name in property
......@@ -159,11 +161,11 @@ ElasticResponse.prototype.processAggregationDocs = function(esAgg, aggDef, targe
table.rows.push(values);
}
};
}
// This is quite complex
// neeed to recurise down the nested buckets to build series
ElasticResponse.prototype.processBuckets = function(aggs, target, seriesList, table, props, depth) {
// This is quite complex
// neeed to recurise down the nested buckets to build series
processBuckets(aggs, target, seriesList, table, props, depth) {
var bucket, aggDef, esAgg, aggId;
var maxDepth = target.bucketAggs.length-1;
......@@ -197,19 +199,19 @@ ElasticResponse.prototype.processBuckets = function(aggs, target, seriesList, ta
}
}
}
};
}
ElasticResponse.prototype._getMetricName = function(metric) {
private getMetricName(metric) {
var metricDef = _.find(queryDef.metricAggTypes, {value: metric});
if (!metricDef) {
metricDef = _.find(queryDef.extendedStats, {value: metric});
}
return metricDef ? metricDef.text : metric;
};
}
ElasticResponse.prototype._getSeriesName = function(series, target, metricTypeCount) {
var metricName = this._getMetricName(series.metric);
private getSeriesName(series, target, metricTypeCount) {
var metricName = this.getMetricName(series.metric);
if (target.alias) {
var regex = /\{\{([\s\S]+?)\}\}/g;
......@@ -252,19 +254,18 @@ ElasticResponse.prototype._getSeriesName = function(series, target, metricTypeCo
}
return name.trim() + ' ' + metricName;
};
}
ElasticResponse.prototype.nameSeries = function(seriesList, target) {
nameSeries(seriesList, target) {
var metricTypeCount = _.uniq(_.map(seriesList, 'metric')).length;
var fieldNameCount = _.uniq(_.map(seriesList, 'field')).length;
for (var i = 0; i < seriesList.length; i++) {
var series = seriesList[i];
series.target = this._getSeriesName(series, target, metricTypeCount, fieldNameCount);
series.target = this.getSeriesName(series, target, metricTypeCount);
}
}
};
ElasticResponse.prototype.processHits = function(hits, seriesList) {
processHits(hits, seriesList) {
var series = {target: 'docs', type: 'docs', datapoints: [], total: hits.total, filterable: true};
var propName, hit, doc, i;
......@@ -289,9 +290,9 @@ ElasticResponse.prototype.processHits = function(hits, seriesList) {
}
seriesList.push(series);
};
}
ElasticResponse.prototype.trimDatapoints = function(aggregations, target) {
trimDatapoints(aggregations, target) {
var histogram = _.find(target.bucketAggs, { type: 'date_histogram'});
var shouldDropFirstAndLast = histogram && histogram.settings && histogram.settings.trimEdges;
......@@ -304,9 +305,9 @@ ElasticResponse.prototype.trimDatapoints = function(aggregations, target) {
}
}
}
};
}
ElasticResponse.prototype.getErrorFromElasticResponse = function(response, err) {
getErrorFromElasticResponse(response, err) {
var result: any = {};
result.data = JSON.stringify(err, null, 4);
if (err.root_cause && err.root_cause.length > 0 && err.root_cause[0].reason) {
......@@ -320,9 +321,9 @@ ElasticResponse.prototype.getErrorFromElasticResponse = function(response, err)
}
return result;
};
}
ElasticResponse.prototype.getTimeSeries = function() {
getTimeSeries() {
var seriesList = [];
for (var i = 0; i < this.response.responses.length; i++) {
......@@ -356,5 +357,5 @@ ElasticResponse.prototype.getTimeSeries = function() {
}
return { data: seriesList };
};
}
}
define([
'lodash',
'moment',
],
function (_, moment) {
'use strict';
function IndexPattern(pattern, interval) {
this.pattern = pattern;
this.interval = interval;
}
///<reference path="../../../headers/common.d.ts" />
import moment from 'moment';
IndexPattern.intervalMap = {
const intervalMap = {
"Hourly": { startOf: 'hour', amount: 'hours'},
"Daily": { startOf: 'day', amount: 'days'},
"Weekly": { startOf: 'isoWeek', amount: 'weeks'},
"Monthly": { startOf: 'month', amount: 'months'},
"Yearly": { startOf: 'year', amount: 'years'},
};
};
export class IndexPattern {
IndexPattern.prototype.getIndexForToday = function() {
constructor(private pattern, private interval: string | null) { }
getIndexForToday() {
if (this.interval) {
return moment.utc().format(this.pattern);
} else {
......@@ -26,12 +22,12 @@ function (_, moment) {
}
};
IndexPattern.prototype.getIndexList = function(from, to) {
getIndexList(from, to) {
if (!this.interval) {
return this.pattern;
}
var intervalInfo = IndexPattern.intervalMap[this.interval];
var intervalInfo = intervalMap[this.interval];
var start = moment(from).utc().startOf(intervalInfo.startOf);
var end = moment(to).utc().startOf(intervalInfo.startOf).valueOf();
var indexList = [];
......@@ -42,7 +38,6 @@ function (_, moment) {
}
return indexList;
};
}
}
return IndexPattern;
});
define([
'./query_def',
],
function (queryDef) {
'use strict';
import * as queryDef from './query_def';
function ElasticQueryBuilder(options) {
export class ElasticQueryBuilder {
timeField: string;
esVersion: number;
constructor(options) {
this.timeField = options.timeField;
this.esVersion = options.esVersion;
}
ElasticQueryBuilder.prototype.getRangeFilter = function() {
getRangeFilter() {
var filter = {};
filter[this.timeField] = {
gte: "$timeFrom",
......@@ -18,9 +18,9 @@ function (queryDef) {
};
return filter;
};
}
ElasticQueryBuilder.prototype.buildTermsAgg = function(aggDef, queryNode, target) {
buildTermsAgg(aggDef, queryNode, target) {
var metricRef, metric, y;
queryNode.terms = { "field": aggDef.field };
......@@ -57,10 +57,10 @@ function (queryDef) {
}
return queryNode;
};
}
ElasticQueryBuilder.prototype.getDateHistogramAgg = function(aggDef) {
var esAgg = {};
getDateHistogramAgg(aggDef) {
var esAgg: any = {};
var settings = aggDef.settings || {};
esAgg.interval = settings.interval;
esAgg.field = this.timeField;
......@@ -77,10 +77,10 @@ function (queryDef) {
}
return esAgg;
};
}
ElasticQueryBuilder.prototype.getHistogramAgg = function(aggDef) {
var esAgg = {};
getHistogramAgg(aggDef) {
var esAgg: any = {};
var settings = aggDef.settings || {};
esAgg.interval = settings.interval;
esAgg.field = aggDef.field;
......@@ -90,9 +90,9 @@ function (queryDef) {
esAgg.missing = settings.missing;
}
return esAgg;
};
}
ElasticQueryBuilder.prototype.getFiltersAgg = function(aggDef) {
getFiltersAgg(aggDef) {
var filterObj = {};
for (var i = 0; i < aggDef.settings.filters.length; i++) {
var query = aggDef.settings.filters[i].query;
......@@ -107,9 +107,9 @@ function (queryDef) {
}
return filterObj;
};
}
ElasticQueryBuilder.prototype.documentQuery = function(query, size) {
documentQuery(query, size) {
query.size = size;
query.sort = {};
query.sort[this.timeField] = {order: 'desc', unmapped_type: 'boolean'};
......@@ -126,9 +126,9 @@ function (queryDef) {
query.docvalue_fields = [this.timeField];
}
return query;
};
}
ElasticQueryBuilder.prototype.addAdhocFilters = function(query, adhocFilters) {
addAdhocFilters(query, adhocFilters) {
if (!adhocFilters) {
return;
}
......@@ -142,7 +142,7 @@ function (queryDef) {
queryCondition = {};
queryCondition[filter.key] = {query: filter.value};
switch(filter.operator){
switch (filter.operator){
case "=":
if (!query.query.bool.must) { query.query.bool.must = []; }
query.query.bool.must.push({match_phrase: queryCondition});
......@@ -169,7 +169,7 @@ function (queryDef) {
}
};
ElasticQueryBuilder.prototype.build = function(target, adhocFilters, queryString) {
build(target, adhocFilters?, queryString?) {
// make sure query has defaults;
target.metrics = target.metrics || [{ type: 'count', id: '1' }];
target.dsType = 'elasticsearch';
......@@ -213,7 +213,7 @@ function (queryDef) {
var aggDef = target.bucketAggs[i];
var esAgg = {};
switch(aggDef.type) {
switch (aggDef.type) {
case 'date_histogram': {
esAgg["date_histogram"] = this.getDateHistogramAgg(aggDef);
break;
......@@ -273,10 +273,10 @@ function (queryDef) {
}
return query;
};
}
ElasticQueryBuilder.prototype.getTermsQuery = function(queryDef) {
var query = {
getTermsQuery(queryDef) {
var query: any = {
"size": 0,
"query": {
"bool": {
......@@ -311,7 +311,5 @@ function (queryDef) {
}
};
return query;
};
return ElasticQueryBuilder;
});
}
}
define([
'lodash'
],
function (_) {
'use strict';
return {
metricAggTypes: [
///<reference path="../../../headers/common.d.ts" />
import _ from 'lodash';
export const metricAggTypes = [
{text: "Count", value: 'count', requiresField: false},
{text: "Average", value: 'avg', requiresField: true, supportsInlineScript: true, supportsMissing: true},
{text: "Sum", value: 'sum', requiresField: true, supportsInlineScript: true, supportsMissing: true},
......@@ -17,27 +14,27 @@ function (_) {
{text: "Moving Average", value: 'moving_avg', requiresField: false, isPipelineAgg: true, minVersion: 2},
{text: "Derivative", value: 'derivative', requiresField: false, isPipelineAgg: true, minVersion: 2 },
{text: "Raw Document", value: "raw_document", requiresField: false}
],
];
bucketAggTypes: [
export const bucketAggTypes = [
{text: "Terms", value: 'terms', requiresField: true},
{text: "Filters", value: 'filters' },
{text: "Geo Hash Grid", value: 'geohash_grid', requiresField: true},
{text: "Date Histogram", value: 'date_histogram', requiresField: true},
{text: "Histogram", value: 'histogram', requiresField: true},
],
];
orderByOptions: [
export const orderByOptions = [
{text: "Doc Count", value: '_count' },
{text: "Term value", value: '_term' },
],
];
orderOptions: [
export const orderOptions = [
{text: "Top", value: 'desc' },
{text: "Bottom", value: 'asc' },
],
];
sizeOptions: [
export const sizeOptions = [
{text: "No limit", value: '0' },
{text: "1", value: '1' },
{text: "2", value: '2' },
......@@ -46,9 +43,9 @@ function (_) {
{text: "10", value: '10' },
{text: "15", value: '15' },
{text: "20", value: '20' },
],
];
extendedStats: [
export const extendedStats = [
{text: 'Avg', value: 'avg'},
{text: 'Min', value: 'min'},
{text: 'Max', value: 'max'},
......@@ -57,9 +54,9 @@ function (_) {
{text: 'Std Dev', value: 'std_deviation'},
{text: 'Std Dev Upper', value: 'std_deviation_bounds_upper'},
{text: 'Std Dev Lower', value: 'std_deviation_bounds_lower'},
],
];
intervalOptions: [
export const intervalOptions = [
{text: 'auto', value: 'auto'},
{text: '10s', value: '10s'},
{text: '1m', value: '1m'},
......@@ -68,17 +65,17 @@ function (_) {
{text: '20m', value: '20m'},
{text: '1h', value: '1h'},
{text: '1d', value: '1d'},
],
];
movingAvgModelOptions: [
export const movingAvgModelOptions = [
{text: 'Simple', value: 'simple'},
{text: 'Linear', value: 'linear'},
{text: 'Exponentially Weighted', value: 'ewma'},
{text: 'Holt Linear', value: 'holt'},
{text: 'Holt Winters', value: 'holt_winters'},
],
];
pipelineOptions: {
export const pipelineOptions = {
'moving_avg' : [
{text: 'window', default: 5},
{text: 'model', default: 'simple'},
......@@ -88,9 +85,9 @@ function (_) {
'derivative': [
{text: 'unit', default: undefined},
]
},
};
movingAvgModelSettings: {
export const movingAvgModelSettings = {
'simple' : [],
'linear' : [],
'ewma' : [
......@@ -106,94 +103,89 @@ function (_) {
{text: "Period", value: "period", default: undefined},
{text: "Pad", value: "pad", default: undefined, isCheckbox: true},
],
},
};
getMetricAggTypes: function(esVersion) {
return _.filter(this.metricAggTypes, function(f) {
export function getMetricAggTypes(esVersion) {
return _.filter(metricAggTypes, function(f) {
if (f.minVersion) {
return f.minVersion <= esVersion;
} else {
return true;
}
});
},
}
getPipelineOptions: function(metric) {
if (!this.isPipelineAgg(metric.type)) {
export function getPipelineOptions(metric) {
if (!isPipelineAgg(metric.type)) {
return [];
}
return this.pipelineOptions[metric.type];
},
return pipelineOptions[metric.type];
}
isPipelineAgg: function(metricType) {
export function isPipelineAgg(metricType) {
if (metricType) {
var po = this.pipelineOptions[metricType];
var po = pipelineOptions[metricType];
return po !== null && po !== undefined;
}
return false;
},
}
getPipelineAggOptions: function(targets) {
var self = this;
export function getPipelineAggOptions(targets) {
var result = [];
_.each(targets.metrics, function(metric) {
if (!self.isPipelineAgg(metric.type)) {
result.push({text: self.describeMetric(metric), value: metric.id });
if (!isPipelineAgg(metric.type)) {
result.push({text: describeMetric(metric), value: metric.id });
}
});
return result;
},
}
getMovingAvgSettings: function(model, filtered) {
export function getMovingAvgSettings(model, filtered) {
var filteredResult = [];
if (filtered) {
_.each(this.movingAvgModelSettings[model], function(setting) {
_.each(movingAvgModelSettings[model], function(setting) {
if (!(setting.isCheckbox)) {
filteredResult.push(setting);
}
});
return filteredResult;
}
return this.movingAvgModelSettings[model];
},
return movingAvgModelSettings[model];
}
getOrderByOptions: function(target) {
var self = this;
export function getOrderByOptions(target) {
var metricRefs = [];
_.each(target.metrics, function(metric) {
if (metric.type !== 'count') {
metricRefs.push({text: self.describeMetric(metric), value: metric.id});
metricRefs.push({text: describeMetric(metric), value: metric.id});
}
});
return this.orderByOptions.concat(metricRefs);
},
return orderByOptions.concat(metricRefs);
}
describeOrder: function(order) {
var def = _.find(this.orderOptions, {value: order});
export function describeOrder(order) {
var def = _.find(orderOptions, {value: order});
return def.text;
},
}
describeMetric: function(metric) {
var def = _.find(this.metricAggTypes, {value: metric.type});
export function describeMetric(metric) {
var def = _.find(metricAggTypes, {value: metric.type});
return def.text + ' ' + metric.field;
},
}
describeOrderBy: function(orderBy, target) {
var def = _.find(this.orderByOptions, {value: orderBy});
export function describeOrderBy(orderBy, target) {
var def = _.find(orderByOptions, {value: orderBy});
if (def) {
return def.text;
}
var metric = _.find(target.metrics, {id: orderBy});
if (metric) {
return this.describeMetric(metric);
return describeMetric(metric);
} else {
return "metric not found";
}
},
};
});
};
......@@ -2,7 +2,7 @@
import {describe, it, expect} from 'test/lib/common';
import moment from 'moment';
import IndexPattern from '../index_pattern';
import {IndexPattern} from '../index_pattern';
describe('IndexPattern', function() {
......@@ -19,7 +19,7 @@ describe('IndexPattern', function() {
describe('no interval', function() {
it('should return correct index', function() {
var pattern = new IndexPattern('my-metrics');
var pattern = new IndexPattern('my-metrics', null);
var from = new Date(2015, 4, 30, 1, 2, 3);
var to = new Date(2015, 5, 1, 12, 5 , 6);
expect(pattern.getIndexList(from, to)).to.eql('my-metrics');
......
import {describe, beforeEach, it, expect} from 'test/lib/common';
import ElasticQueryBuilder from '../query_builder';
import {ElasticQueryBuilder} from '../query_builder';
describe('ElasticQueryBuilder', function() {
var builder;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment