elastic_response.js 10 KB

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