Skip to content

Commit

Permalink
[ML] Add support for ES|QL in Data visualizer (elastic#174188)
Browse files Browse the repository at this point in the history
## Summary

This PR adds support for ES|QL queries in Data visualizer.

<img width="1695" alt="Screenshot 2024-01-26 at 17 07 59"
src="https://github.com/elastic/kibana/assets/43350163/8a54b859-60d6-4c47-b3dd-e5f3ed43b6b0">

<img width="1695" alt="Screenshot 2024-01-26 at 17 12 39"
src="https://github.com/elastic/kibana/assets/43350163/32fd08e4-7f3b-43e6-81a7-7ec4e777bac0">


https://github.com/elastic/kibana/assets/43350163/a3f540e9-461d-4ebc-bd69-de4ffa2bc554



### Changes:

- Add a new card from the Data visualizer main page

- Add a link from the ML navigation

<img width="1717" alt="Screenshot 2024-01-08 at 18 03 50"
src="https://github.com/elastic/kibana/assets/43350163/832f7890-4ce6-44c1-ab87-cde01f4bf1c0">

- Added a new button to Use ES|QL

<img width="1714" alt="Screenshot 2024-01-09 at 11 23 09"
src="https://github.com/elastic/kibana/assets/43350163/a38a9360-6691-4f3b-a824-8481ab543250">


- Support for **keyword**, **text**, **numeric**, **boolean**, **date**,
and **ip** fields

<img width="1714" alt="Screenshot 2024-01-09 at 11 24 38"
src="https://github.com/elastic/kibana/assets/43350163/b122ee5c-1500-4e2b-9434-e64b0b6ea3be">

<img width="1441" alt="Screenshot 2024-01-09 at 11 25 25"
src="https://github.com/elastic/kibana/assets/43350163/eb35ee78-8a34-467e-84da-2026b01fcda1">

<img width="969" alt="Screenshot 2024-01-09 at 11 44 02"
src="https://github.com/elastic/kibana/assets/43350163/d0f9947d-2b2c-4c14-89ba-9fc5d0a2bf64">

<img width="981" alt="Screenshot 2024-01-10 at 12 01 42"
src="https://github.com/elastic/kibana/assets/43350163/aa5a8d44-7447-41fc-a544-d1b626bf8bce">

- Default to user's fieldFormats for fields that are dynamic generated
by ES|QL, else use Data view's format

- Default to Data view's setting (e.g. type `bytes` in this case for
field `bytes_normal_counter`)
<img width="1037" alt="Screenshot 2024-01-10 at 12 10 38"
src="https://github.com/elastic/kibana/assets/43350163/9fb7e31c-f397-4209-a463-e1a43fe27ffd">

- Default to user's fieldFormats formatting for dynamically generated
fields (e.g. type `number` in this case for field `avg_price`)
<img width="1283" alt="Screenshot 2024-01-10 at 12 01 03"
src="https://github.com/elastic/kibana/assets/43350163/acc25358-50bb-4237-9476-86067ef0badf">

- Add a new UI control to allow users to limit analysis to 5,000 -
10,000 - 100,000 - 1,000,000, rows. This speeds up fetching of the stats
for big data sets and avoid potential circuit breaking exceptions.
- Break overall stats request into smaller parallel requests (which
prevent time out or payload too big due by too many fields), at 10
requests at a time
- Break field stats for individual fields into more efficient batches
(which prevent time out or payload too big due by too many fields), at
10 requests at at ime
- Improve error handling by propagating up the error AND the ES|QL
request in both the UI and the developer's console (for better
debugging)
- Improve error handling in field stats rows: If one field, or a group
of fields, say 'keyword' fields fail to fetch for some reasons, it will
show error for that field but not affect all other fields.


<img width="1690" alt="Screenshot 2024-01-26 at 16 04 28"
src="https://github.com/elastic/kibana/assets/43350163/6e240e12-76b4-42d6-b3be-c05342d76df9">

- Add deep linking in the top search bar

<img width="1185" alt="Screenshot 2024-01-26 at 16 56 49"
src="https://github.com/elastic/kibana/assets/43350163/4f24df68-edc5-41c5-b2ed-d6150ba1e20b">

- More robust support for keyword fields with geo data

<img width="1438" alt="Screenshot 2024-01-26 at 16 55 01"
src="https://github.com/elastic/kibana/assets/43350163/3b97925b-ca28-4952-8082-8d3242e3cb3f">




### Todos:
- [x] Add earliest/latest for date time fields -> Current blocker:
escape special characters in esql variable names
- [x] Fix formatting of numbers for dynamic query, where we don't know
the formatting based on the data view
- [x] Fix date time 'Update' not updating until Refresh is clicked
- [x] Better optimization to not fetch distribution & expanded row
content for pages that are not visible


### Good to have:
- [ ] Investigate bringing back the +/- filter buttons (either by
modifying the ES|QL query directly or by adding separate DSL filters?)

------------

### 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&mdash;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&mdash;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 <[email protected]>
  • Loading branch information
qn895 and kibanamachine authored Jan 31, 2024
1 parent 2ba824b commit 53c3907
Show file tree
Hide file tree
Showing 65 changed files with 2,850 additions and 138 deletions.
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,7 @@ x-pack/packages/maps/vector_tile_utils @elastic/kibana-gis
x-pack/plugins/metrics_data_access @elastic/obs-knowledge-team
x-pack/packages/ml/agg_utils @elastic/ml-ui
x-pack/packages/ml/anomaly_utils @elastic/ml-ui
x-pack/packages/ml/cancellable_search @elastic/ml-ui
x-pack/packages/ml/category_validator @elastic/ml-ui
x-pack/packages/ml/chi2test @elastic/ml-ui
x-pack/packages/ml/creation_wizard_utils @elastic/ml-ui
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,7 @@
"@kbn/metrics-data-access-plugin": "link:x-pack/plugins/metrics_data_access",
"@kbn/ml-agg-utils": "link:x-pack/packages/ml/agg_utils",
"@kbn/ml-anomaly-utils": "link:x-pack/packages/ml/anomaly_utils",
"@kbn/ml-cancellable-search": "link:x-pack/packages/ml/cancellable_search",
"@kbn/ml-category-validator": "link:x-pack/packages/ml/category_validator",
"@kbn/ml-chi2test": "link:x-pack/packages/ml/chi2test",
"@kbn/ml-creation-wizard-utils": "link:x-pack/packages/ml/creation_wizard_utils",
Expand Down
1 change: 1 addition & 0 deletions packages/deeplinks/ml/deep_links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type LinkId =
| 'nodesOverview'
| 'nodes'
| 'memoryUsage'
| 'esqlDataVisualizer'
| 'dataVisualizer'
| 'fileUpload'
| 'indexDataVisualizer'
Expand Down
9 changes: 9 additions & 0 deletions packages/default-nav/ml/default_navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,15 @@ export const defaultNavigation: MlNodeDefinition = {
);
},
},
{
title: i18n.translate('defaultNavigation.ml.esqlDataVisualizer', {
defaultMessage: 'ES|QL',
}),
link: 'ml:esqlDataVisualizer',
getIsActive: ({ pathNameSerialized, prepend }) => {
return pathNameSerialized.includes(prepend('/app/ml/datavisualizer/esql'));
},
},
{
title: i18n.translate('defaultNavigation.ml.dataComparison', {
defaultMessage: 'Data drift',
Expand Down
2 changes: 2 additions & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -1054,6 +1054,8 @@
"@kbn/ml-agg-utils/*": ["x-pack/packages/ml/agg_utils/*"],
"@kbn/ml-anomaly-utils": ["x-pack/packages/ml/anomaly_utils"],
"@kbn/ml-anomaly-utils/*": ["x-pack/packages/ml/anomaly_utils/*"],
"@kbn/ml-cancellable-search": ["x-pack/packages/ml/cancellable_search"],
"@kbn/ml-cancellable-search/*": ["x-pack/packages/ml/cancellable_search/*"],
"@kbn/ml-category-validator": ["x-pack/packages/ml/category_validator"],
"@kbn/ml-category-validator/*": ["x-pack/packages/ml/category_validator/*"],
"@kbn/ml-chi2test": ["x-pack/packages/ml/chi2test"],
Expand Down
3 changes: 3 additions & 0 deletions x-pack/packages/ml/cancellable_search/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @kbn/ml-cancellable-search

React hook for cancellable data searching
8 changes: 8 additions & 0 deletions x-pack/packages/ml/cancellable_search/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export { useCancellableSearch, type UseCancellableSearch } from './src/use_cancellable_search';
12 changes: 12 additions & 0 deletions x-pack/packages/ml/cancellable_search/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

module.exports = {
preset: '@kbn/test',
rootDir: '../../../..',
roots: ['<rootDir>/x-pack/packages/ml/cancellable_search'],
};
5 changes: 5 additions & 0 deletions x-pack/packages/ml/cancellable_search/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "shared-common",
"id": "@kbn/ml-cancellable-search",
"owner": "@elastic/ml-ui"
}
8 changes: 8 additions & 0 deletions x-pack/packages/ml/cancellable_search/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "@kbn/ml-cancellable-search",
"description": "React hook for cancellable data searching",
"author": "Machine Learning UI",
"private": true,
"version": "1.0.0",
"license": "Elastic License 2.0"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useCallback, useRef, useState } from 'react';
import { type IKibanaSearchResponse, isRunningResponse } from '@kbn/data-plugin/common';
import { tap } from 'rxjs/operators';
import type { DataPublicPluginStart } from '@kbn/data-plugin/public';

export interface UseCancellableSearch {
runRequest: <RequestBody, ResponseType extends IKibanaSearchResponse>(
requestBody: RequestBody,
options?: object
) => Promise<ResponseType | null>;
cancelRequest: () => void;
isLoading: boolean;
}

// Similar to aiops/hooks/use_cancellable_search.ts
export function useCancellableSearch(data: DataPublicPluginStart) {
const abortController = useRef(new AbortController());
const [isLoading, setIsFetching] = useState<boolean>(false);

const runRequest = useCallback(
<RequestBody, ResponseType extends IKibanaSearchResponse>(
requestBody: RequestBody,
options = {}
): Promise<ResponseType | null> => {
return new Promise((resolve, reject) => {
data.search
.search<RequestBody, ResponseType>(requestBody, {
abortSignal: abortController.current.signal,
...options,
})
.pipe(
tap(() => {
setIsFetching(true);
})
)
.subscribe({
next: (result) => {
if (!isRunningResponse(result)) {
setIsFetching(false);
resolve(result);
} else {
// partial results
// Ignore partial results for now.
// An issue with the search function means partial results are not being returned correctly.
}
},
error: (error) => {
if (error.name === 'AbortError') {
return resolve(null);
}
setIsFetching(false);
reject(error);
},
});
});
},
[data.search]
);

const cancelRequest = useCallback(() => {
abortController.current.abort();
abortController.current = new AbortController();
}, []);

return { runRequest, cancelRequest, isLoading };
}
21 changes: 21 additions & 0 deletions x-pack/packages/ml/cancellable_search/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"extends": "../../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "target/types",
"types": [
"jest",
"node",
"react"
]
},
"include": [
"**/*.ts",
"**/*.tsx",
],
"exclude": [
"target/**/*",
],
"kbn_references": [
"@kbn/data-plugin"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ interface DatePickerWrapperProps {
* Boolean flag to set use of flex group wrapper
*/
flexGroup?: boolean;
/**
* Boolean flag to disable the date picker
*/
isDisabled?: boolean;
}

/**
Expand All @@ -100,7 +104,14 @@ interface DatePickerWrapperProps {
* @returns {React.ReactElement} The DatePickerWrapper component.
*/
export const DatePickerWrapper: FC<DatePickerWrapperProps> = (props) => {
const { isAutoRefreshOnly, isLoading = false, showRefresh, width, flexGroup = true } = props;
const {
isAutoRefreshOnly,
isLoading = false,
showRefresh,
width,
flexGroup = true,
isDisabled = false,
} = props;
const {
data,
notifications: { toasts },
Expand Down Expand Up @@ -292,6 +303,7 @@ export const DatePickerWrapper: FC<DatePickerWrapperProps> = (props) => {
commonlyUsedRanges={commonlyUsedRanges}
updateButtonProps={{ iconOnly: isWithinLBreakpoint, fill: false }}
width={width}
isDisabled={isDisabled}
/>
</EuiFlexItem>
{showRefresh === true || !isTimeRangeSelectorEnabled ? (
Expand Down
13 changes: 8 additions & 5 deletions x-pack/plugins/data_visualizer/common/types/field_stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,21 @@ export const isIKibanaSearchResponse = (arg: unknown): arg is IKibanaSearchRespo
return isPopulatedObject(arg, ['rawResponse']);
};

export interface NumericFieldStats {
export interface NonSampledNumericFieldStats {
fieldName: string;
count?: number;
min?: number;
max?: number;
avg?: number;
median?: number;
distribution?: Distribution;
}

export interface NumericFieldStats extends NonSampledNumericFieldStats {
isTopValuesSampled: boolean;
topValues: Bucket[];
topValuesSampleSize: number;
topValuesSamplerShardSize: number;
median?: number;
distribution?: Distribution;
}

export interface StringFieldStats {
Expand Down Expand Up @@ -178,6 +181,7 @@ export type ChartRequestAgg = AggHistogram | AggCardinality | AggTerms;
export type ChartData = NumericChartData | OrdinalChartData | UnsupportedChartData;

export type BatchStats =
| NonSampledNumericFieldStats
| NumericFieldStats
| StringFieldStats
| BooleanFieldStats
Expand All @@ -186,6 +190,7 @@ export type BatchStats =
| FieldExamples;

export type FieldStats =
| NonSampledNumericFieldStats
| NumericFieldStats
| StringFieldStats
| BooleanFieldStats
Expand All @@ -199,7 +204,6 @@ export function isValidFieldStats(arg: unknown): arg is FieldStats {

export interface FieldStatsCommonRequestParams {
index: string;
samplerShardSize: number;
timeFieldName?: string;
earliestMs?: number | undefined;
latestMs?: number | undefined;
Expand All @@ -222,7 +226,6 @@ export interface OverallStatsSearchStrategyParams {
aggInterval: TimeBucketsInterval;
intervalMs?: number;
searchQuery: Query['query'];
samplerShardSize: number;
index: string;
timeFieldName?: string;
runtimeFieldMap?: estypes.MappingRuntimeFields;
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/data_visualizer/kibana.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
"esUiShared",
"fieldFormats",
"uiActions",
"lens"
"lens",
"textBasedLanguages",
]
}
}
Loading

0 comments on commit 53c3907

Please sign in to comment.