Elasticsearch: Added `modifyQuery` method to add filters in Explore (#52313)

pull/51912/head
Sven Grossmann 3 years ago committed by GitHub
parent a2512dd1c7
commit 0531e4efc0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 48
      public/app/plugins/datasource/elasticsearch/datasource.test.ts
  2. 21
      public/app/plugins/datasource/elasticsearch/datasource.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<ElasticsearchQuery> => {
return {
requestId: '',

@ -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 };
}
}
/**

Loading…
Cancel
Save