[Search] Fix search query builder to generate wildcard query for keyword fields (#140629)

This commit is contained in:
Michael Dokolin 2022-09-16 11:37:20 +02:00 committed by GitHub
parent 0bfc3fd41a
commit 6932b712bc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 50 additions and 13 deletions

View file

@ -54,6 +54,10 @@ export type DataViewFieldBase = {
*/
lang?: estypes.ScriptLanguage;
scripted?: boolean;
/**
* ES field types as strings array.
*/
esTypes?: string[];
};
/**

View file

@ -42,6 +42,12 @@ export const fields: DataViewFieldBase[] = [
type: 'string',
scripted: false,
},
{
name: 'machine.os.keyword',
type: 'string',
esTypes: ['keyword'],
scripted: false,
},
{
name: 'script number',
type: 'number',

View file

@ -206,6 +206,25 @@ describe('kuery functions', () => {
expect(result).toEqual(expected);
});
test('should create a wildcard query for keyword fields', () => {
const expected = {
bool: {
should: [
{
wildcard: {
'machine.os.keyword': 'win*',
},
},
],
minimum_should_match: 1,
},
};
const node = nodeTypes.function.buildNode('is', 'machine.os.keyword', 'win*');
const result = is.toElasticsearchQuery(node, indexPattern);
expect(result).toEqual(expected);
});
test('should support scripted fields', () => {
const node = nodeTypes.function.buildNode('is', 'script string', 'foo');
const result = is.toElasticsearchQuery(node, indexPattern);

View file

@ -142,15 +142,20 @@ export function toElasticsearchQuery(
}),
];
} else if (wildcard.isNode(valueArg)) {
return [
...accumulator,
wrapWithNestedQuery({
query_string: {
fields: [field.name],
query: wildcard.toQueryStringQuery(valueArg),
},
}),
];
const query = field.esTypes?.includes('keyword')
? {
wildcard: {
[field.name]: value,
},
}
: {
query_string: {
fields: [field.name],
query: wildcard.toQueryStringQuery(valueArg),
},
};
return [...accumulator, wrapWithNestedQuery(query)];
} else if (field.type === 'date') {
/*
If we detect that it's a date field and the user wants an exact date, we need to convert the query to both >= and <= the value provided to force a range query. This is because match and match_phrase queries do not accept a timezone parameter.

View file

@ -74,10 +74,13 @@ describe('getFields', () => {
const fieldNameNode = nodeTypes.wildcard.buildNode('machine*');
const results = getFields(fieldNameNode, indexPattern);
expect(Array.isArray(results)).toBeTruthy();
expect(results).toHaveLength(2);
expect(results!.find((field) => field.name === 'machine.os')).toBeDefined();
expect(results!.find((field) => field.name === 'machine.os.raw')).toBeDefined();
expect(results).toEqual(expect.any(Array));
expect(results).toHaveLength(3);
expect(results).toEqual([
expect.objectContaining({ name: 'machine.os' }),
expect.objectContaining({ name: 'machine.os.raw' }),
expect.objectContaining({ name: 'machine.os.keyword' }),
]);
});
});
});