diff --git a/public/app/plugins/datasource/elasticsearch/datasource.test.ts b/public/app/plugins/datasource/elasticsearch/datasource.test.ts index 887ff469840..78f622211cc 100644 --- a/public/app/plugins/datasource/elasticsearch/datasource.test.ts +++ b/public/app/plugins/datasource/elasticsearch/datasource.test.ts @@ -1021,6 +1021,54 @@ describe('enhanceDataFrame', () => { }); }); +describe('modifyQuery', () => { + let ds: ElasticDatasource; + beforeEach(() => { + ds = getTestContext().ds; + }); + describe('with empty query', () => { + let query: ElasticsearchQuery; + beforeEach(() => { + query = { query: '', refId: 'A' }; + }); + + it('should add the filter', () => { + expect(ds.modifyQuery(query, { type: 'ADD_FILTER', key: 'foo', value: 'bar' }).query).toBe('foo:"bar"'); + }); + + it('should add the negative filter', () => { + expect(ds.modifyQuery(query, { type: 'ADD_FILTER_OUT', key: 'foo', value: 'bar' }).query).toBe('-foo:"bar"'); + }); + + it('should do nothing on unknown type', () => { + expect(ds.modifyQuery(query, { type: 'unknown', key: 'foo', value: 'bar' }).query).toBe(query.query); + }); + }); + + describe('with non-empty query', () => { + let query: ElasticsearchQuery; + beforeEach(() => { + query = { query: 'test:"value"', refId: 'A' }; + }); + + it('should add the filter', () => { + expect(ds.modifyQuery(query, { type: 'ADD_FILTER', key: 'foo', value: 'bar' }).query).toBe( + 'test:"value" AND foo:"bar"' + ); + }); + + it('should add the negative filter', () => { + expect(ds.modifyQuery(query, { type: 'ADD_FILTER_OUT', key: 'foo', value: 'bar' }).query).toBe( + 'test:"value" AND -foo:"bar"' + ); + }); + + it('should do nothing on unknown type', () => { + expect(ds.modifyQuery(query, { type: 'unknown', key: 'foo', value: 'bar' }).query).toBe(query.query); + }); + }); +}); + const createElasticQuery = (): DataQueryRequest => { return { requestId: '', diff --git a/public/app/plugins/datasource/elasticsearch/datasource.ts b/public/app/plugins/datasource/elasticsearch/datasource.ts index e52fca2064f..4aa1df7f555 100644 --- a/public/app/plugins/datasource/elasticsearch/datasource.ts +++ b/public/app/plugins/datasource/elasticsearch/datasource.ts @@ -952,6 +952,27 @@ export class ElasticDatasource return false; } + + modifyQuery(query: ElasticsearchQuery, action: { type: string; key: string; value: string }): ElasticsearchQuery { + let expression = query.query ?? ''; + switch (action.type) { + case 'ADD_FILTER': { + if (expression.length > 0) { + expression += ' AND '; + } + expression += `${action.key}:"${action.value}"`; + break; + } + case 'ADD_FILTER_OUT': { + if (expression.length > 0) { + expression += ' AND '; + } + expression += `-${action.key}:"${action.value}"`; + break; + } + } + return { ...query, query: expression }; + } } /**