Skip to content

Commit

Permalink
[ML] Fix multi match query overriding filters in Data visualizer and …
Browse files Browse the repository at this point in the history
…Data Drift (elastic#176347)

This PR removes usage of `createMergedEsQuery` in favor of buildEsQuery.
It also fixes an intermittent issue with filters
elastic#170472 not being honored when
query is partial/of multi match type.
<img width="1728" alt="Screenshot 2024-02-07 at 10 20 26"
src="https://github.com/elastic/kibana/assets/43350163/a6ba78ef-4970-4d5b-8bdb-b74f807969e0">


It also improves adding/removing filter for empty values

### 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: Kibana Machine <[email protected]>
  • Loading branch information
2 people authored and CoenWarmer committed Feb 15, 2024
1 parent fc10329 commit 80fcc74
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 198 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,10 @@ export const TopValues: FC<Props> = ({ stats, fieldFormat, barColor, compressed,
>
{Array.isArray(topValues)
? topValues.map((value) => {
const fieldValue =
value.key_as_string ?? (value.key ? value.key.toString() : EMPTY_EXAMPLE);
const fieldValue = value.key_as_string ?? (value.key ? value.key.toString() : '');
const displayValue = fieldValue ?? EMPTY_EXAMPLE;
return (
<EuiFlexGroup gutterSize="xs" alignItems="center" key={fieldValue}>
<EuiFlexGroup gutterSize="xs" alignItems="center" key={displayValue}>
<EuiFlexItem data-test-subj="dataVisualizerFieldDataTopValueBar">
<EuiProgress
value={value.percent}
Expand All @@ -136,7 +136,7 @@ export const TopValues: FC<Props> = ({ stats, fieldFormat, barColor, compressed,
/>
</EuiFlexItem>
{fieldName !== undefined &&
fieldValue !== undefined &&
displayValue !== undefined &&
onAddFilter !== undefined ? (
<div
css={css`
Expand All @@ -151,10 +151,10 @@ export const TopValues: FC<Props> = ({ stats, fieldFormat, barColor, compressed,
'xpack.dataVisualizer.dataGrid.field.addFilterAriaLabel',
{
defaultMessage: 'Filter for {fieldName}: "{value}"',
values: { fieldName, value: fieldValue },
values: { fieldName, value: displayValue },
}
)}
data-test-subj={`dvFieldDataTopValuesAddFilterButton-${fieldName}-${fieldValue}`}
data-test-subj={`dvFieldDataTopValuesAddFilterButton-${fieldName}-${displayValue}`}
style={{
minHeight: 'auto',
minWidth: 'auto',
Expand All @@ -172,10 +172,10 @@ export const TopValues: FC<Props> = ({ stats, fieldFormat, barColor, compressed,
'xpack.dataVisualizer.dataGrid.field.removeFilterAriaLabel',
{
defaultMessage: 'Filter out {fieldName}: "{value}"',
values: { fieldName, value: fieldValue },
values: { fieldName, value: displayValue },
}
)}
data-test-subj={`dvFieldDataTopValuesExcludeFilterButton-${fieldName}-${fieldValue}`}
data-test-subj={`dvFieldDataTopValuesExcludeFilterButton-${fieldName}-${displayValue}`}
style={{
minHeight: 'auto',
minWidth: 'auto',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import { mlTimefilterRefresh$, useTimefilter } from '@kbn/ml-date-picker';
import { merge } from 'rxjs';
import { RandomSampler } from '@kbn/ml-random-sampler-utils';
import { mapAndFlattenFilters } from '@kbn/data-plugin/public';
import { Query } from '@kbn/es-query';
import { buildEsQuery, Query } from '@kbn/es-query';
import { SearchQueryLanguage } from '@kbn/ml-query-utils';
import { createMergedEsQuery } from '../../index_data_visualizer/utils/saved_search_utils';
import { getEsQueryConfig } from '@kbn/data-plugin/common';
import { useDataDriftStateManagerContext } from '../../data_drift/use_state_manager';
import type { InitialSettings } from '../../data_drift/use_data_drift_result';
import {
Expand Down Expand Up @@ -74,7 +74,7 @@ export const useData = (
() => {
const searchQuery =
searchString !== undefined && searchQueryLanguage !== undefined
? { query: searchString, language: searchQueryLanguage }
? ({ query: searchString, language: searchQueryLanguage } as Query)
: undefined;

const timefilterActiveBounds = timeRange ?? timefilter.getActiveBounds();
Expand All @@ -90,24 +90,24 @@ export const useData = (
runtimeFieldMap: selectedDataView.getRuntimeMappings(),
};

const refQuery = createMergedEsQuery(
searchQuery,
const refQuery = buildEsQuery(
selectedDataView,
searchQuery ?? [],
mapAndFlattenFilters([
...queryManager.filterManager.getFilters(),
...(referenceStateManager.filters ?? []),
]),
selectedDataView,
uiSettings
uiSettings ? getEsQueryConfig(uiSettings) : undefined
);

const compQuery = createMergedEsQuery(
searchQuery,
const compQuery = buildEsQuery(
selectedDataView,
searchQuery ?? [],
mapAndFlattenFilters([
...queryManager.filterManager.getFilters(),
...(comparisonStateManager.filters ?? []),
]),
selectedDataView,
uiSettings
uiSettings ? getEsQueryConfig(uiSettings) : undefined
);

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { chunk, cloneDeep, flatten } from 'lodash';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { lastValueFrom } from 'rxjs';
import { getEsQueryConfig } from '@kbn/data-plugin/common';

import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type {
Expand All @@ -30,7 +31,7 @@ import { computeChi2PValue, type Histogram } from '@kbn/ml-chi2test';
import { mapAndFlattenFilters } from '@kbn/data-plugin/public';

import type { AggregationsMultiTermsBucketKeys } from '@elastic/elasticsearch/lib/api/types';
import { createMergedEsQuery } from '../index_data_visualizer/utils/saved_search_utils';
import { buildEsQuery } from '@kbn/es-query';
import { useDataVisualizerKibana } from '../kibana_context';

import { useDataDriftStateManagerContext } from './use_state_manager';
Expand Down Expand Up @@ -758,18 +759,18 @@ export const useFetchDataComparisonResult = (

const kqlQuery =
searchString !== undefined && searchQueryLanguage !== undefined
? { query: searchString, language: searchQueryLanguage }
? ({ query: searchString, language: searchQueryLanguage } as Query)
: undefined;

const refDataQuery = getDataComparisonQuery({
searchQuery: createMergedEsQuery(
kqlQuery,
searchQuery: buildEsQuery(
currentDataView,
kqlQuery ?? [],
mapAndFlattenFilters([
...queryManager.filterManager.getFilters(),
...(referenceStateManager.filters ?? []),
]),
currentDataView,
uiSettings
uiSettings ? getEsQueryConfig(uiSettings) : undefined
),
datetimeField: currentDataView?.timeFieldName,
runtimeFields,
Expand Down Expand Up @@ -827,14 +828,14 @@ export const useFetchDataComparisonResult = (
setLoaded(0.25);

const prodDataQuery = getDataComparisonQuery({
searchQuery: createMergedEsQuery(
kqlQuery,
searchQuery: buildEsQuery(
currentDataView,
kqlQuery ?? [],
mapAndFlattenFilters([
...queryManager.filterManager.getFilters(),
...(comparisonStateManager.filters ?? []),
]),
currentDataView,
uiSettings
uiSettings ? getEsQueryConfig(uiSettings) : undefined
),
datetimeField: currentDataView?.timeFieldName,
runtimeFields,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { css } from '@emotion/react';
import React, { FC, useEffect, useMemo, useState, useCallback, useRef } from 'react';
import type { Required } from 'utility-types';
import { getEsQueryConfig } from '@kbn/data-plugin/common';

import {
useEuiBreakpoint,
Expand All @@ -21,7 +22,7 @@ import {
EuiTitle,
} from '@elastic/eui';

import { type Filter, FilterStateStore, type Query } from '@kbn/es-query';
import { type Filter, FilterStateStore, type Query, buildEsQuery } from '@kbn/es-query';
import { generateFilters } from '@kbn/data-plugin/public';
import { DataView, DataViewField } from '@kbn/data-views-plugin/public';
import { usePageUrlState, useUrlState } from '@kbn/ml-url-state';
Expand Down Expand Up @@ -62,7 +63,6 @@ import { DocumentCountContent } from '../../../common/components/document_count_
import { OMIT_FIELDS } from '../../../../../common/constants';
import { SearchPanel } from '../search_panel';
import { ActionsPanel } from '../actions_panel';
import { createMergedEsQuery } from '../../utils/saved_search_utils';
import { DataVisualizerDataViewManagement } from '../data_view_management';
import type { GetAdditionalLinks } from '../../../common/components/results_links';
import { useDataVisualizerGridData } from '../../hooks/use_data_visualizer_grid_data';
Expand Down Expand Up @@ -389,14 +389,14 @@ export const IndexDataVisualizerView: FC<IndexDataVisualizerViewProps> = (dataVi
language: searchQueryLanguage,
};

const combinedQuery = createMergedEsQuery(
const combinedQuery = buildEsQuery(
currentDataView,
{
query: searchString || '',
language: searchQueryLanguage,
},
data.query.filterManager.getFilters() ?? [],
currentDataView,
uiSettings
uiSettings ? getEsQueryConfig(uiSettings) : undefined
);

setSearchParams({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
* 2.0.
*/

import type { Filter, Query, TimeRange } from '@kbn/es-query';
import { buildEsQuery, Filter, Query, TimeRange } from '@kbn/es-query';
import { i18n } from '@kbn/i18n';
import React, { useEffect, useState } from 'react';
import { isDefined } from '@kbn/ml-is-defined';
import { DataView } from '@kbn/data-views-plugin/common';
import type { SearchQueryLanguage } from '@kbn/ml-query-utils';
import { createMergedEsQuery } from '../../utils/saved_search_utils';
import { getEsQueryConfig } from '@kbn/data-plugin/common';
import { useDataVisualizerKibana } from '../../../kibana_context';

export const SearchPanelContent = ({
Expand Down Expand Up @@ -63,16 +63,17 @@ export const SearchPanelContent = ({
const searchHandler = ({ query, filters }: { query?: Query; filters?: Filter[] }) => {
const mergedQuery = isDefined(query) ? query : searchInput;
const mergedFilters = isDefined(filters) ? filters : queryManager.filterManager.getFilters();

try {
if (mergedFilters) {
queryManager.filterManager.setFilters(mergedFilters);
}

const combinedQuery = createMergedEsQuery(
mergedQuery,
queryManager.filterManager.getFilters() ?? [],
const combinedQuery = buildEsQuery(
dataView,
uiSettings
mergedQuery ? [mergedQuery] : [],
queryManager.filterManager.getFilters() ?? [],
uiSettings ? getEsQueryConfig(uiSettings) : undefined
);

setSearchParams({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,11 @@ export const useDataVisualizerGridData = (
});

if (searchData === undefined || dataVisualizerListState.searchString !== '') {
if (dataVisualizerListState.filters) {
if (filterManager) {
const globalFilters = filterManager?.getGlobalFilters();

if (filterManager) filterManager.setFilters(dataVisualizerListState.filters);
if (dataVisualizerListState.filters)
filterManager.setFilters(dataVisualizerListState.filters);
if (globalFilters) filterManager?.addFilters(globalFilters);
}
return {
Expand Down Expand Up @@ -169,6 +170,7 @@ export const useDataVisualizerGridData = (
currentFilters,
}),
lastRefresh,
data.query.filterManager,
]);

const _timeBuckets = useTimeBuckets();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,10 @@
* 2.0.
*/

import {
getQueryFromSavedSearchObject,
createMergedEsQuery,
getEsQueryFromSavedSearch,
} from './saved_search_utils';
import { getQueryFromSavedSearchObject, getEsQueryFromSavedSearch } from './saved_search_utils';
import type { SavedSearchSavedObject } from '../../../../common/types';
import type { SavedSearch } from '@kbn/saved-search-plugin/public';
import { type Filter, FilterStateStore } from '@kbn/es-query';
import { FilterStateStore } from '@kbn/es-query';
import { stubbedSavedObjectIndexPattern } from '@kbn/data-views-plugin/common/data_view.stub';
import { DataView } from '@kbn/data-views-plugin/public';
import { fieldFormatsMock } from '@kbn/field-formats-plugin/common/mocks';
Expand Down Expand Up @@ -217,80 +213,6 @@ describe('getQueryFromSavedSearchObject()', () => {
});
});

describe('createMergedEsQuery()', () => {
const luceneQuery = {
query: 'responsetime:>50',
language: 'lucene',
};
const kqlQuery = {
query: 'responsetime > 49',
language: 'kuery',
};
const mockFilters: Filter[] = [
{
meta: {
index: '90a978e0-1c80-11ec-b1d7-f7e5cf21b9e0',
negate: false,
disabled: false,
alias: null,
type: 'phrase',
key: 'airline',
params: {
query: 'ASA',
},
},
query: {
match: {
airline: {
query: 'ASA',
type: 'phrase',
},
},
},
$state: {
store: 'appState' as FilterStateStore,
},
},
];

it('return formatted ES bool query with both the original query and filters combined', () => {
expect(createMergedEsQuery(luceneQuery, mockFilters)).toEqual({
bool: {
filter: [{ match_phrase: { airline: { query: 'ASA' } } }],
must: [{ query_string: { query: 'responsetime:>50' } }],
must_not: [],
should: [],
},
});
expect(createMergedEsQuery(kqlQuery, mockFilters)).toEqual({
bool: {
filter: [{ match_phrase: { airline: { query: 'ASA' } } }],
minimum_should_match: 1,
must_not: [],
should: [{ range: { responsetime: { gt: '49' } } }],
},
});
});
it('return formatted ES bool query without filters ', () => {
expect(createMergedEsQuery(luceneQuery)).toEqual({
bool: {
filter: [],
must: [{ query_string: { query: 'responsetime:>50' } }],
must_not: [],
should: [],
},
});
expect(createMergedEsQuery(kqlQuery)).toEqual({
bool: {
filter: [],
minimum_should_match: 1,
must_not: [],
should: [{ range: { responsetime: { gt: '49' } } }],
},
});
});
});

describe('getEsQueryFromSavedSearch()', () => {
it('return undefined if saved search is not provided', () => {
expect(
Expand Down
Loading

0 comments on commit 80fcc74

Please sign in to comment.