[ES|QL] Add ECS information to the editor hint & prioritize fields based on ECS information on the editor (#187922)

## Summary

Closes https://github.com/elastic/kibana/issues/181036. This PR adds ECS
information to the editor hint & prioritizes fields based on ECS
information on the editor. The logic involves:

1) Identify if dataset has ecs fields (e.g. column contains ecs.version)
2) If yes, check which fields have ecs info using [fieldsMetadata
client](https://github.com/elastic/kibana/issues/181036#issuecomment-2149134909)
3) Push fields with ecs info up to the top of the list of suggestions
and order these fields alphabetically. These pushed fields have "1D"
sort text.
4) Show the rest of the fields without ecs decription at the bottom,
order these fields alphabetically.



https://github.com/user-attachments/assets/055c2513-ba6f-40f9-a27f-d717ce37a390

**Note for reviewers**: 
- When fetching fields metadata, if there are many fields, we are
breaking down into multiple requests (250 fields/request) to avoid
payload too large.




### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>
This commit is contained in:
Quynh Nguyen (Quinn) 2024-07-15 12:32:42 -05:00 committed by GitHub
parent 875d6e99f0
commit 0ac61b76b6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 267 additions and 27 deletions

View file

@ -70,6 +70,7 @@ import {
buildOptionDefinition,
buildSettingDefinitions,
buildValueDefinitions,
buildFieldsDefinitionsWithMetadata,
} from './factories';
import { EDITOR_MARKER, SINGLE_BACKTICK, METADATA_FIELDS } from '../shared/constants';
import { getAstContext, removeMarkerArgFromArgsList } from '../shared/context';
@ -292,7 +293,7 @@ function getFieldsByTypeRetriever(queryString: string, resourceRetriever?: ESQLC
return {
getFieldsByType: async (expectedType: string | string[] = 'any', ignored: string[] = []) => {
const fields = await helpers.getFieldsByType(expectedType, ignored);
return buildFieldsDefinitions(fields);
return buildFieldsDefinitionsWithMetadata(fields);
},
getFieldsMap: helpers.getFieldsMap,
};

View file

@ -22,6 +22,7 @@ import {
import { shouldBeQuotedSource, getCommandDefinition, shouldBeQuotedText } from '../shared/helpers';
import { buildDocumentation, buildFunctionDocumentation } from './documentation_util';
import { DOUBLE_BACKTICK, SINGLE_TICK_REGEX } from '../shared/constants';
import type { ESQLRealField } from '../validation/types';
const allFunctions = statsAggregationFunctionDefinitions
.concat(evalFunctionDefinitions)
@ -125,8 +126,34 @@ export function getSuggestionCommandDefinition(
};
}
export const buildFieldsDefinitions = (fields: string[]): SuggestionRawDefinition[] =>
fields.map((label) => ({
export const buildFieldsDefinitionsWithMetadata = (
fields: ESQLRealField[]
): SuggestionRawDefinition[] => {
return fields.map((field) => {
const description = field.metadata?.description;
const titleCaseType = field.type.charAt(0).toUpperCase() + field.type.slice(1);
return {
label: field.name,
text: getSafeInsertText(field.name),
kind: 'Variable',
detail: titleCaseType,
documentation: description
? {
value: `
---
${description}`,
}
: undefined,
// If there is a description, it is a field from ECS, so it should be sorted to the top
sortText: description ? '1D' : 'D',
};
});
};
export const buildFieldsDefinitions = (fields: string[]): SuggestionRawDefinition[] => {
return fields.map((label) => ({
label,
text: getSafeInsertText(label),
kind: 'Variable',
@ -135,7 +162,7 @@ export const buildFieldsDefinitions = (fields: string[]): SuggestionRawDefinitio
}),
sortText: 'D',
}));
};
export const buildVariablesDefinitions = (variables: string[]): SuggestionRawDefinition[] =>
variables.map((label) => ({
label,

View file

@ -112,7 +112,7 @@ async function getSpellingActionForColumns(
}
// @TODO add variables support
const possibleFields = await getSpellingPossibilities(async () => {
const availableFields = await getFieldsByType('any');
const availableFields = (await getFieldsByType('any')).map(({ name }) => name);
const enrichPolicies = ast.filter(({ name }) => name === 'enrich');
if (enrichPolicies.length) {
const enrichPolicyNames = enrichPolicies.flatMap(({ args }) =>
@ -209,7 +209,7 @@ async function getQuotableActionForColumns(
)
);
} else {
const availableFields = new Set(await getFieldsByType('any'));
const availableFields = new Set((await getFieldsByType('any')).map(({ name }) => name));
if (availableFields.has(errorText) || availableFields.has(solution)) {
actions.push(
createAction(

View file

@ -7,9 +7,10 @@
*/
import type { EditorError } from '../types';
import type { ESQLRealField } from '../validation/types';
type GetSourceFn = () => Promise<string[]>;
type GetFieldsByTypeFn = (type: string | string[], ignored?: string[]) => Promise<string[]>;
type GetFieldsByTypeFn = (type: string | string[], ignored?: string[]) => Promise<ESQLRealField[]>;
type GetPoliciesFn = () => Promise<string[]>;
type GetPolicyFieldsFn = (name: string) => Promise<string[]>;

View file

@ -26,18 +26,17 @@ export function getFieldsByTypeHelper(queryText: string, resourceRetriever?: ESQ
}
};
return {
getFieldsByType: async (expectedType: string | string[] = 'any', ignored: string[] = []) => {
getFieldsByType: async (
expectedType: string | string[] = 'any',
ignored: string[] = []
): Promise<ESQLRealField[]> => {
const types = Array.isArray(expectedType) ? expectedType : [expectedType];
await getFields();
return (
Array.from(cacheFields.values())
?.filter(({ name, type }) => {
const ts = Array.isArray(type) ? type : [type];
return (
!ignored.includes(name) && ts.some((t) => types[0] === 'any' || types.includes(t))
);
})
.map(({ name }) => name) || []
Array.from(cacheFields.values())?.filter(({ name, type }) => {
const ts = Array.isArray(type) ? type : [type];
return !ignored.includes(name) && ts.some((t) => types[0] === 'any' || types.includes(t));
}) || []
);
},
getFieldsMap: async () => {

View file

@ -6,6 +6,8 @@
* Side Public License, v 1.
*/
import type { ESQLRealField } from '../validation/types';
/** @internal **/
type CallbackFn<Options = {}, Result = string> = (ctx?: Options) => Result[] | Promise<Result[]>;
@ -20,7 +22,7 @@ export interface ESQLCallbacks {
dataStreams?: Array<{ name: string; title?: string }>;
}
>;
getFieldsFor?: CallbackFn<{ query: string }, { name: string; type: string }>;
getFieldsFor?: CallbackFn<{ query: string }, ESQLRealField>;
getPolicies?: CallbackFn<
{},
{ name: string; sourceIndices: string[]; matchField: string; enrichFields: string[] }

View file

@ -18,6 +18,10 @@ export interface ESQLVariable {
export interface ESQLRealField {
name: string;
type: string;
metadata?: {
description?: string;
type?: string;
};
}
export interface ESQLPolicy {

View file

@ -0,0 +1,81 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { getColumnsWithMetadata } from './ecs_metadata_helper';
import type { DatatableColumnType } from '@kbn/expressions-plugin/common';
import type { FieldsMetadataPublicStart } from '@kbn/fields-metadata-plugin/public';
describe('getColumnsWithMetadata', () => {
it('should return original columns if fieldsMetadata is not provided', async () => {
const columns = [
{ name: 'ecs.version', type: 'string' as DatatableColumnType },
{ name: 'field1', type: 'string' as DatatableColumnType },
{ name: 'field2', type: 'number' as DatatableColumnType },
];
const result = await getColumnsWithMetadata(columns);
expect(result).toEqual(columns);
});
it('should return columns with metadata if ECS version field is present', async () => {
const columns = [
{ name: 'ecs.version', type: 'string' as DatatableColumnType },
{ name: 'field2', type: 'number' as DatatableColumnType },
];
const fieldsMetadata = {
getClient: jest.fn().mockResolvedValue({
find: jest.fn().mockResolvedValue({
fields: {
'ecs.version': { description: 'ECS version field', type: 'keyword' },
'ecs.field': { description: 'ECS field description', type: 'keyword' },
},
}),
}),
} as unknown as FieldsMetadataPublicStart;
const result = await getColumnsWithMetadata(columns, fieldsMetadata);
expect(result).toEqual([
{
name: 'ecs.version',
type: 'string',
metadata: { description: 'ECS version field' },
},
{ name: 'field2', type: 'number' },
]);
});
it('should handle keyword suffix correctly', async () => {
const columns = [
{ name: 'ecs.version', type: 'string' as DatatableColumnType },
{ name: 'ecs.version.keyword', type: 'string' as DatatableColumnType },
{ name: 'field2', type: 'number' as DatatableColumnType },
];
const fieldsMetadata = {
getClient: jest.fn().mockResolvedValue({
find: jest.fn().mockResolvedValue({
fields: {
'ecs.version': { description: 'ECS version field', type: 'keyword' },
},
}),
}),
} as unknown as FieldsMetadataPublicStart;
const result = await getColumnsWithMetadata(columns, fieldsMetadata);
expect(result).toEqual([
{ name: 'ecs.version', type: 'string', metadata: { description: 'ECS version field' } },
{
name: 'ecs.version.keyword',
type: 'string',
metadata: { description: 'ECS version field' },
},
{ name: 'field2', type: 'number' },
]);
});
});

View file

@ -0,0 +1,102 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import type { ESQLRealField } from '@kbn/esql-validation-autocomplete';
import { esFieldTypeToKibanaFieldType } from '@kbn/field-types';
import type { FieldsMetadataPublicStart } from '@kbn/fields-metadata-plugin/public';
import { chunk } from 'lodash';
const removeKeywordSuffix = (name: string) => {
return name.endsWith('.keyword') ? name.slice(0, -8) : name;
};
/**
* Returns columns with the metadata/description (e.g ECS info)
* if available
*
* @param columns
* @param fieldsMetadata
* @returns
*/
export async function getColumnsWithMetadata(
columns: Array<Omit<ESQLRealField, 'metadata'>>,
fieldsMetadata?: FieldsMetadataPublicStart
): Promise<ESQLRealField[]> {
if (!fieldsMetadata) return columns;
try {
const fieldsMetadataClient = await fieldsMetadata?.getClient();
if (fieldsMetadataClient) {
const fields = await fieldsMetadataClient.find({
fieldNames: columns.map((c) => c.name),
attributes: ['description', 'type'],
});
if (fields?.fields) {
return columns.map((c) => {
// Metadata services gives description for
// 'ecs.version' but not 'ecs.version.keyword'
// but both should show description if available
const metadata = fields.fields[removeKeywordSuffix(c.name)];
// Need to convert metadata's type (e.g. keyword) to ES|QL type (e.g. string) to check if they are the same
if (
!metadata ||
(metadata?.type && esFieldTypeToKibanaFieldType(metadata.type) !== c.type)
)
return c;
return {
...c,
metadata: { description: metadata.description },
};
});
}
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Unable to fetch field metadata', error);
}
return columns;
}
/**
* Returns columns with the metadata/description (e.g ECS info)
* if available. Safely partition the requests to avoid 400 payload too big errors.
*
* @param columns
* @param fieldsMetadata
* @returns
*/
export async function getRateLimitedColumnsWithMetadata(
columns: Array<Omit<ESQLRealField, 'metadata'>>,
fieldsMetadata?: FieldsMetadataPublicStart,
maxFieldsPerRequest = 250,
maxConcurrentRequests = 10
): Promise<ESQLRealField[]> {
if (!fieldsMetadata) return columns;
try {
// Chunking requests here since we are calling fieldsMetadata.find with list of fields,
// and we need to make sure payload is not too big, or else get 400 error
const chunkedColumns = chunk(columns, maxFieldsPerRequest);
const result: Array<PromiseSettledResult<ESQLRealField[]>> = [];
// Also only make max of n at a time to avoid too many concurrent requests
for (let i = 0; i < chunkedColumns.length; i += maxConcurrentRequests) {
const cols = chunkedColumns.slice(i, i + maxConcurrentRequests);
const chunkResult = await Promise.allSettled(
cols.map((c) => getColumnsWithMetadata(c, fieldsMetadata))
);
result.push(...chunkResult);
}
return result.flatMap((r, idx) => (r.status === 'fulfilled' ? r.value : chunkedColumns[idx]));
} catch (error) {
// eslint-disable-next-line no-console
console.error('Unable to fetch field metadata', error);
}
return columns;
}

View file

@ -60,4 +60,4 @@
.TextBasedLangEditor--expanded .monaco-editor, .TextBasedLangEditor--expanded .monaco-editor .margin, .TextBasedLangEditor--expanded .monaco-editor .overflow-guard {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
}

View file

@ -23,6 +23,7 @@ import { getAggregateQueryMode, getLanguageDisplayName } from '@kbn/es-query';
import type { ExpressionsStart } from '@kbn/expressions-plugin/public';
import { i18n } from '@kbn/i18n';
import type { IndexManagementPluginSetup } from '@kbn/index-management';
import type { FieldsMetadataPublicStart } from '@kbn/fields-metadata-plugin/public';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import {
LanguageDocumentationPopover,
@ -56,6 +57,7 @@ import {
EDITOR_MIN_HEIGHT,
textBasedLanguageEditorStyles,
} from './text_based_languages_editor.styles';
import { getRateLimitedColumnsWithMetadata } from './ecs_metadata_helper';
import './overwrite.scss';
@ -123,6 +125,7 @@ interface TextBasedEditorDeps {
dataViews: DataViewsPublicPluginStart;
expressions: ExpressionsStart;
indexManagementApiService?: IndexManagementPluginSetup['apiService'];
fieldsMetadata?: FieldsMetadataPublicStart;
}
const MAX_COMPACT_VIEW_LENGTH = 250;
@ -167,8 +170,15 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
const language = getAggregateQueryMode(query);
const queryString: string = query[language] ?? '';
const kibana = useKibana<TextBasedEditorDeps>();
const { dataViews, expressions, indexManagementApiService, application, docLinks, core } =
kibana.services;
const {
dataViews,
expressions,
indexManagementApiService,
application,
docLinks,
core,
fieldsMetadata,
} = kibana.services;
const timeZone = core?.uiSettings?.get('dateFormat:tz');
const [code, setCode] = useState<string>(queryString ?? '');
const [codeOneLiner, setCodeOneLiner] = useState<string | null>(null);
@ -430,7 +440,8 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
undefined,
abortController
).result;
return table?.columns.map((c) => ({ name: c.name, type: c.meta.type })) || [];
const columns = table?.columns.map((c) => ({ name: c.name, type: c.meta.type })) || [];
return await getRateLimitedColumnsWithMetadata(columns, fieldsMetadata);
} catch (e) {
// no action yet
}
@ -458,6 +469,7 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
expressions,
abortController,
indexManagementApiService,
fieldsMetadata,
]);
const parseMessages = useCallback(async () => {

View file

@ -26,6 +26,9 @@
"@kbn/index-management",
"@kbn/code-editor",
"@kbn/shared-ux-markdown",
"@kbn/fields-metadata-plugin",
"@kbn/esql-validation-autocomplete",
"@kbn/field-types"
],
"exclude": [
"target/**/*",

View file

@ -7,7 +7,8 @@
"server": true,
"browser": true,
"optionalPlugins": [
"indexManagement"
"indexManagement",
"fieldsMetadata"
],
"requiredPlugins": [
"data",

View file

@ -10,7 +10,8 @@ import { BehaviorSubject } from 'rxjs';
import type { CoreStart } from '@kbn/core/public';
import type { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public';
import type { ExpressionsStart } from '@kbn/expressions-plugin/public';
import { IndexManagementPluginSetup } from '@kbn/index-management';
import type { IndexManagementPluginSetup } from '@kbn/index-management';
import type { FieldsMetadataPublicStart } from '@kbn/fields-metadata-plugin/public';
export let core: CoreStart;
@ -20,6 +21,7 @@ interface ServiceDeps {
dataViews: DataViewsPublicPluginStart;
expressions: ExpressionsStart;
indexManagementApiService?: IndexManagementPluginSetup['apiService'];
fieldsMetadata?: FieldsMetadataPublicStart;
}
const servicesReady$ = new BehaviorSubject<ServiceDeps | undefined>(undefined);
@ -39,7 +41,8 @@ export const setKibanaServices = (
kibanaCore: CoreStart,
dataViews: DataViewsPublicPluginStart,
expressions: ExpressionsStart,
indexManagement?: IndexManagementPluginSetup
indexManagement?: IndexManagementPluginSetup,
fieldsMetadata?: FieldsMetadataPublicStart
) => {
core = kibanaCore;
core.theme.theme$.subscribe(({ darkMode }) => {
@ -49,6 +52,7 @@ export const setKibanaServices = (
dataViews,
expressions,
indexManagementApiService: indexManagement?.apiService,
fieldsMetadata,
});
});
};

View file

@ -12,6 +12,7 @@ import type { ExpressionsStart } from '@kbn/expressions-plugin/public';
import type { DataPublicPluginStart } from '@kbn/data-plugin/public';
import type { IndexManagementPluginSetup } from '@kbn/index-management';
import type { UiActionsSetup, UiActionsStart } from '@kbn/ui-actions-plugin/public';
import type { FieldsMetadataPublicStart } from '@kbn/fields-metadata-plugin/public';
import {
updateESQLQueryTrigger,
UpdateESQLQueryAction,
@ -24,6 +25,7 @@ interface EsqlPluginStart {
expressions: ExpressionsStart;
uiActions: UiActionsStart;
data: DataPublicPluginStart;
fieldsMetadata: FieldsMetadataPublicStart;
}
interface EsqlPluginSetup {
@ -44,11 +46,11 @@ export class EsqlPlugin implements Plugin<{}, void> {
public start(
core: CoreStart,
{ dataViews, expressions, data, uiActions }: EsqlPluginStart
{ dataViews, expressions, data, uiActions, fieldsMetadata }: EsqlPluginStart
): void {
const appendESQLAction = new UpdateESQLQueryAction(data);
uiActions.addTriggerAction(UPDATE_ESQL_QUERY_TRIGGER, appendESQLAction);
setKibanaServices(core, dataViews, expressions, this.indexManagement);
setKibanaServices(core, dataViews, expressions, this.indexManagement, fieldsMetadata);
}
public stop() {}

View file

@ -21,7 +21,8 @@
"@kbn/esql-utils",
"@kbn/ui-actions-plugin",
"@kbn/data-plugin",
"@kbn/es-query"
"@kbn/es-query",
"@kbn/fields-metadata-plugin"
],
"exclude": [
"target/**/*",