Skip to content

Commit

Permalink
Improve SearchSource SearchRequest type (#186862)
Browse files Browse the repository at this point in the history
## Summary

Improves the `SearchRequest` type exported from the data plugin. Prior
to this PR, it was just a `Record<string, any>`. This is just one step
in moving toward the correct type.

### 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: Davis McPhee <[email protected]>
  • Loading branch information
lukasolson and davismcphee authored Jul 23, 2024
1 parent 9be68ee commit 375a699
Show file tree
Hide file tree
Showing 15 changed files with 108 additions and 81 deletions.
1 change: 1 addition & 0 deletions packages/kbn-discover-utils/src/__mocks__/data_view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ export const buildDataViewMock = ({
return dataViewFields.find((field) => field.name === timeFieldName);
},
getRuntimeField: () => null,
getAllowHidden: () => false,
setFieldCount: jest.fn(),
} as unknown as DataView;

Expand Down
8 changes: 2 additions & 6 deletions packages/kbn-generate-csv/src/lib/search_cursor_pit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@
import type { estypes } from '@elastic/elasticsearch';
import type { Logger } from '@kbn/core/server';
import { lastValueFrom } from 'rxjs';
import {
ES_SEARCH_STRATEGY,
type ISearchSource,
type SearchRequest,
} from '@kbn/data-plugin/common';
import { ES_SEARCH_STRATEGY, type ISearchSource } from '@kbn/data-plugin/common';
import { SearchCursor, type SearchCursorClients, type SearchCursorSettings } from './search_cursor';
import { i18nTexts } from './i18n_texts';

Expand Down Expand Up @@ -74,7 +70,7 @@ export class SearchCursorPit extends SearchCursor {
return pitId;
}

protected async searchWithPit(searchBody: SearchRequest) {
protected async searchWithPit(searchBody: estypes.SearchRequest) {
const { maxConcurrentShardRequests, scroll, taskInstanceFields } = this.settings;

// maxConcurrentShardRequests=0 is not supported
Expand Down
8 changes: 2 additions & 6 deletions packages/kbn-generate-csv/src/lib/search_cursor_scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ import type { estypes } from '@elastic/elasticsearch';
import { lastValueFrom } from 'rxjs';
import type { Logger } from '@kbn/core/server';
import type { IEsSearchResponse } from '@kbn/search-types';
import {
ES_SEARCH_STRATEGY,
type ISearchSource,
type SearchRequest,
} from '@kbn/data-plugin/common';
import { ES_SEARCH_STRATEGY, type ISearchSource } from '@kbn/data-plugin/common';
import { SearchCursor, type SearchCursorClients, type SearchCursorSettings } from './search_cursor';
import { i18nTexts } from './i18n_texts';

Expand All @@ -32,7 +28,7 @@ export class SearchCursorScroll extends SearchCursor {
// The first search query begins the scroll context in ES
public async initialize() {}

private async scan(searchBody: SearchRequest) {
private async scan(searchBody: estypes.SearchRequest) {
const { includeFrozen, maxConcurrentShardRequests, scroll, taskInstanceFields } = this.settings;

// maxConcurrentShardRequests=0 is not supported
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import { Observable } from 'rxjs';

import { schema } from '@kbn/config-schema';
import { CoreSetup, ElasticsearchClient } from '@kbn/core/server';
import { SearchRequest } from '@kbn/data-plugin/common';
import { getKbnServerError, reportServerError } from '@kbn/kibana-utils-plugin/server';
import { PluginSetup as UnifiedSearchPluginSetup } from '@kbn/unified-search-plugin/server';

import type { SearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { OptionsListRequestBody, OptionsListResponse } from '../../common/options_list/types';
import { getValidationAggregationBuilder } from './options_list_validation_queries';
import { getSuggestionAggregationBuilder } from './suggestion_queries';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,15 @@ export function getSearchParamsFromRequest(
const searchParams = getSearchParams(getConfig);
// eslint-disable-next-line @typescript-eslint/naming-convention
const { track_total_hits, ...body } = searchRequest.body;
const dataView = typeof searchRequest.index !== 'string' ? searchRequest.index : undefined;
const index = dataView?.title ?? `${searchRequest.index}`;

return {
index: searchRequest.index.title || searchRequest.index,
index,
body,
// @ts-ignore
track_total_hits,
...(searchRequest.index?.allowHidden && { expand_wildcards: 'all' }),
...(dataView?.getAllowHidden() && { expand_wildcards: 'all' }),
...searchParams,
};
}
8 changes: 7 additions & 1 deletion src/plugins/data/common/search/search_source/fetch/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
* Side Public License, v 1.
*/
import type { IKibanaSearchResponse } from '@kbn/search-types';
import type { DataView } from '@kbn/data-views-plugin/common';
import type { AggregateQuery, Filter, Query } from '@kbn/es-query';
import { SearchSourceSearchOptions } from '../../..';
import { GetConfigFn } from '../../../types';

Expand All @@ -17,7 +19,11 @@ import { GetConfigFn } from '../../../types';
* where `ISearchRequestParams` is used externally instead.
* FIXME: replace with estypes.SearchRequest?
*/
export type SearchRequest = Record<string, any>;
export type SearchRequest<T extends Record<string, any> = Record<string, any>> = {
index?: DataView | string;
query?: Array<Query | AggregateQuery>;
filters?: Filter[] | (() => Filter[]);
} & Omit<T, 'index' | 'query' | 'filters'>;

export interface FetchHandlers {
getConfig: GetConfigFn;
Expand Down
21 changes: 9 additions & 12 deletions src/plugins/data/common/search/search_source/query_to_fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import { DataViewLazy } from '@kbn/data-views-plugin/common';
import { fromKueryExpression, getKqlFieldNames } from '@kbn/es-query';
import { fromKueryExpression, getKqlFieldNames, isFilter, isOfQueryType } from '@kbn/es-query';
import type { SearchRequest } from './fetch';
import { EsQuerySortValue } from '../..';

Expand All @@ -25,23 +25,20 @@ export async function queryToFields({
const sortArr = Array.isArray(sort) ? sort : [sort];
fields.push(...sortArr.flatMap((s) => Object.keys(s)));
}
for (const query of request.query) {
for (const query of (request.query ?? []).filter(isOfQueryType)) {
if (query.query && query.language === 'kuery') {
const nodes = fromKueryExpression(query.query);
const queryFields = getKqlFieldNames(nodes);
fields = fields.concat(queryFields);
}
}
const filters = request.filters;
if (filters) {
const filtersArr = Array.isArray(filters) ? filters : [filters];
for (const f of filtersArr) {
// unified search bar filters have meta object and key (regular filters)
// unified search bar "custom" filters ("Edit as query DSL", where meta.key is not present but meta is)
// Any other Elasticsearch query DSL filter that gets passed in by consumers (not coming from unified search, and these probably won't have a meta key at all)
if (f?.meta?.key && f.meta.disabled !== true) {
fields.push(f.meta.key);
}
const { filters = [] } = request;
for (const f of typeof filters === 'function' ? filters() : filters) {
// unified search bar filters have meta object and key (regular filters)
// unified search bar "custom" filters ("Edit as query DSL", where meta.key is not present but meta is)
// Any other Elasticsearch query DSL filter that gets passed in by consumers (not coming from unified search, and these probably won't have a meta key at all)
if (isFilter(f) && f?.meta?.key && f.meta.disabled !== true) {
fields.push(f.meta.key);
}
}

Expand Down
19 changes: 13 additions & 6 deletions src/plugins/data/common/search/search_source/search_source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,14 @@ const indexPattern = {
fields: [{ name: 'foo-bar' }, { name: 'field1' }, { name: 'field2' }, { name: '_id' }],
getComputedFields,
getSourceFiltering: () => mockSource,
getAllowHidden: jest.fn(),
} as unknown as DataView;

const indexPattern2 = {
title: 'foo',
getComputedFields,
getSourceFiltering: () => mockSource2,
getAllowHidden: jest.fn(),
} as unknown as DataView;

const fields3 = [{ name: 'foo-bar' }, { name: 'field1' }, { name: 'field2' }];
Expand Down Expand Up @@ -1474,10 +1476,15 @@ describe('SearchSource', () => {
return buildExpression(ast).toString();
}

beforeEach(() => {
searchSource = new SearchSource({}, searchSourceDependencies);
searchSource.setField('index', indexPattern);
});

test('should generate an expression AST', () => {
expect(toString(searchSource.toExpressionAst())).toMatchInlineSnapshot(`
"kibana_context
| esdsl dsl=\\"{}\\""
| esdsl dsl=\\"{}\\" index=\\"1234\\""
`);
});

Expand All @@ -1486,7 +1493,7 @@ describe('SearchSource', () => {

expect(toString(searchSource.toExpressionAst())).toMatchInlineSnapshot(`
"kibana_context q={kql q=\\"something\\"}
| esdsl dsl=\\"{}\\""
| esdsl dsl=\\"{}\\" index=\\"1234\\""
`);
});

Expand All @@ -1504,7 +1511,7 @@ describe('SearchSource', () => {
expect(toString(searchSource.toExpressionAst())).toMatchInlineSnapshot(`
"kibana_context filters={kibanaFilter query=\\"{\\\\\\"query_string\\\\\\":{\\\\\\"query\\\\\\":\\\\\\"query1\\\\\\"}}\\"}
filters={kibanaFilter query=\\"{\\\\\\"query_string\\\\\\":{\\\\\\"query\\\\\\":\\\\\\"query2\\\\\\"}}\\"}
| esdsl dsl=\\"{}\\""
| esdsl dsl=\\"{}\\" index=\\"1234\\""
`);
});

Expand All @@ -1517,7 +1524,7 @@ describe('SearchSource', () => {

expect(toString(searchSource.toExpressionAst())).toMatchInlineSnapshot(`
"kibana_context filters={kibanaFilter query=\\"{\\\\\\"query_string\\\\\\":{\\\\\\"query\\\\\\":\\\\\\"query\\\\\\"}}\\"}
| esdsl dsl=\\"{}\\""
| esdsl dsl=\\"{}\\" index=\\"1234\\""
`);
});

Expand All @@ -1540,7 +1547,7 @@ describe('SearchSource', () => {
expect(toString(childSearchSource.toExpressionAst())).toMatchInlineSnapshot(`
"kibana_context q={kql q=\\"something2\\"} q={kql q=\\"something1\\"} filters={kibanaFilter query=\\"{\\\\\\"query_string\\\\\\":{\\\\\\"query\\\\\\":\\\\\\"query2\\\\\\"}}\\"}
filters={kibanaFilter query=\\"{\\\\\\"query_string\\\\\\":{\\\\\\"query\\\\\\":\\\\\\"query1\\\\\\"}}\\"}
| esdsl dsl=\\"{}\\""
| esdsl dsl=\\"{}\\" index=\\"1234\\""
`);
});

Expand All @@ -1558,7 +1565,7 @@ describe('SearchSource', () => {

expect(toString(searchSource.toExpressionAst())).toMatchInlineSnapshot(`
"kibana_context
| esdsl size=1000 dsl=\\"{}\\""
| esdsl size=1000 dsl=\\"{}\\" index=\\"1234\\""
`);
});

Expand Down
Loading

0 comments on commit 375a699

Please sign in to comment.