elastic_response.ts 11 KB

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