Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[AppServices] Allow plugin to access SearchSource SerializedFields th… #88551

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,45 +9,16 @@ returns all search source fields
<b>Signature:</b>

```typescript
getFields(): {
type?: string | undefined;
query?: import("../..").Query | undefined;
filter?: Filter | Filter[] | (() => Filter | Filter[] | undefined) | undefined;
sort?: Record<string, import("./types").SortDirectionNumeric | import("./types").SortDirection> | Record<string, import("./types").SortDirectionNumeric | import("./types").SortDirection>[] | undefined;
highlight?: any;
highlightAll?: boolean | undefined;
aggs?: any;
from?: number | undefined;
size?: number | undefined;
source?: string | boolean | string[] | undefined;
version?: boolean | undefined;
fields?: SearchFieldValue[] | undefined;
fieldsFromSource?: string | boolean | string[] | undefined;
index?: import("../..").IndexPattern | undefined;
searchAfter?: import("./types").EsQuerySearchAfter | undefined;
timeout?: string | undefined;
terminate_after?: number | undefined;
};
getFields(recurse?: boolean): SearchSourceFields;
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| recurse | <code>boolean</code> | |

<b>Returns:</b>

`{
type?: string | undefined;
query?: import("../..").Query | undefined;
filter?: Filter | Filter[] | (() => Filter | Filter[] | undefined) | undefined;
sort?: Record<string, import("./types").SortDirectionNumeric | import("./types").SortDirection> | Record<string, import("./types").SortDirectionNumeric | import("./types").SortDirection>[] | undefined;
highlight?: any;
highlightAll?: boolean | undefined;
aggs?: any;
from?: number | undefined;
size?: number | undefined;
source?: string | boolean | string[] | undefined;
version?: boolean | undefined;
fields?: SearchFieldValue[] | undefined;
fieldsFromSource?: string | boolean | string[] | undefined;
index?: import("../..").IndexPattern | undefined;
searchAfter?: import("./types").EsQuerySearchAfter | undefined;
timeout?: string | undefined;
terminate_after?: number | undefined;
}`
`SearchSourceFields`

Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,15 @@ serializes search source fields (which can later be passed to [ISearchStartSearc
<b>Signature:</b>

```typescript
getSerializedFields(): SearchSourceFields;
getSerializedFields(recurse?: boolean): SearchSourceFields;
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| recurse | <code>boolean</code> | |

<b>Returns:</b>

`SearchSourceFields`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ export declare class SearchSource
| [destroy()](./kibana-plugin-plugins-data-public.searchsource.destroy.md) | | Completely destroy the SearchSource. {<!-- -->undefined<!-- -->} |
| [fetch(options)](./kibana-plugin-plugins-data-public.searchsource.fetch.md) | | Fetch this source and reject the returned Promise on error |
| [getField(field, recurse)](./kibana-plugin-plugins-data-public.searchsource.getfield.md) | | Gets a single field from the fields |
| [getFields()](./kibana-plugin-plugins-data-public.searchsource.getfields.md) | | returns all search source fields |
| [getFields(recurse)](./kibana-plugin-plugins-data-public.searchsource.getfields.md) | | returns all search source fields |
| [getId()](./kibana-plugin-plugins-data-public.searchsource.getid.md) | | returns search source id |
| [getOwnField(field)](./kibana-plugin-plugins-data-public.searchsource.getownfield.md) | | Get the field from our own fields, don't traverse up the chain |
| [getParent()](./kibana-plugin-plugins-data-public.searchsource.getparent.md) | | Get the parent of this SearchSource {<!-- -->undefined\|searchSource<!-- -->} |
| [getSearchRequestBody()](./kibana-plugin-plugins-data-public.searchsource.getsearchrequestbody.md) | | Returns body contents of the search request, often referred as query DSL. |
| [getSerializedFields()](./kibana-plugin-plugins-data-public.searchsource.getserializedfields.md) | | serializes search source fields (which can later be passed to [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md)<!-- -->) |
| [getSerializedFields(recurse)](./kibana-plugin-plugins-data-public.searchsource.getserializedfields.md) | | serializes search source fields (which can later be passed to [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md)<!-- -->) |
| [onRequestStart(handler)](./kibana-plugin-plugins-data-public.searchsource.onrequeststart.md) | | Add a handler that will be notified whenever requests start |
| [removeField(field)](./kibana-plugin-plugins-data-public.searchsource.removefield.md) | | remove field |
| [serialize()](./kibana-plugin-plugins-data-public.searchsource.serialize.md) | | Serializes the instance to a JSON string and a set of referenced objects. Use this method to get a representation of the search source which can be stored in a saved object.<!-- -->The references returned by this function can be mixed with other references in the same object, however make sure there are no name-collisions. The references will be named <code>kibanaSavedObjectMeta.searchSourceJSON.index</code> and <code>kibanaSavedObjectMeta.searchSourceJSON.filter[&lt;number&gt;].meta.index</code>.<!-- -->Using <code>createSearchSource</code>, the instance can be re-created. |
Expand Down
16 changes: 15 additions & 1 deletion src/plugins/data/common/field_formats/field_formats_registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,28 @@ import { FormatFactory } from './utils';
import { ES_FIELD_TYPES, KBN_FIELD_TYPES } from '../kbn_field_types/types';
import { UI_SETTINGS } from '../constants';
import { FieldFormatNotFoundError } from '../field_formats';
import { SerializedFieldFormat } from '../../../expressions/common/types';

export class FieldFormatsRegistry {
protected fieldFormats: Map<FieldFormatId, FieldFormatInstanceType> = new Map();
protected defaultMap: Record<string, FieldFormatConfig> = {};
protected metaParamsOptions: Record<string, any> = {};
protected getConfig?: FieldFormatsGetConfigFn;
// overriden on the public contract
public deserialize: FormatFactory = () => {
public deserialize: FormatFactory = (mapping?: SerializedFieldFormat) => {
if (!mapping) {
return new (FieldFormat.from(identity))();
}

const { id, params = {} } = mapping;
if (id) {
const Format = this.getType(id);

if (Format) {
return new Format(params, this.getConfig);
}
}

return new (FieldFormat.from(identity))();
};

Expand Down
12 changes: 9 additions & 3 deletions src/plugins/data/common/search/search_source/search_source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,13 @@ export class SearchSource {
/**
* returns all search source fields
*/
getFields() {
getFields(recurse = false): SearchSourceFields {
if (recurse) {
const parent = this.getParent();
if (parent) {
return { ...parent.getFields(recurse), ...this.fields };
}
}
return { ...this.fields };
}

Expand Down Expand Up @@ -592,8 +598,8 @@ export class SearchSource {
/**
* serializes search source fields (which can later be passed to {@link ISearchStartSearchSource})
*/
public getSerializedFields() {
const { filter: originalFilters, ...searchSourceFields } = omit(this.getFields(), [
public getSerializedFields(recurse = false) {
const { filter: originalFilters, ...searchSourceFields } = omit(this.getFields(recurse), [
'sort',
'size',
]);
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/data/common/search/tabify/tabify_docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const tabifyDocs = (

const rows = esResponse.hits.hits
.map((hit) => {
const toConvert = params.source ? hit._source : hit.fields;
const toConvert = params.source && hit._source ? hit._source : hit.fields;
const flat = flattenHit(toConvert, index, params.shallow);
for (const [key, value] of Object.entries(flat)) {
const field = index?.fields.getByName(key);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ export const getTopNavLinks = ({
const sharingData = await getSharingData(
savedSearch.searchSource,
state.appStateContainer.getState(),
services.uiSettings,
getFieldCounts
services.uiSettings
);
services.share.toggleShareContextMenu({
anchorElement,
Expand All @@ -104,8 +103,11 @@ export const getTopNavLinks = ({
objectId: savedSearch.id,
objectType: 'search',
sharingData: {
...sharingData,
title: savedSearch.title,
taskType: 'csv',
taskConfig: {
...sharingData,
title: savedSearch.title,
},
},
isDirty: !savedSearch.id || state.isAppStateDirty(),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,53 +15,18 @@ import { SORT_DEFAULT_ORDER_SETTING } from '../../../common';
describe('getSharingData', () => {
test('returns valid data for sharing', async () => {
const searchSourceMock = createSearchSourceMock({ index: indexPatternMock });
const result = await getSharingData(
searchSourceMock,
{ columns: [] },
({
get: (key: string) => {
if (key === SORT_DEFAULT_ORDER_SETTING) {
return 'desc';
}
return false;
},
} as unknown) as IUiSettingsClient,
() => Promise.resolve({})
);
const result = await getSharingData(searchSourceMock, { columns: [] }, ({
get: (key: string) => {
if (key === SORT_DEFAULT_ORDER_SETTING) {
return 'desc';
}
return false;
},
} as unknown) as IUiSettingsClient);
expect(result).toMatchInlineSnapshot(`
Object {
"conflictedTypesFields": Array [],
"fields": Array [],
"indexPatternId": "the-index-pattern-id",
"metaFields": Array [
"_index",
"_score",
],
"searchRequest": Object {
"body": Object {
"_source": Object {},
"fields": Array [],
"query": Object {
"bool": Object {
"filter": Array [],
"must": Array [],
"must_not": Array [],
"should": Array [],
},
},
"script_fields": Object {},
"sort": Array [
Object {
"_score": Object {
"order": "desc",
},
},
],
"stored_fields": Array [
"*",
],
},
"index": "the-index-pattern-title",
"searchSource": Object {
"index": "the-index-pattern-id",
},
}
`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,53 +7,23 @@
*/

import { IUiSettingsClient } from 'kibana/public';
import { DOC_HIDE_TIME_COLUMN_SETTING, SORT_DEFAULT_ORDER_SETTING } from '../../../common';
import { SORT_DEFAULT_ORDER_SETTING } from '../../../common';
import { getSortForSearchSource } from '../angular/doc_table';
import { SearchSource } from '../../../../data/common';
import { AppState } from '../angular/discover_state';
import { SortOrder } from '../../saved_searches/types';

const getSharingDataFields = async (
getFieldCounts: () => Promise<Record<string, number>>,
selectedFields: string[],
timeFieldName: string,
hideTimeColumn: boolean
) => {
if (selectedFields.length === 1 && selectedFields[0] === '_source') {
const fieldCounts = await getFieldCounts();
return {
searchFields: undefined,
selectFields: Object.keys(fieldCounts).sort(),
};
}

const fields =
timeFieldName && !hideTimeColumn ? [timeFieldName, ...selectedFields] : selectedFields;
return {
searchFields: fields,
selectFields: fields,
};
};

/**
* Preparing data to share the current state as link or CSV/Report
*/
export async function getSharingData(
currentSearchSource: SearchSource,
state: AppState,
config: IUiSettingsClient,
getFieldCounts: () => Promise<Record<string, number>>
config: IUiSettingsClient
) {
const searchSource = currentSearchSource.createCopy();
const index = searchSource.getField('index')!;

const { searchFields, selectFields } = await getSharingDataFields(
getFieldCounts,
state.columns || [],
index.timeFieldName || '',
config.get(DOC_HIDE_TIME_COLUMN_SETTING)
);
searchSource.setField('fieldsFromSource', searchFields);
searchSource.setField(
'sort',
getSortForSearchSource(state.sort as SortOrder[], index, config.get(SORT_DEFAULT_ORDER_SETTING))
Expand All @@ -63,16 +33,7 @@ export async function getSharingData(
searchSource.removeField('aggs');
searchSource.removeField('size');

const body = await searchSource.getSearchRequestBody();

return {
searchRequest: {
index: index.title,
body,
},
fields: selectFields,
metaFields: index.metaFields,
conflictedTypesFields: index.fields.filter((f) => f.type === 'conflict').map((f) => f.name),
indexPatternId: index.id,
searchSource: searchSource.getSerializedFields(true),
};
}