-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathdataReportHelpers.ts
260 lines (246 loc) · 7.79 KB
/
dataReportHelpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import { DATA_REPORT_CONFIG } from './constants';
import esb from 'elastic-builder';
import moment from 'moment';
import converter from 'json-2-csv';
import _ from 'lodash';
export var metaData = {
saved_search_id: <string>null,
report_format: <string>null,
start: <string>null,
end: <string>null,
fields: <string>null,
type: <string>null,
timeFieldName: <string>null,
sorting: <string>null,
fields_exist: <boolean>false,
selectedFields: <any>[],
paternName: <string>null,
filters: <any>[],
dateFields: <any>[],
};
// Get the selected columns by the user.
export const getSelectedFields = async (columns) => {
const selectedFields = [];
for (let column of columns) {
if (column !== '_source') {
metaData.fields_exist = true;
selectedFields.push(column);
} else {
selectedFields.push('_source');
}
}
metaData.selectedFields = selectedFields;
};
//Build the OpenSearch query from the meta data
// is_count is set to 1 if we building the count query but 0 if we building the fetch data query
export const buildQuery = (report, is_count) => {
let requestBody = esb.boolQuery();
const filters = report._source.filters;
for (let item of JSON.parse(filters).filter) {
if (item.meta.disabled === false) {
switch (item.meta.negate) {
case false:
switch (item.meta.type) {
case 'phrase':
requestBody.must(
esb.matchPhraseQuery(item.meta.key, item.meta.params.query)
);
break;
case 'exists':
requestBody.must(esb.existsQuery(item.meta.key));
break;
case 'phrases':
if (item.meta.value.indexOf(',') > -1) {
const valueSplit = item.meta.value.split(', ');
for (const [key, incr] of valueSplit.entries()) {
requestBody.should(esb.matchPhraseQuery(item.meta.key, incr));
}
} else {
requestBody.should(
esb.matchPhraseQuery(item.meta.key, item.meta.params.query)
);
}
requestBody.minimumShouldMatch(1);
break;
}
break;
case true:
switch (item.meta.type) {
case 'phrase':
requestBody.mustNot(
esb.matchPhraseQuery(item.meta.key, item.meta.params.query)
);
break;
case 'exists':
requestBody.mustNot(esb.existsQuery(item.meta.key));
break;
case 'phrases':
if (item.meta.value.indexOf(',') > -1) {
const valueSplit = item.meta.value.split(', ');
for (const [key, incr] of valueSplit.entries()) {
requestBody.should(esb.matchPhraseQuery(item.meta.key, incr));
}
} else {
requestBody.should(
esb.matchPhraseQuery(item.meta.key, item.meta.params.query)
);
}
requestBody.minimumShouldMatch(1);
break;
}
break;
}
}
}
//search part
let searchQuery = JSON.parse(filters)
.query.query.replace(/ and /g, ' AND ')
.replace(/ or /g, ' OR ')
.replace(/ not /g, ' NOT ');
if (searchQuery) {
requestBody.must(esb.queryStringQuery(searchQuery));
}
if (report._source.timeFieldName && report._source.timeFieldName.length > 0) {
requestBody.must(
esb
.rangeQuery(report._source.timeFieldName)
.format('epoch_millis')
.gte(report._source.start - 1)
.lte(report._source.end + 1)
);
}
if (is_count) {
return esb.requestBodySearch().query(requestBody);
}
//Add the Sort to the query
let reqBody = esb.requestBodySearch().query(requestBody).version(true);
if (report._source.sorting.length > 0) {
if (report._source.sorting.length === 1)
reqBody.sort(
esb.sort(report._source.sorting[0][0], report._source.sorting[0][1])
);
else
reqBody.sort(
esb.sort(report._source.sorting[0], report._source.sorting[1])
);
}
//get the selected fields only
if (report._source.fields_exist) {
reqBody.source({ includes: report._source.selectedFields });
}
return reqBody;
};
// Fetch the data from OpenSearch
export const getOpenSearchData = (arrayHits, report, params) => {
let hits: any = [];
for (let valueRes of arrayHits) {
for (let data of valueRes.hits) {
const fields = data.fields;
//get all the fields of type date and fromat them to excel format
for (let dateType of report._source.dateFields) {
if (data._source[dateType]) {
data._source[dateType] = moment(fields[dateType][0]).format(
DATA_REPORT_CONFIG.excelDateFormat
);
}
}
delete data['fields'];
if (report._source.fields_exist === true) {
let result = traverse(data._source, report._source.selectedFields);
hits.push(params.excel ? sanitize(result) : result);
} else {
hits.push(params.excel ? sanitize(data) : data);
}
// Truncate to expected limit size
if (hits.length >= params.limit) {
return hits;
}
}
}
return hits;
};
//Convert the data to Csv format
export const convertToCSV = async (dataset) => {
let convertedData: any = [];
const options = {
delimiter: { field: ',', eol: '\n' },
emptyFieldValue: ' ',
};
await converter.json2csvAsync(dataset[0], options).then((csv) => {
convertedData = csv;
});
return convertedData;
};
function flattenHits(hits, result = {}, prefix = '') {
for (const [key, value] of Object.entries(hits)) {
if (!hits.hasOwnProperty(key)) continue;
if (
value != null &&
typeof value === 'object' &&
!Array.isArray(value) &&
Object.keys(value).length > 0
) {
flattenHits(value, result, prefix + key + '.');
} else {
result[prefix + key] = value;
}
}
return result;
}
//Return only the selected fields
function traverse(data, keys, result = {}) {
data = flattenHits(data);
const sourceKeys = Object.keys(data);
keys.forEach((key) => {
const value = _.get(data, key, undefined);
if (value !== undefined) result[key] = value;
else {
Object.keys(data)
.filter((sourceKey) => sourceKey.startsWith(key + '.'))
.forEach((sourceKey) => (result[sourceKey] = data[sourceKey]));
}
});
return result;
}
/**
* Escape special characters if field value prefixed with.
* This is intend to avoid CSV injection in Microsoft Excel.
* @param doc document
*/
function sanitize(doc: any) {
for (const field in doc) {
if (
doc[field].toString().startsWith('+') ||
(doc[field].toString().startsWith('-') && typeof doc[field] !== "number") ||
doc[field].toString().startsWith('=') ||
doc[field].toString().startsWith('@')
) {
doc[field] = "'" + doc[field];
}
}
return doc;
}