Commit 4c9cb415 by Andrej Ocenas Committed by David

Elastic: Fix parsing for millisecond number timestamps (#20290)

* Stop parsing 'field'

* Remove time field from query for docs queries

* Test refactor to test all versions

* Fix tests
parent c43aa348
...@@ -58,7 +58,7 @@ describe('Apending DataFrame', () => { ...@@ -58,7 +58,7 @@ describe('Apending DataFrame', () => {
]); ]);
// Add a time value that has an array type // Add a time value that has an array type
frame.add({ time: [300] }); frame.add({ time: 300 });
expect(frame.toArray()).toEqual([ expect(frame.toArray()).toEqual([
{ time: 100, name: 'a', value: 1, value2: null }, // 1 { time: 100, name: 'a', value: 1, value2: null }, // 1
{ time: 200, name: 'BB', value: 20, value2: null }, // 2 { time: 200, name: 'BB', value: 20, value2: null }, // 2
......
...@@ -231,11 +231,6 @@ export class MutableDataFrame<T = any> implements DataFrame, MutableVector<T> { ...@@ -231,11 +231,6 @@ export class MutableDataFrame<T = any> implements DataFrame, MutableVector<T> {
field.parse = makeFieldParser(val, field); field.parse = makeFieldParser(val, field);
} }
val = field.parse(val); val = field.parse(val);
} else if (field.type === FieldType.time && isArray(val)) {
if (!field.parse) {
field.parse = (val: any[]) => val[0] || undefined;
}
val = field.parse(val);
} }
if (val === undefined) { if (val === undefined) {
......
...@@ -424,40 +424,26 @@ export class ElasticResponse { ...@@ -424,40 +424,26 @@ export class ElasticResponse {
throw this.getErrorFromElasticResponse(this.response, response.error); throw this.getErrorFromElasticResponse(this.response, response.error);
} }
const hits = response.hits; // We keep a list of all props so that we can create all the fields in the dataFrame, this can lead
// to wide sparse dataframes in case the scheme is different per document.
let propNames: string[] = []; let propNames: string[] = [];
let propName, hit, doc: any, i;
for (i = 0; i < hits.hits.length; i++) { for (const hit of response.hits.hits) {
hit = hits.hits[i];
const flattened = hit._source ? flatten(hit._source, null) : {}; const flattened = hit._source ? flatten(hit._source, null) : {};
doc = {}; const doc = {
doc[this.targets[0].timeField] = null;
doc = {
...doc,
_id: hit._id, _id: hit._id,
_type: hit._type, _type: hit._type,
_index: hit._index, _index: hit._index,
_source: { ...flattened },
...flattened, ...flattened,
}; };
// Note: the order of for...in is arbitrary amd implementation dependant for (const propName of Object.keys(doc)) {
// and should probably not be relied upon.
for (propName in hit.fields) {
if (propNames.indexOf(propName) === -1) { if (propNames.indexOf(propName) === -1) {
propNames.push(propName); propNames.push(propName);
} }
doc[propName] = hit.fields[propName];
} }
for (propName in doc) {
if (propNames.indexOf(propName) === -1) {
propNames.push(propName);
}
}
doc._source = { ...flattened };
docs.push(doc); docs.push(doc);
} }
...@@ -468,9 +454,7 @@ export class ElasticResponse { ...@@ -468,9 +454,7 @@ export class ElasticResponse {
series.addField({ series.addField({
name: this.targets[0].timeField, name: this.targets[0].timeField,
type: FieldType.time, type: FieldType.time,
}).parse = (v: any) => { });
return v[0] || '';
};
if (logMessageField) { if (logMessageField) {
series.addField({ series.addField({
......
...@@ -5,7 +5,7 @@ export class ElasticQueryBuilder { ...@@ -5,7 +5,7 @@ export class ElasticQueryBuilder {
timeField: string; timeField: string;
esVersion: number; esVersion: number;
constructor(options: any) { constructor(options: { timeField: string; esVersion: number }) {
this.timeField = options.timeField; this.timeField = options.timeField;
this.esVersion = options.esVersion; this.esVersion = options.esVersion;
} }
...@@ -129,11 +129,6 @@ export class ElasticQueryBuilder { ...@@ -129,11 +129,6 @@ export class ElasticQueryBuilder {
} }
query.script_fields = {}; query.script_fields = {};
if (this.esVersion < 5) {
query.fielddata_fields = [this.timeField];
} else {
query.docvalue_fields = [this.timeField];
}
return query; return query;
} }
......
...@@ -871,9 +871,6 @@ describe('ElasticResponse', () => { ...@@ -871,9 +871,6 @@ describe('ElasticResponse', () => {
host: 'djisaodjsoad', host: 'djisaodjsoad',
message: 'hello, i am a message', message: 'hello, i am a message',
}, },
fields: {
'@timestamp': ['2019-06-24T09:51:19.765Z'],
},
}, },
{ {
_id: 'kdospaidopa', _id: 'kdospaidopa',
...@@ -884,9 +881,6 @@ describe('ElasticResponse', () => { ...@@ -884,9 +881,6 @@ describe('ElasticResponse', () => {
host: 'dsalkdakdop', host: 'dsalkdakdop',
message: 'hello, i am also message', message: 'hello, i am also message',
}, },
fields: {
'@timestamp': ['2019-06-24T09:52:19.765Z'],
},
}, },
], ],
}, },
......
import { ElasticQueryBuilder } from '../query_builder'; import { ElasticQueryBuilder } from '../query_builder';
describe('ElasticQueryBuilder', () => { describe('ElasticQueryBuilder', () => {
let builder: any; const builder = new ElasticQueryBuilder({ timeField: '@timestamp', esVersion: 2 });
const builder5x = new ElasticQueryBuilder({ timeField: '@timestamp', esVersion: 5 });
const builder56 = new ElasticQueryBuilder({ timeField: '@timestamp', esVersion: 56 });
const builder6x = new ElasticQueryBuilder({ timeField: '@timestamp', esVersion: 60 });
const builder7x = new ElasticQueryBuilder({ timeField: '@timestamp', esVersion: 70 });
beforeEach(() => { const allBuilders = [builder, builder5x, builder56, builder6x, builder7x];
builder = new ElasticQueryBuilder({ timeField: '@timestamp' });
});
it('with defaults', () => { allBuilders.forEach(builder => {
describe(`version ${builder.esVersion}`, () => {
it('should return query with defaults', () => {
const query = builder.build({ const query = builder.build({
metrics: [{ type: 'Count', id: '0' }], metrics: [{ type: 'Count', id: '0' }],
timeField: '@timestamp', timeField: '@timestamp',
...@@ -18,22 +22,6 @@ describe('ElasticQueryBuilder', () => { ...@@ -18,22 +22,6 @@ describe('ElasticQueryBuilder', () => {
expect(query.aggs['1'].date_histogram.extended_bounds.min).toBe('$timeFrom'); expect(query.aggs['1'].date_histogram.extended_bounds.min).toBe('$timeFrom');
}); });
it('with defaults on es5.x', () => {
const builder5x = new ElasticQueryBuilder({
timeField: '@timestamp',
esVersion: 5,
});
const query = builder5x.build({
metrics: [{ type: 'Count', id: '0' }],
timeField: '@timestamp',
bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '1' }],
});
expect(query.query.bool.filter[0].range['@timestamp'].gte).toBe('$timeFrom');
expect(query.aggs['1'].date_histogram.extended_bounds.min).toBe('$timeFrom');
});
it('with multiple bucket aggs', () => { it('with multiple bucket aggs', () => {
const query = builder.build({ const query = builder.build({
metrics: [{ type: 'count', id: '1' }], metrics: [{ type: 'count', id: '1' }],
...@@ -55,45 +43,15 @@ describe('ElasticQueryBuilder', () => { ...@@ -55,45 +43,15 @@ describe('ElasticQueryBuilder', () => {
bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '2' }], bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '2' }],
}, },
100, 100,
1000 '1000'
); );
const aggs = query.aggs['2'].aggs; const aggs = query.aggs['2'].aggs;
expect(aggs['1'].avg.field).toBe('@value'); expect(aggs['1'].avg.field).toBe('@value');
}); });
it('with term agg and order by term', () => { it('term agg and order by term', () => {
const query = builder.build( const target = {
{
metrics: [
{ type: 'count', id: '1' },
{ type: 'avg', field: '@value', id: '5' },
],
bucketAggs: [
{
type: 'terms',
field: '@host',
settings: { size: 5, order: 'asc', orderBy: '_term' },
id: '2',
},
{ type: 'date_histogram', field: '@timestamp', id: '3' },
],
},
100,
1000
);
const firstLevel = query.aggs['2'];
expect(firstLevel.terms.order._term).toBe('asc');
});
it('with term agg and order by term on es6.x', () => {
const builder6x = new ElasticQueryBuilder({
timeField: '@timestamp',
esVersion: 60,
});
const query = builder6x.build(
{
metrics: [ metrics: [
{ type: 'count', id: '1' }, { type: 'count', id: '1' },
{ type: 'avg', field: '@value', id: '5' }, { type: 'avg', field: '@value', id: '5' },
...@@ -107,14 +65,14 @@ describe('ElasticQueryBuilder', () => { ...@@ -107,14 +65,14 @@ describe('ElasticQueryBuilder', () => {
}, },
{ type: 'date_histogram', field: '@timestamp', id: '3' }, { type: 'date_histogram', field: '@timestamp', id: '3' },
], ],
}, };
100, const query = builder.build(target, 100, '1000');
// @ts-ignore
1000
);
const firstLevel = query.aggs['2']; const firstLevel = query.aggs['2'];
if (builder.esVersion >= 60) {
expect(firstLevel.terms.order._key).toBe('asc'); expect(firstLevel.terms.order._key).toBe('asc');
} else {
expect(firstLevel.terms.order._term).toBe('asc');
}
}); });
it('with term agg and order by metric agg', () => { it('with term agg and order by metric agg', () => {
...@@ -135,7 +93,7 @@ describe('ElasticQueryBuilder', () => { ...@@ -135,7 +93,7 @@ describe('ElasticQueryBuilder', () => {
], ],
}, },
100, 100,
1000 '1000'
); );
const firstLevel = query.aggs['2']; const firstLevel = query.aggs['2'];
...@@ -161,7 +119,7 @@ describe('ElasticQueryBuilder', () => { ...@@ -161,7 +119,7 @@ describe('ElasticQueryBuilder', () => {
bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '3' }], bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '3' }],
}, },
100, 100,
1000 '1000'
); );
const firstLevel = query.aggs['3']; const firstLevel = query.aggs['3'];
...@@ -191,41 +149,48 @@ describe('ElasticQueryBuilder', () => { ...@@ -191,41 +149,48 @@ describe('ElasticQueryBuilder', () => {
expect(query.aggs['2'].aggs['4'].date_histogram.field).toBe('@timestamp'); expect(query.aggs['2'].aggs['4'].date_histogram.field).toBe('@timestamp');
}); });
it('with filters aggs on es5.x', () => { it('should return correct query for raw_document metric', () => {
const builder5x = new ElasticQueryBuilder({ const target = {
timeField: '@timestamp', metrics: [{ type: 'raw_document', id: '1', settings: {} }],
esVersion: 5,
});
const query = builder5x.build({
metrics: [{ type: 'count', id: '1' }],
timeField: '@timestamp', timeField: '@timestamp',
bucketAggs: [ bucketAggs: [] as any[],
};
const query = builder.build(target);
expect(query).toMatchObject({
size: 500,
query: {
bool: {
filter: [
{ {
id: '2', range: {
type: 'filters', '@timestamp': {
settings: { format: 'epoch_millis',
filters: [{ query: '@metric:cpu' }, { query: '@metric:logins.count' }], gte: '$timeFrom',
lte: '$timeTo',
},
},
},
{
query_string: {
analyze_wildcard: true,
query: undefined,
}, },
}, },
{ type: 'date_histogram', field: '@timestamp', id: '4' },
], ],
},
},
sort: {
'@timestamp': {
order: 'desc',
unmapped_type: 'boolean',
},
},
script_fields: {},
}); });
expect(query.aggs['2'].filters.filters['@metric:cpu'].query_string.query).toBe('@metric:cpu');
expect(query.aggs['2'].filters.filters['@metric:logins.count'].query_string.query).toBe('@metric:logins.count');
expect(query.aggs['2'].aggs['4'].date_histogram.field).toBe('@timestamp');
});
it('with raw_document metric', () => {
const query = builder.build({
metrics: [{ type: 'raw_document', id: '1', settings: {} }],
timeField: '@timestamp',
bucketAggs: [],
}); });
expect(query.size).toBe(500); it('should set query size from settings when raw_documents', () => {
});
it('with raw_document metric size set', () => {
const query = builder.build({ const query = builder.build({
metrics: [{ type: 'raw_document', id: '1', settings: { size: 1337 } }], metrics: [{ type: 'raw_document', id: '1', settings: { size: 1337 } }],
timeField: '@timestamp', timeField: '@timestamp',
...@@ -487,87 +452,56 @@ describe('ElasticQueryBuilder', () => { ...@@ -487,87 +452,56 @@ describe('ElasticQueryBuilder', () => {
expect(query.query.bool.filter[5].bool.must_not.regexp['key6']).toBe('value6'); expect(query.query.bool.filter[5].bool.must_not.regexp['key6']).toBe('value6');
}); });
// terms query ES<6.0 - check ordering for _term and doc_type describe('getTermsQuery', () => {
function testGetTermsQuery(queryDef: any) {
const query = builder.getTermsQuery(queryDef);
return query.aggs['1'].terms.order;
}
it('getTermsQuery(default case) es<6.0 should set asc sorting on _term', () => { function checkSort(order: any, expected: string) {
const query = builder.getTermsQuery({}); if (builder.esVersion < 60) {
expect(query.aggs['1'].terms.order._term).toBe('asc'); expect(order._term).toBe(expected);
expect(query.aggs['1'].terms.order._key).toBeUndefined(); expect(order._key).toBeUndefined();
expect(query.aggs['1'].terms.order._count).toBeUndefined(); } else {
expect(order._term).toBeUndefined();
expect(order._key).toBe(expected);
}
}
it('should set correct default sorting', () => {
const order = testGetTermsQuery({});
checkSort(order, 'asc');
expect(order._count).toBeUndefined();
}); });
it('getTermsQuery(order:desc) es<6.0 should set desc sorting on _term', () => { it('should set correct explicit sorting', () => {
const query = builder.getTermsQuery({ order: 'desc' }); const order = testGetTermsQuery({ order: 'desc' });
expect(query.aggs['1'].terms.order._term).toBe('desc'); console.log({ order });
expect(query.aggs['1'].terms.order._key).toBeUndefined(); checkSort(order, 'desc');
expect(query.aggs['1'].terms.order._count).toBeUndefined(); expect(order._count).toBeUndefined();
}); });
it('getTermsQuery(orderBy:doc_count) es<6.0 should set desc sorting on _count', () => { it('getTermsQuery(orderBy:doc_count) should set desc sorting on _count', () => {
const query = builder.getTermsQuery({ orderBy: 'doc_count' }); const query = builder.getTermsQuery({ orderBy: 'doc_count' });
expect(query.aggs['1'].terms.order._term).toBeUndefined(); expect(query.aggs['1'].terms.order._term).toBeUndefined();
expect(query.aggs['1'].terms.order._key).toBeUndefined(); expect(query.aggs['1'].terms.order._key).toBeUndefined();
expect(query.aggs['1'].terms.order._count).toBe('desc'); expect(query.aggs['1'].terms.order._count).toBe('desc');
}); });
it('getTermsQuery(orderBy:doc_count, order:asc) es<6.0 should set asc sorting on _count', () => { it('getTermsQuery(orderBy:doc_count, order:asc) should set asc sorting on _count', () => {
const query = builder.getTermsQuery({ orderBy: 'doc_count', order: 'asc' }); const query = builder.getTermsQuery({ orderBy: 'doc_count', order: 'asc' });
expect(query.aggs['1'].terms.order._term).toBeUndefined(); expect(query.aggs['1'].terms.order._term).toBeUndefined();
expect(query.aggs['1'].terms.order._key).toBeUndefined(); expect(query.aggs['1'].terms.order._key).toBeUndefined();
expect(query.aggs['1'].terms.order._count).toBe('asc'); expect(query.aggs['1'].terms.order._count).toBe('asc');
}); });
// terms query ES>=6.0 - check ordering for _key and doc_type
it('getTermsQuery(default case) es6.x should set asc sorting on _key', () => {
const builder6x = new ElasticQueryBuilder({
timeField: '@timestamp',
esVersion: 60,
});
const query = builder6x.getTermsQuery({});
expect(query.aggs['1'].terms.order._term).toBeUndefined();
expect(query.aggs['1'].terms.order._key).toBe('asc');
expect(query.aggs['1'].terms.order._count).toBeUndefined();
});
it('getTermsQuery(order:desc) es6.x should set desc sorting on _key', () => {
const builder6x = new ElasticQueryBuilder({
timeField: '@timestamp',
esVersion: 60,
});
const query = builder6x.getTermsQuery({ order: 'desc' });
expect(query.aggs['1'].terms.order._term).toBeUndefined();
expect(query.aggs['1'].terms.order._key).toBe('desc');
expect(query.aggs['1'].terms.order._count).toBeUndefined();
});
it('getTermsQuery(orderBy:doc_count) es6.x should set desc sorting on _count', () => {
const builder6x = new ElasticQueryBuilder({
timeField: '@timestamp',
esVersion: 60,
});
const query = builder6x.getTermsQuery({ orderBy: 'doc_count' });
expect(query.aggs['1'].terms.order._term).toBeUndefined();
expect(query.aggs['1'].terms.order._key).toBeUndefined();
expect(query.aggs['1'].terms.order._count).toBe('desc');
}); });
it('getTermsQuery(orderBy:doc_count, order:asc) es6.x should set asc sorting on _count', () => {
const builder6x = new ElasticQueryBuilder({
timeField: '@timestamp',
esVersion: 60,
});
const query = builder6x.getTermsQuery({ orderBy: 'doc_count', order: 'asc' });
expect(query.aggs['1'].terms.order._term).toBeUndefined();
expect(query.aggs['1'].terms.order._key).toBeUndefined();
expect(query.aggs['1'].terms.order._count).toBe('asc');
});
// Logs query
it('getTermsQuery should request documents and date histogram', () => { it('getTermsQuery should request documents and date histogram', () => {
const query = builder.getLogsQuery({}); const query = builder.getLogsQuery({}, '');
console.log({ query });
expect(query).toHaveProperty('query.bool.filter'); expect(query).toHaveProperty('query.bool.filter');
expect(query.aggs['2']).toHaveProperty('date_histogram'); expect(query.aggs['2']).toHaveProperty('date_histogram');
}); });
});
});
}); });
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment