elastic_response.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import _ from 'lodash';
  3. import queryDef from "./query_def";
  4. import TableModel from 'app/core/table_model';
  5. export function ElasticResponse(targets, response) {
  6. this.targets = targets;
  7. this.response = response;
  8. }
  9. ElasticResponse.prototype.processMetrics = function(esAgg, target, seriesList, props) {
  10. var metric, y, i, newSeries, bucket, value;
  11. for (y = 0; y < target.metrics.length; y++) {
  12. metric = target.metrics[y];
  13. if (metric.hide) {
  14. continue;
  15. }
  16. switch (metric.type) {
  17. case 'count': {
  18. newSeries = { datapoints: [], metric: 'count', props: props};
  19. for (i = 0; i < esAgg.buckets.length; i++) {
  20. bucket = esAgg.buckets[i];
  21. value = bucket.doc_count;
  22. newSeries.datapoints.push([value, bucket.key]);
  23. }
  24. seriesList.push(newSeries);
  25. break;
  26. }
  27. case 'percentiles': {
  28. if (esAgg.buckets.length === 0) {
  29. break;
  30. }
  31. var firstBucket = esAgg.buckets[0];
  32. var percentiles = firstBucket[metric.id].values;
  33. for (var percentileName in percentiles) {
  34. newSeries = {datapoints: [], metric: 'p' + percentileName, props: props, field: metric.field};
  35. for (i = 0; i < esAgg.buckets.length; i++) {
  36. bucket = esAgg.buckets[i];
  37. var values = bucket[metric.id].values;
  38. newSeries.datapoints.push([values[percentileName], bucket.key]);
  39. }
  40. seriesList.push(newSeries);
  41. }
  42. break;
  43. }
  44. case 'extended_stats': {
  45. for (var statName in metric.meta) {
  46. if (!metric.meta[statName]) {
  47. continue;
  48. }
  49. newSeries = {datapoints: [], metric: statName, props: props, field: metric.field};
  50. for (i = 0; i < esAgg.buckets.length; i++) {
  51. bucket = esAgg.buckets[i];
  52. var stats = bucket[metric.id];
  53. // add stats that are in nested obj to top level obj
  54. stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;
  55. stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower;
  56. newSeries.datapoints.push([stats[statName], bucket.key]);
  57. }
  58. seriesList.push(newSeries);
  59. }
  60. break;
  61. }
  62. default: {
  63. newSeries = { datapoints: [], metric: metric.type, field: metric.field, props: props};
  64. for (i = 0; i < esAgg.buckets.length; i++) {
  65. bucket = esAgg.buckets[i];
  66. value = bucket[metric.id];
  67. if (value !== undefined) {
  68. if (value.normalized_value) {
  69. newSeries.datapoints.push([value.normalized_value, bucket.key]);
  70. } else {
  71. newSeries.datapoints.push([value.value, bucket.key]);
  72. }
  73. }
  74. }
  75. seriesList.push(newSeries);
  76. break;
  77. }
  78. }
  79. }
  80. };
  81. ElasticResponse.prototype.processAggregationDocs = function(esAgg, aggDef, target, table, props) {
  82. // add columns
  83. if (table.columns.length === 0) {
  84. for (let propKey of _.keys(props)) {
  85. table.addColumn({text: propKey, filterable: true});
  86. }
  87. table.addColumn({text: aggDef.field, filterable: true});
  88. }
  89. // helper func to add values to value array
  90. let addMetricValue = (values, metricName, value) => {
  91. table.addColumn({text: metricName});
  92. values.push(value);
  93. };
  94. for (let bucket of esAgg.buckets) {
  95. let values = [];
  96. for (let propValues of _.values(props)) {
  97. values.push(propValues);
  98. }
  99. // add bucket key (value)
  100. values.push(bucket.key);
  101. for (let metric of target.metrics) {
  102. switch (metric.type) {
  103. case "count": {
  104. addMetricValue(values, this._getMetricName(metric.type), bucket.doc_count);
  105. break;
  106. }
  107. case 'extended_stats': {
  108. for (var statName in metric.meta) {
  109. if (!metric.meta[statName]) {
  110. continue;
  111. }
  112. var stats = bucket[metric.id];
  113. // add stats that are in nested obj to top level obj
  114. stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;
  115. stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower;
  116. addMetricValue(values, this._getMetricName(statName), stats[statName]);
  117. }
  118. break;
  119. }
  120. default: {
  121. let metricName = this._getMetricName(metric.type);
  122. let otherMetrics = _.filter(target.metrics, {type: metric.type});
  123. // if more of the same metric type include field field name in property
  124. if (otherMetrics.length > 1) {
  125. metricName += ' ' + metric.field;
  126. }
  127. addMetricValue(values, metricName, bucket[metric.id].value);
  128. break;
  129. }
  130. }
  131. }
  132. table.rows.push(values);
  133. }
  134. };
  135. // This is quite complex
  136. // neeed to recurise down the nested buckets to build series
  137. ElasticResponse.prototype.processBuckets = function(aggs, target, seriesList, table, props, depth) {
  138. var bucket, aggDef, esAgg, aggId;
  139. var maxDepth = target.bucketAggs.length-1;
  140. for (aggId in aggs) {
  141. aggDef = _.find(target.bucketAggs, {id: aggId});
  142. esAgg = aggs[aggId];
  143. if (!aggDef) {
  144. continue;
  145. }
  146. if (depth === maxDepth) {
  147. if (aggDef.type === 'date_histogram') {
  148. this.processMetrics(esAgg, target, seriesList, props);
  149. } else {
  150. this.processAggregationDocs(esAgg, aggDef, target, table, props);
  151. }
  152. } else {
  153. for (var nameIndex in esAgg.buckets) {
  154. bucket = esAgg.buckets[nameIndex];
  155. props = _.clone(props);
  156. if (bucket.key !== void 0) {
  157. props[aggDef.field] = bucket.key;
  158. } else {
  159. props["filter"] = nameIndex;
  160. }
  161. if (bucket.key_as_string) {
  162. props[aggDef.field] = bucket.key_as_string;
  163. }
  164. this.processBuckets(bucket, target, seriesList, table, props, depth+1);
  165. }
  166. }
  167. }
  168. };
  169. ElasticResponse.prototype._getMetricName = function(metric) {
  170. var metricDef = _.find(queryDef.metricAggTypes, {value: metric});
  171. if (!metricDef) {
  172. metricDef = _.find(queryDef.extendedStats, {value: metric});
  173. }
  174. return metricDef ? metricDef.text : metric;
  175. };
  176. ElasticResponse.prototype._getSeriesName = function(series, target, metricTypeCount) {
  177. var metricName = this._getMetricName(series.metric);
  178. if (target.alias) {
  179. var regex = /\{\{([\s\S]+?)\}\}/g;
  180. return target.alias.replace(regex, function(match, g1, g2) {
  181. var group = g1 || g2;
  182. if (group.indexOf('term ') === 0) { return series.props[group.substring(5)]; }
  183. if (series.props[group] !== void 0) { return series.props[group]; }
  184. if (group === 'metric') { return metricName; }
  185. if (group === 'field') { return series.field; }
  186. return match;
  187. });
  188. }
  189. if (series.field && queryDef.isPipelineAgg(series.metric)) {
  190. var appliedAgg = _.find(target.metrics, { id: series.field });
  191. if (appliedAgg) {
  192. metricName += ' ' + queryDef.describeMetric(appliedAgg);
  193. } else {
  194. metricName = 'Unset';
  195. }
  196. } else if (series.field) {
  197. metricName += ' ' + series.field;
  198. }
  199. var propKeys = _.keys(series.props);
  200. if (propKeys.length === 0) {
  201. return metricName;
  202. }
  203. var name = '';
  204. for (var propName in series.props) {
  205. name += series.props[propName] + ' ';
  206. }
  207. if (metricTypeCount === 1) {
  208. return name.trim();
  209. }
  210. return name.trim() + ' ' + metricName;
  211. };
  212. ElasticResponse.prototype.nameSeries = function(seriesList, target) {
  213. var metricTypeCount = _.uniq(_.map(seriesList, 'metric')).length;
  214. var fieldNameCount = _.uniq(_.map(seriesList, 'field')).length;
  215. for (var i = 0; i < seriesList.length; i++) {
  216. var series = seriesList[i];
  217. series.target = this._getSeriesName(series, target, metricTypeCount, fieldNameCount);
  218. }
  219. };
  220. ElasticResponse.prototype.processHits = function(hits, seriesList) {
  221. var series = {target: 'docs', type: 'docs', datapoints: [], total: hits.total, filterable: true};
  222. var propName, hit, doc, i;
  223. for (i = 0; i < hits.hits.length; i++) {
  224. hit = hits.hits[i];
  225. doc = {
  226. _id: hit._id,
  227. _type: hit._type,
  228. _index: hit._index
  229. };
  230. if (hit._source) {
  231. for (propName in hit._source) {
  232. doc[propName] = hit._source[propName];
  233. }
  234. }
  235. for (propName in hit.fields) {
  236. doc[propName] = hit.fields[propName];
  237. }
  238. series.datapoints.push(doc);
  239. }
  240. seriesList.push(series);
  241. };
  242. ElasticResponse.prototype.trimDatapoints = function(aggregations, target) {
  243. var histogram = _.find(target.bucketAggs, { type: 'date_histogram'});
  244. var shouldDropFirstAndLast = histogram && histogram.settings && histogram.settings.trimEdges;
  245. if (shouldDropFirstAndLast) {
  246. var trim = histogram.settings.trimEdges;
  247. for (var prop in aggregations) {
  248. var points = aggregations[prop];
  249. if (points.datapoints.length > trim * 2) {
  250. points.datapoints = points.datapoints.slice(trim, points.datapoints.length - trim);
  251. }
  252. }
  253. }
  254. };
  255. ElasticResponse.prototype.getErrorFromElasticResponse = function(response, err) {
  256. var result: any = {};
  257. result.data = JSON.stringify(err, null, 4);
  258. if (err.root_cause && err.root_cause.length > 0 && err.root_cause[0].reason) {
  259. result.message = err.root_cause[0].reason;
  260. } else {
  261. result.message = err.reason || 'Unkown elatic error response';
  262. }
  263. if (response.$$config) {
  264. result.config = response.$$config;
  265. }
  266. return result;
  267. };
  268. ElasticResponse.prototype.getTimeSeries = function() {
  269. var seriesList = [];
  270. for (var i = 0; i < this.response.responses.length; i++) {
  271. var response = this.response.responses[i];
  272. if (response.error) {
  273. throw this.getErrorFromElasticResponse(this.response, response.error);
  274. }
  275. if (response.hits && response.hits.hits.length > 0) {
  276. this.processHits(response.hits, seriesList);
  277. }
  278. if (response.aggregations) {
  279. var aggregations = response.aggregations;
  280. var target = this.targets[i];
  281. var tmpSeriesList = [];
  282. var table = new TableModel();
  283. this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0);
  284. this.trimDatapoints(tmpSeriesList, target);
  285. this.nameSeries(tmpSeriesList, target);
  286. for (var y = 0; y < tmpSeriesList.length; y++) {
  287. seriesList.push(tmpSeriesList[y]);
  288. }
  289. if (table.rows.length > 0) {
  290. seriesList.push(table);
  291. }
  292. }
  293. }
  294. return { data: seriesList };
  295. };