Skip to content

Commit

Permalink
Make Indices discoverable in Kibana Global Search (elastic#175473)
Browse files Browse the repository at this point in the history
## Summary
Added a search provider to return only visible indices and land in the
overview page once clicked or selected.

### No indices available
<img width="1046" alt="Screenshot 2024-01-24 at 2 48 58 PM"
src="https://github.com/elastic/kibana/assets/150824886/82d5a997-2d0b-42e0-8818-2f4b83170230">

### Matched index shows up
<img width="920" alt="Screenshot 2024-01-24 at 2 42 13 PM"
src="https://github.com/elastic/kibana/assets/150824886/59bd676c-f5c3-4b10-a1ae-cd8b4008c81e">

### Shows all matched index
<img width="1048" alt="Screenshot 2024-01-24 at 2 50 09 PM"
src="https://github.com/elastic/kibana/assets/150824886/30877185-ac9c-4fe2-b859-d597dd3941b1">


### Checklist

Delete any items that are not applicable to this PR.

- [X] 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
- [x] [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
- [x] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [x] 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)
- [x] 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))
- [x] 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 fkanout committed Mar 4, 2024
1 parent ec729ee commit bff8ac3
Show file tree
Hide file tree
Showing 11 changed files with 317 additions and 2 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions x-pack/plugins/enterprise_search/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ import { workplaceSearchTelemetryType } from './saved_objects/workplace_search/t
import { GlobalConfigService } from './services/global_config_service';
import { uiSettings as enterpriseSearchUISettings } from './ui_settings';

import { getIndicesSearchResultProvider } from './utils/indices_search_result_provider';
import { getSearchResultProvider } from './utils/search_result_provider';

import { ConfigType } from '.';
Expand Down Expand Up @@ -343,6 +344,7 @@ export class EnterpriseSearchPlugin implements Plugin {

if (globalSearch) {
globalSearch.registerResultProvider(getSearchResultProvider(http.basePath, config));
globalSearch.registerResultProvider(getIndicesSearchResultProvider(http.basePath));
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
/*
* 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 { NEVER, lastValueFrom } from 'rxjs';

import { IScopedClusterClient } from '@kbn/core/server';

import { ENTERPRISE_SEARCH_CONTENT_PLUGIN } from '../../common/constants';

import { getIndicesSearchResultProvider } from './indices_search_result_provider';

describe('Enterprise Search - indices search provider', () => {
const basePathMock = {
prepend: (input: string) => `/kbn${input}`,
} as any;

const indicesSearchResultProvider = getIndicesSearchResultProvider(basePathMock);

const regularIndexResponse = {
'search-github-api': {
aliases: {},
},
'search-msft-sql-index': {
aliases: {},
},
};

const mockClient = {
asCurrentUser: {
count: jest.fn().mockReturnValue({ count: 100 }),
indices: {
get: jest.fn(),
stats: jest.fn(),
},
security: {
hasPrivileges: jest.fn(),
},
},
asInternalUser: {},
};
const client = mockClient as unknown as IScopedClusterClient;
mockClient.asCurrentUser.indices.get.mockResolvedValue(regularIndexResponse);

const githubIndex = {
id: 'search-github-api',
score: 75,
title: 'search-github-api',
type: 'Index',
url: {
path: `${ENTERPRISE_SEARCH_CONTENT_PLUGIN.URL}/search_indices/search-github-api`,
prependBasePath: true,
},
icon: '/kbn/plugins/enterpriseSearch/assets/source_icons/index.svg',
};

const msftIndex = {
id: 'search-msft-sql-index',
score: 75,
title: 'search-msft-sql-index',
type: 'Index',
url: {
path: `${ENTERPRISE_SEARCH_CONTENT_PLUGIN.URL}/search_indices/search-msft-sql-index`,
prependBasePath: true,
},
icon: '/kbn/plugins/enterpriseSearch/assets/source_icons/index.svg',
};

beforeEach(() => {});

afterEach(() => {
jest.clearAllMocks();
});

describe('find', () => {
it('returns formatted results', async () => {
const results = await lastValueFrom(
indicesSearchResultProvider.find(
{ term: 'search-github-api' },
{
aborted$: NEVER,
client,
maxResults: 100,
preference: '',
},
{} as any
)
);
expect(results).toEqual([{ ...githubIndex, score: 100 }]);
});

it('returns all matched results', async () => {
const results = await lastValueFrom(
indicesSearchResultProvider.find(
{ term: 'search' },
{
aborted$: NEVER,
client,
maxResults: 100,
preference: '',
},
{} as any
)
);
expect(results).toEqual([
{ ...githubIndex, score: 90 },
{ ...msftIndex, score: 90 },
]);
});

it('returns all indices on empty string', async () => {
const results = await lastValueFrom(
indicesSearchResultProvider.find(
{ term: '' },
{
aborted$: NEVER,
client,
maxResults: 100,
preference: '',
},
{} as any
)
);
expect(results).toHaveLength(0);
});

it('respect maximum results', async () => {
const results = await lastValueFrom(
indicesSearchResultProvider.find(
{ term: 'search' },
{
aborted$: NEVER,
client,
maxResults: 1,
preference: '',
},
{} as any
)
);
expect(results).toEqual([{ ...githubIndex, score: 90 }]);
});

describe('returns empty results', () => {
it('when term does not match with created indices', async () => {
const results = await lastValueFrom(
indicesSearchResultProvider.find(
{ term: 'sample' },
{
aborted$: NEVER,
client,
maxResults: 100,
preference: '',
},
{} as any
)
);
expect(results).toEqual([]);
});

it('if client is undefined', async () => {
const results = await lastValueFrom(
indicesSearchResultProvider.find(
{ term: 'sample' },
{
aborted$: NEVER,
client: undefined,
maxResults: 100,
preference: '',
},
{} as any
)
);
expect(results).toEqual([]);
});

it('if tag is specified', async () => {
const results = await lastValueFrom(
indicesSearchResultProvider.find(
{ term: 'search', tags: ['tag'] },
{
aborted$: NEVER,
client,
maxResults: 100,
preference: '',
},
{} as any
)
);
expect(results).toEqual([]);
});

it('if unknown type is specified', async () => {
const results = await lastValueFrom(
indicesSearchResultProvider.find(
{ term: 'search', types: ['tag'] },
{
aborted$: NEVER,
client,
maxResults: 100,
preference: '',
},
{} as any
)
);
expect(results).toEqual([]);
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* 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 { from, takeUntil } from 'rxjs';

import { IBasePath } from '@kbn/core-http-server';
import {
GlobalSearchProviderResult,
GlobalSearchResultProvider,
} from '@kbn/global-search-plugin/server';
import { i18n } from '@kbn/i18n';

import { ENTERPRISE_SEARCH_CONTENT_PLUGIN } from '../../common/constants';

import { getIndexData } from '../lib/indices/utils/get_index_data';

export function getIndicesSearchResultProvider(basePath: IBasePath): GlobalSearchResultProvider {
return {
find: ({ term, types, tags }, { aborted$, client, maxResults }) => {
if (!client || !term || tags || (types && !types.includes('indices'))) {
return from([[]]);
}
const fetchIndices = async (): Promise<GlobalSearchProviderResult[]> => {
const { indexNames } = await getIndexData(client, false, false, term);

const searchResults: GlobalSearchProviderResult[] = indexNames
.map((indexName) => {
let score = 0;
const searchTerm = (term || '').toLowerCase();
const searchName = indexName.toLowerCase();
if (!searchTerm) {
score = 80;
} else if (searchName === searchTerm) {
score = 100;
} else if (searchName.startsWith(searchTerm)) {
score = 90;
} else if (searchName.includes(searchTerm)) {
score = 75;
}

return {
id: indexName,
title: indexName,
icon: basePath.prepend('/plugins/enterpriseSearch/assets/source_icons/index.svg'),
type: i18n.translate('xpack.enterpriseSearch.searchIndexProvider.type.name', {
defaultMessage: 'Index',
}),
url: {
path: `${ENTERPRISE_SEARCH_CONTENT_PLUGIN.URL}/search_indices/${indexName}`,
prependBasePath: true,
},
score,
};
})
.filter(({ score }) => score > 0)
.slice(0, maxResults);
return searchResults;
};
return from(fetchIndices()).pipe(takeUntil(aborted$));
},
getSearchableTypes: () => ['indices'],
id: 'enterpriseSearchIndices',
};
}
6 changes: 6 additions & 0 deletions x-pack/plugins/global_search/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import { Observable } from 'rxjs';
import { Serializable } from '@kbn/utility-types';
import { IScopedClusterClient } from '@kbn/core/server';

/**
* Options provided to {@link GlobalSearchResultProvider | a result provider}'s `find` method.
Expand All @@ -26,6 +27,11 @@ export interface GlobalSearchProviderFindOptions {
* this can (and should) be used to cancel any pending asynchronous task and complete the result observable from within the provider.
*/
aborted$: Observable<void>;
/**
* A ES client of type IScopedClusterClient is passed to the `find` call.
* When performing calls to ES, the interested provider can utilize this parameter to identify the specific cluster.
*/
client?: IScopedClusterClient;
/**
* The total maximum number of results (including all batches, not per emission) that should be returned by the provider for a given `find` request.
* Any result emitted exceeding this quota will be ignored by the service and not emitted to the consumer.
Expand Down
6 changes: 6 additions & 0 deletions x-pack/plugins/global_search/public/services/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { Observable } from 'rxjs';
import { IScopedClusterClient } from '@kbn/core/server';

/**
* Options for the server-side {@link GlobalSearchPluginStart.find | find API}
Expand All @@ -25,4 +26,9 @@ export interface GlobalSearchFindOptions {
* If/when provided and emitting, the result observable will be completed and no further result emission will be performed.
*/
aborted$?: Observable<void>;
/**
* A ES client of type IScopedClusterClient is passed to the `find` call.
* When performing calls to ES, the interested provider can utilize this parameter to identify the specific cluster.
*/
client?: IScopedClusterClient;
}
3 changes: 2 additions & 1 deletion x-pack/plugins/global_search/server/routes/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ export const registerInternalFindRoute = (router: GlobalSearchRouter) => {
const { params, options } = req.body;
try {
const globalSearch = await ctx.globalSearch;
const { client } = (await ctx.core).elasticsearch;
const allResults = await globalSearch
.find(params, { ...options, aborted$: req.events.aborted$ })
.find(params, { ...options, aborted$: req.events.aborted$, client })
.pipe(
map((batch) => batch.results),
reduce((acc, results) => [...acc, ...results])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ describe('POST /internal/global_search/find', () => {
{
preference: 'custom-pref',
aborted$: expect.any(Object),
client: expect.any(Object),
}
);
});
Expand Down
6 changes: 6 additions & 0 deletions x-pack/plugins/global_search/server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
Capabilities,
IRouter,
CustomRequestHandlerContext,
IScopedClusterClient,
} from '@kbn/core/server';
import {
GlobalSearchBatchedResults,
Expand Down Expand Up @@ -92,6 +93,11 @@ export interface GlobalSearchFindOptions {
* If/when provided and emitting, no further result emission will be performed and the result observable will be completed.
*/
aborted$?: Observable<void>;
/**
* A ES client of type IScopedClusterClient is passed to the `find` call.
* When performing calls to ES, the interested provider can utilize this parameter to identify the specific cluster.
*/
client?: IScopedClusterClient;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ describe('resultToOption', () => {
);
});

it('uses icon for `index` type', () => {
const input = createSearchResult({ type: 'index', icon: 'index-icon' });
expect(resultToOption(input, [])).toEqual(
expect.objectContaining({
icon: { type: 'index-icon' },
})
);
});

it('does not use icon for other types', () => {
const input = createSearchResult({ type: 'dashboard', icon: 'dash-icon' });
expect(resultToOption(input, [])).toEqual(
Expand Down
Loading

0 comments on commit bff8ac3

Please sign in to comment.