elastic_response.ts 11 KB

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