transformers.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import _ from 'lodash';
  2. import flatten from '../../../core/utils/flatten';
  3. import TimeSeries from '../../../core/time_series2';
  4. import TableModel from '../../../core/table_model';
  5. var transformers = {};
  6. transformers['timeseries_to_rows'] = {
  7. description: 'Time series to rows',
  8. getColumns: function() {
  9. return [];
  10. },
  11. transform: function(data, panel, model) {
  12. model.columns = [
  13. {text: 'Time', type: 'date'},
  14. {text: 'Metric'},
  15. {text: 'Value'},
  16. ];
  17. for (var i = 0; i < data.length; i++) {
  18. var series = data[i];
  19. for (var y = 0; y < series.datapoints.length; y++) {
  20. var dp = series.datapoints[y];
  21. model.rows.push([dp[1], series.target, dp[0]]);
  22. }
  23. }
  24. },
  25. };
  26. transformers['timeseries_to_columns'] = {
  27. description: 'Time series to columns',
  28. getColumns: function() {
  29. return [];
  30. },
  31. transform: function(data, panel, model) {
  32. model.columns.push({text: 'Time', type: 'date'});
  33. // group by time
  34. var points = {};
  35. for (let i = 0; i < data.length; i++) {
  36. var series = data[i];
  37. model.columns.push({text: series.target});
  38. for (var y = 0; y < series.datapoints.length; y++) {
  39. var dp = series.datapoints[y];
  40. var timeKey = dp[1].toString();
  41. if (!points[timeKey]) {
  42. points[timeKey] = {time: dp[1]};
  43. points[timeKey][i] = dp[0];
  44. } else {
  45. points[timeKey][i] = dp[0];
  46. }
  47. }
  48. }
  49. for (var time in points) {
  50. var point = points[time];
  51. var values = [point.time];
  52. for (let i = 0; i < data.length; i++) {
  53. var value = point[i];
  54. values.push(value);
  55. }
  56. model.rows.push(values);
  57. }
  58. }
  59. };
  60. transformers['timeseries_aggregations'] = {
  61. description: 'Time series aggregations',
  62. getColumns: function() {
  63. return [
  64. {text: 'Avg', value: 'avg'},
  65. {text: 'Min', value: 'min'},
  66. {text: 'Max', value: 'max'},
  67. {text: 'Total', value: 'total'},
  68. {text: 'Current', value: 'current'},
  69. {text: 'Count', value: 'count'},
  70. ];
  71. },
  72. transform: function(data, panel, model) {
  73. var i, y;
  74. model.columns.push({text: 'Metric'});
  75. for (i = 0; i < panel.columns.length; i++) {
  76. model.columns.push({text: panel.columns[i].text});
  77. }
  78. for (i = 0; i < data.length; i++) {
  79. var series = new TimeSeries({
  80. datapoints: data[i].datapoints,
  81. alias: data[i].target,
  82. });
  83. series.getFlotPairs('connected');
  84. var cells = [series.alias];
  85. for (y = 0; y < panel.columns.length; y++) {
  86. cells.push(series.stats[panel.columns[y].value]);
  87. }
  88. model.rows.push(cells);
  89. }
  90. }
  91. };
  92. transformers['annotations'] = {
  93. description: 'Annotations',
  94. getColumns: function() {
  95. return [];
  96. },
  97. transform: function(data, panel, model) {
  98. model.columns.push({text: 'Time', type: 'date'});
  99. model.columns.push({text: 'Title'});
  100. model.columns.push({text: 'Text'});
  101. model.columns.push({text: 'Tags'});
  102. if (!data || !data.annotations || data.annotations.length === 0) {
  103. return;
  104. }
  105. for (var i = 0; i < data.annotations.length; i++) {
  106. var evt = data.annotations[i];
  107. model.rows.push([evt.time, evt.title, evt.text, evt.tags]);
  108. }
  109. }
  110. };
  111. transformers['table'] = {
  112. description: 'Table',
  113. getColumns: function(data) {
  114. if (!data || data.length === 0) {
  115. return [];
  116. }
  117. // Single query returns data columns as is
  118. if (data.length === 1) {
  119. return [...data[0].columns];
  120. }
  121. // Track column indexes: name -> index
  122. const columnNames = {};
  123. // Union of all columns
  124. const columns = data.reduce((acc, series) => {
  125. series.columns.forEach(col => {
  126. const { text } = col;
  127. if (columnNames[text] === undefined) {
  128. columnNames[text] = acc.length;
  129. acc.push(col);
  130. }
  131. });
  132. return acc;
  133. }, []);
  134. return columns;
  135. },
  136. transform: function(data, panel, model) {
  137. if (!data || data.length === 0) {
  138. return;
  139. }
  140. const noTableIndex = _.findIndex(data, d => d.type !== 'table');
  141. if (noTableIndex > -1) {
  142. throw {message: `Result of query #${String.fromCharCode(65 + noTableIndex)} is not in table format, try using another transform.`};
  143. }
  144. // Single query returns data columns and rows as is
  145. if (data.length === 1) {
  146. model.columns = [...data[0].columns];
  147. model.rows = [...data[0].rows];
  148. return;
  149. }
  150. // Track column indexes of union: name -> index
  151. const columnNames = {};
  152. // Union of all non-value columns
  153. const columnsUnion = data.reduce((acc, series) => {
  154. series.columns.forEach(col => {
  155. const { text } = col;
  156. if (columnNames[text] === undefined) {
  157. columnNames[text] = acc.length;
  158. acc.push(col);
  159. }
  160. });
  161. return acc;
  162. }, []);
  163. // Map old column index to union index per series, e.g.,
  164. // given columnNames {A: 0, B: 1} and
  165. // data [{columns: [{ text: 'A' }]}, {columns: [{ text: 'B' }]}] => [[0], [1]]
  166. const columnIndexMapper = data.map(series =>
  167. series.columns.map(col => columnNames[col.text])
  168. );
  169. // Flatten rows of all series and adjust new column indexes
  170. const flattenedRows = data.reduce((acc, series, seriesIndex) => {
  171. const mapper = columnIndexMapper[seriesIndex];
  172. series.rows.forEach(row => {
  173. const alteredRow = [];
  174. // Shifting entries according to index mapper
  175. mapper.forEach((to, from) => {
  176. alteredRow[to] = row[from];
  177. });
  178. acc.push(alteredRow);
  179. });
  180. return acc;
  181. }, []);
  182. // Returns true if both rows have matching non-empty fields as well as matching
  183. // indexes where one field is empty and the other is not
  184. function areRowsMatching(columns, row, otherRow) {
  185. let foundFieldToMatch = false;
  186. for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {
  187. if (row[columnIndex] !== undefined && otherRow[columnIndex] !== undefined) {
  188. if (row[columnIndex] !== otherRow[columnIndex]) {
  189. return false;
  190. }
  191. } else if (row[columnIndex] === undefined || otherRow[columnIndex] === undefined) {
  192. foundFieldToMatch = true;
  193. }
  194. }
  195. return foundFieldToMatch;
  196. }
  197. // Merge rows that have same values for columns
  198. const mergedRows = {};
  199. const compactedRows = flattenedRows.reduce((acc, row, rowIndex) => {
  200. if (!mergedRows[rowIndex]) {
  201. // Look from current row onwards
  202. let offset = rowIndex + 1;
  203. // More than one row can be merged into current row
  204. while (offset < flattenedRows.length) {
  205. // Find next row that could be merged
  206. const match = _.findIndex(flattenedRows,
  207. otherRow => areRowsMatching(columnsUnion, row, otherRow),
  208. offset);
  209. if (match > -1) {
  210. const matchedRow = flattenedRows[match];
  211. // Merge values from match into current row if there is a gap in the current row
  212. for (let columnIndex = 0; columnIndex < columnsUnion.length; columnIndex++) {
  213. if (row[columnIndex] === undefined && matchedRow[columnIndex] !== undefined) {
  214. row[columnIndex] = matchedRow[columnIndex];
  215. }
  216. }
  217. // Dont visit this row again
  218. mergedRows[match] = matchedRow;
  219. // Keep looking for more rows to merge
  220. offset = match + 1;
  221. } else {
  222. // No match found, stop looking
  223. break;
  224. }
  225. }
  226. acc.push(row);
  227. }
  228. return acc;
  229. }, []);
  230. model.columns = columnsUnion;
  231. model.rows = compactedRows;
  232. }
  233. };
  234. transformers['json'] = {
  235. description: 'JSON Data',
  236. getColumns: function(data) {
  237. if (!data || data.length === 0) {
  238. return [];
  239. }
  240. var names: any = {};
  241. for (var i = 0; i < data.length; i++) {
  242. var series = data[i];
  243. if (series.type !== 'docs') {
  244. continue;
  245. }
  246. // only look at 100 docs
  247. var maxDocs = Math.min(series.datapoints.length, 100);
  248. for (var y = 0; y < maxDocs; y++) {
  249. var doc = series.datapoints[y];
  250. var flattened = flatten(doc, null);
  251. for (var propName in flattened) {
  252. names[propName] = true;
  253. }
  254. }
  255. }
  256. return _.map(names, function(value, key) {
  257. return {text: key, value: key};
  258. });
  259. },
  260. transform: function(data, panel, model) {
  261. var i, y, z;
  262. for (let column of panel.columns) {
  263. var tableCol: any = {text: column.text};
  264. // if filterable data then set columns to filterable
  265. if (data.length > 0 && data[0].filterable) {
  266. tableCol.filterable = true;
  267. }
  268. model.columns.push(tableCol);
  269. }
  270. if (model.columns.length === 0) {
  271. model.columns.push({text: 'JSON'});
  272. }
  273. for (i = 0; i < data.length; i++) {
  274. var series = data[i];
  275. for (y = 0; y < series.datapoints.length; y++) {
  276. var dp = series.datapoints[y];
  277. var values = [];
  278. if (_.isObject(dp) && panel.columns.length > 0) {
  279. var flattened = flatten(dp, null);
  280. for (z = 0; z < panel.columns.length; z++) {
  281. values.push(flattened[panel.columns[z].value]);
  282. }
  283. } else {
  284. values.push(JSON.stringify(dp));
  285. }
  286. model.rows.push(values);
  287. }
  288. }
  289. }
  290. };
  291. function transformDataToTable(data, panel) {
  292. var model = new TableModel();
  293. if (!data || data.length === 0) {
  294. return model;
  295. }
  296. var transformer = transformers[panel.transform];
  297. if (!transformer) {
  298. throw {message: 'Transformer ' + panel.transform + ' not found'};
  299. }
  300. transformer.transform(data, panel, model);
  301. return model;
  302. }
  303. export {transformers, transformDataToTable};