Skip to content

Commit

Permalink
[ML] Adds ES|QL support for field statistics table in Discover (#180849)
Browse files Browse the repository at this point in the history
## Summary

Follow up of #179098. Adds ES|QL
for support field statistics table in Discover

<img width="1728" alt="Screenshot 2024-05-09 at 13 59 29"
src="https://github.com/elastic/kibana/assets/43350163/ede8bcc5-2fc6-4a0a-8e3e-993294bbeafd">


https://github.com/elastic/kibana/assets/43350163/09a1feeb-cff6-4b8b-bf82-bb930413f215



https://github.com/elastic/kibana/assets/43350163/2acd78ec-1856-406e-a8f9-f6b2a26f8d81



### 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: Stratoula Kalafateli <[email protected]>
Co-authored-by: kibanamachine <[email protected]>
Co-authored-by: Davis McPhee <[email protected]>
  • Loading branch information
4 people authored Jun 3, 2024
1 parent 3efa595 commit d720a9b
Show file tree
Hide file tree
Showing 40 changed files with 340 additions and 223 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,22 @@ import { useAdditionalFieldGroups } from '../../hooks/sidebar/use_additional_fie
export const FieldStatisticsTab: React.FC<Omit<FieldStatisticsTableProps, 'query' | 'filters'>> =
React.memo((props) => {
const services = useDiscoverServices();
const querySubscriberResult = useQuerySubscriber({
const { query, filters } = useQuerySubscriber({
data: services.data,
});
const additionalFieldGroups = useAdditionalFieldGroups();

if (!services.dataVisualizer) return null;

return (
<FieldStatisticsTable
{...props}
query={querySubscriberResult.query}
filters={querySubscriberResult.filters}
dataView={props.dataView}
columns={props.columns}
stateContainer={props.stateContainer}
onAddFilter={props.onAddFilter}
trackUiMetric={props.trackUiMetric}
isEsqlMode={props.isEsqlMode}
query={query}
filters={filters}
additionalFieldGroups={additionalFieldGroups}
/>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,19 @@ import React, { useEffect, useMemo, useCallback } from 'react';
import { METRIC_TYPE } from '@kbn/analytics';
import { EuiFlexItem } from '@elastic/eui';
import { css } from '@emotion/react';
import useObservable from 'react-use/lib/useObservable';
import { of, map } from 'rxjs';
import { of, map, filter } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
import useObservable from 'react-use/lib/useObservable';
import {
convertFieldsToFallbackFields,
getAllFallbackFields,
getAssociatedSmartFieldsAsString,
SmartFieldFallbackTooltip,
} from '@kbn/unified-field-list';
import type { DataVisualizerTableItem } from '@kbn/data-visualizer-plugin/public/application/common/components/stats_table/data_visualizer_stats_table';
import type { DataVisualizerTableItem } from '@kbn/data-visualizer-plugin/public/application/common/components/stats_table/types';
import { useDiscoverServices } from '../../../../hooks/use_discover_services';
import { FIELD_STATISTICS_LOADED } from './constants';

import type { NormalSamplingOption, FieldStatisticsTableProps } from './types';
export type { FieldStatisticsTableProps };

Expand All @@ -35,9 +36,11 @@ const statsTableCss = css({
});

const fallBacklastReloadRequestTime$ = new BehaviorSubject(0);
const fallbackTotalHits = of(undefined);

export const FieldStatisticsTable = (props: FieldStatisticsTableProps) => {
export const FieldStatisticsTable = React.memo((props: FieldStatisticsTableProps) => {
const {
isEsqlMode,
dataView,
savedSearch,
query,
Expand Down Expand Up @@ -81,10 +84,15 @@ export const FieldStatisticsTable = (props: FieldStatisticsTableProps) => {
[additionalFieldGroups, allFallbackFields]
);

const totalHits = useObservable(stateContainer?.dataState.data$.totalHits$ ?? of(undefined));
const totalDocuments = useMemo(() => totalHits?.result, [totalHits]);

const services = useDiscoverServices();

// Other apps consuming Discover UI might inject their own proxied data services
// so we need override the kibana context services with the injected proxied services
// to make sure the table use the right service
const overridableServices = useMemo(() => {
return { data: services.data };
}, [services.data]);

const dataVisualizerService = services.dataVisualizer;

// State from Discover we want the embeddable to reflect
Expand All @@ -95,11 +103,25 @@ export const FieldStatisticsTable = (props: FieldStatisticsTableProps) => {

const lastReloadRequestTime$ = useMemo(() => {
return stateContainer?.dataState?.refetch$
? stateContainer?.dataState?.refetch$.pipe(map(() => Date.now()))
? stateContainer?.dataState?.refetch$.pipe(
map(() => {
return Date.now();
})
)
: fallBacklastReloadRequestTime$;
}, [stateContainer]);

const lastReloadRequestTime = useObservable(lastReloadRequestTime$, 0);
const totalHitsComplete$ = useMemo(() => {
return stateContainer
? stateContainer.dataState.data$.totalHits$.pipe(
filter((d) => d.fetchStatus === 'complete'),
map((d) => d?.result)
)
: fallbackTotalHits;
}, [stateContainer]);

const totalDocuments = useObservable(totalHitsComplete$);
const lastReloadRequestTime = useObservable(lastReloadRequestTime$);

useEffect(() => {
// Track should only be called once when component is loaded
Expand All @@ -119,7 +141,7 @@ export const FieldStatisticsTable = (props: FieldStatisticsTableProps) => {
const updateState = useCallback(
(changes) => {
if (changes.showDistributions !== undefined && stateContainer) {
stateContainer.appState.update({ hideAggregatedPreview: !changes.showDistributions });
stateContainer.appState.update({ hideAggregatedPreview: !changes.showDistributions }, true);
}
},
[stateContainer]
Expand All @@ -144,7 +166,9 @@ export const FieldStatisticsTable = (props: FieldStatisticsTableProps) => {
showPreviewByDefault={showPreviewByDefault}
onTableUpdate={updateState}
renderFieldName={renderFieldName}
esql={isEsqlMode}
overridableServices={overridableServices}
/>
</EuiFlexItem>
);
};
});
Original file line number Diff line number Diff line change
Expand Up @@ -169,4 +169,8 @@ export interface FieldStatisticsTableProps {
* Additional field groups (e.g. Smart Fields)
*/
additionalFieldGroups?: AdditionalFieldGroups;
/**
* If table should query using ES|QL
*/
isEsqlMode?: boolean;
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export function DiscoverLayout({ stateContainer }: DiscoverLayoutProps) {
history,
spaces,
observabilityAIAssistant,
dataVisualizer: dataVisualizerService,
} = useDiscoverServices();
const pageBackgroundColor = useEuiBackgroundColor('plain');
const globalQueryState = data.query.getState();
Expand All @@ -86,12 +87,13 @@ export function DiscoverLayout({ stateContainer }: DiscoverLayoutProps) {
state.sort,
]);
const isEsqlMode = useIsEsqlMode();

const viewMode: VIEW_MODE = useAppStateSelector((state) => {
if (state.viewMode === VIEW_MODE.DOCUMENT_LEVEL || state.viewMode === VIEW_MODE.PATTERN_LEVEL) {
return state.viewMode;
}
if (uiSettings.get(SHOW_FIELD_STATISTICS) !== true || isEsqlMode)
const fieldStatsNotAvailable =
!uiSettings.get(SHOW_FIELD_STATISTICS) && !!dataVisualizerService;
if (state.viewMode === VIEW_MODE.AGGREGATED_LEVEL && fieldStatsNotAvailable) {
return VIEW_MODE.DOCUMENT_LEVEL;
}
return state.viewMode ?? VIEW_MODE.DOCUMENT_LEVEL;
});
const [dataView, dataViewLoading] = useInternalStateSelector((state) => [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const DiscoverMainContent = ({

const setDiscoverViewMode = useCallback(
(mode: VIEW_MODE) => {
stateContainer.appState.update({ viewMode: mode });
stateContainer.appState.update({ viewMode: mode }, true);

if (trackUiMetric) {
if (mode === VIEW_MODE.AGGREGATED_LEVEL) {
Expand Down Expand Up @@ -151,6 +151,7 @@ export const DiscoverMainContent = ({
stateContainer={stateContainer}
onAddFilter={!isEsqlMode ? onAddFilter : undefined}
trackUiMetric={trackUiMetric}
isEsqlMode={isEsqlMode}
/>
</>
) : null}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,12 @@ describe('useEsqlMode', () => {
stateContainer.dataState.data$.documents$.next(msgComplete);
expect(replaceUrlState).toHaveBeenCalledTimes(0);
});
test('should change viewMode to undefined (default) if it was AGGREGATED_LEVEL', async () => {
test('should not change viewMode to undefined (default) if it was AGGREGATED_LEVEL', async () => {
const { replaceUrlState } = renderHookWithContext(false, {
viewMode: VIEW_MODE.AGGREGATED_LEVEL,
});

await waitFor(() => expect(replaceUrlState).toHaveBeenCalledTimes(1));
expect(replaceUrlState).toHaveBeenCalledWith({
viewMode: undefined,
});
await waitFor(() => expect(replaceUrlState).toHaveBeenCalledTimes(0));
});

test('should change viewMode to undefined (default) if it was PATTERN_LEVEL', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
} from '@kbn/unified-histogram-plugin/public';
import { SavedObjectSaveOpts } from '@kbn/saved-objects-plugin/public';
import { isEqual, isFunction } from 'lodash';
import { VIEW_MODE } from '../../../../common/constants';
import { restoreStateFromSavedSearch } from '../../../services/saved_searches/restore_from_saved_search';
import { updateSavedSearch } from './utils/update_saved_search';
import { addLog } from '../../../utils/add_log';
Expand Down Expand Up @@ -340,7 +341,12 @@ export function isEqualSavedSearch(savedSearchPrev: SavedSearch, savedSearchNext
const prevValue = getSavedSearchFieldForComparison(prevSavedSearch, key);
const nextValue = getSavedSearchFieldForComparison(nextSavedSearchWithoutSearchSource, key);

const isSame = isEqual(prevValue, nextValue);
const isSame =
isEqual(prevValue, nextValue) ||
// By default, viewMode: undefined is equivalent to documents view
// So they should be treated as same
(key === 'viewMode' &&
(prevValue ?? VIEW_MODE.DOCUMENT_LEVEL) === (nextValue ?? VIEW_MODE.DOCUMENT_LEVEL));

if (!isSame) {
addLog('[savedSearch] difference between initial and changed version', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,14 @@ describe('getStateDefaults', () => {
});
expect(actualForUndefinedViewMode.viewMode).toBeUndefined();

const actualForEsqlWithInvalidAggLevelViewMode = getStateDefaults({
const actualForEsqlWithAggregatedViewMode = getStateDefaults({
services: discoverServiceMock,
savedSearch: {
...savedSearchMockWithESQL,
viewMode: VIEW_MODE.AGGREGATED_LEVEL,
},
});
expect(actualForEsqlWithInvalidAggLevelViewMode.viewMode).toBe(VIEW_MODE.DOCUMENT_LEVEL);
expect(actualForEsqlWithAggregatedViewMode.viewMode).toBe(VIEW_MODE.AGGREGATED_LEVEL);

const actualForEsqlWithInvalidPatternLevelViewMode = getStateDefaults({
services: discoverServiceMock,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ describe('getValidViewMode', () => {
viewMode: VIEW_MODE.AGGREGATED_LEVEL,
isEsqlMode: true,
})
).toBe(VIEW_MODE.DOCUMENT_LEVEL);
).toBe(VIEW_MODE.AGGREGATED_LEVEL);

expect(
getValidViewMode({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,8 @@ export const getValidViewMode = ({
viewMode?: VIEW_MODE;
isEsqlMode: boolean;
}): VIEW_MODE | undefined => {
if (
(viewMode === VIEW_MODE.PATTERN_LEVEL || viewMode === VIEW_MODE.AGGREGATED_LEVEL) &&
isEsqlMode
) {
// only this mode is supported for text-based languages
if (viewMode === VIEW_MODE.PATTERN_LEVEL && isEsqlMode) {
// only this mode is supported for ES|QL languages
return VIEW_MODE.DOCUMENT_LEVEL;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,14 @@ describe('Document view mode toggle component', () => {
expect(findTestSubject(component, 'dscViewModeFieldStatsButton').exists()).toBe(false);
});

it('should not render if ES|QL', async () => {
it('should show document and field stats view if ES|QL', async () => {
const component = await mountComponent({ isEsqlMode: true });
expect(findTestSubject(component, 'dscViewModeToggle').exists()).toBe(false);
expect(findTestSubject(component, 'dscViewModeToggle').exists()).toBe(true);
expect(findTestSubject(component, 'discoverQueryTotalHits').exists()).toBe(true);

expect(findTestSubject(component, 'dscViewModeDocumentButton').exists()).toBe(false);
expect(findTestSubject(component, 'dscViewModeDocumentButton').exists()).toBe(true);
expect(findTestSubject(component, 'dscViewModePatternAnalysisButton').exists()).toBe(false);
expect(findTestSubject(component, 'dscViewModeFieldStatsButton').exists()).toBe(false);
expect(findTestSubject(component, 'dscViewModeFieldStatsButton').exists()).toBe(true);
});

it('should set the view mode to VIEW_MODE.DOCUMENT_LEVEL when dscViewModeDocumentButton is clicked', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const DocumentViewModeToggle = ({

useEffect(
function checkForPatternAnalysis() {
if (!aiopsService) {
if (!aiopsService || isEsqlMode) {
setShowPatternAnalysisTab(false);
return;
}
Expand All @@ -76,7 +76,7 @@ export const DocumentViewModeToggle = ({
})
.catch(() => setShowPatternAnalysisTabWrapper(false));
},
[aiopsService, dataView, setShowPatternAnalysisTabWrapper]
[aiopsService, dataView, isEsqlMode, setShowPatternAnalysisTabWrapper]
);

useEffect(() => {
Expand Down Expand Up @@ -121,7 +121,7 @@ export const DocumentViewModeToggle = ({
</EuiFlexItem>
)}
<EuiFlexItem grow={false}>
{isEsqlMode || (showFieldStatisticsTab === false && showPatternAnalysisTab === false) ? (
{showFieldStatisticsTab === false && showPatternAnalysisTab === false ? (
<HitsCounter mode={HitsCounterMode.standalone} stateContainer={stateContainer} />
) : (
<EuiTabs size="m" css={tabsCss} data-test-subj="dscViewModeToggle" bottomBorder={false}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,7 @@ export class SavedSearchEmbeddable
query={this.input.query}
onAddFilter={searchProps.onFilter}
searchSessionId={this.input.searchSessionId}
isEsqlMode={isEsqlMode}
/>
</KibanaContextProvider>
</KibanaRenderContextProvider>,
Expand Down
2 changes: 1 addition & 1 deletion test/functional/apps/discover/group4/_esql_view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {

expect(await testSubjects.exists('showQueryBarMenu')).to.be(false);
expect(await testSubjects.exists('addFilter')).to.be(false);
expect(await testSubjects.exists('dscViewModeDocumentButton')).to.be(false);
expect(await testSubjects.exists('dscViewModeDocumentButton')).to.be(true);
// when Lens suggests a table, we render an ESQL based histogram
expect(await testSubjects.exists('unifiedHistogramChart')).to.be(true);
expect(await testSubjects.exists('discoverQueryHits')).to.be(true);
Expand Down
4 changes: 2 additions & 2 deletions test/functional/apps/discover/group6/_view_mode_toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
await testSubjects.existOrFail('dscViewModeToggle');
});

it('should not show view mode toggle for ES|QL searches', async () => {
it('should still show view mode toggle for ES|QL searches', async () => {
await testSubjects.click('dscViewModeDocumentButton');

await retry.try(async () => {
Expand All @@ -119,7 +119,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {

await PageObjects.discover.selectTextBaseLang();

await testSubjects.missingOrFail('dscViewModeToggle');
await testSubjects.existOrFail('dscViewModeToggle');

if (!useLegacyTable) {
await testSubjects.existOrFail('unifiedDataTableToolbar');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export interface FieldVisStats {
examples?: Array<string | GeoPointExample | object>;
timeRangeEarliest?: number;
timeRangeLatest?: number;
approximate?: boolean;
}

export interface DVErrorObject {
Expand Down
5 changes: 5 additions & 0 deletions x-pack/plugins/data_visualizer/common/types/field_stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ export interface StringFieldStats {
sampledValues?: Bucket[];
topValuesSampleSize?: number;
topValuesSamplerShardSize?: number;
/**
* Approximate: true for when the terms are from a random subset of the source data
* such that result/count for each term is not deterministic every time
*/
approximate?: boolean;
}

export interface DateFieldStats {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,6 @@ import { IndexBasedNumberContentPreview } from './components/field_data_row/numb

import { useTableSettings } from './use_table_settings';
import { TopValuesPreview } from './components/field_data_row/top_values_preview';
import type {
FieldVisConfig,
FileBasedFieldVisConfig,
} from '../../../../../common/types/field_vis_config';
import { isIndexBasedFieldVisConfig } from '../../../../../common/types/field_vis_config';
import { FileBasedNumberContentPreview } from '../field_data_row';
import { BooleanContentPreview } from './components/field_data_row';
Expand All @@ -47,12 +43,12 @@ import { DistinctValues } from './components/field_data_row/distinct_values';
import { FieldTypeIcon } from '../field_type_icon';
import './_index.scss';
import type { FieldStatisticTableEmbeddableProps } from '../../../index_data_visualizer/embeddables/grid_embeddable/types';
import type { DataVisualizerTableItem } from './types';

const FIELD_NAME = 'fieldName';

export type ItemIdToExpandedRowMap = Record<string, JSX.Element>;

export type DataVisualizerTableItem = FieldVisConfig | FileBasedFieldVisConfig;
interface DataVisualizerTableProps<T extends object> {
items: T[];
pageState: DataVisualizerTableState;
Expand Down
Loading

0 comments on commit d720a9b

Please sign in to comment.