[8.x] [Onboarding] delete document action (#195263) (#195359)

# Backport

This will backport the following commits from `main` to `8.x`:
- [[Onboarding] delete document action
(#195263)](https://github.com/elastic/kibana/pull/195263)

<!--- Backport version: 9.4.3 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Joe
McElroy","email":"joseph.mcelroy@elastic.co"},"sourceCommit":{"committedDate":"2024-10-08T08:38:54Z","message":"[Onboarding]
delete document action (#195263)\n\n## Summary\r\n\r\nAbility to delete
documents.\r\n\r\nI had to reduce the capability of the search_documents
hook so the\r\ndelete document hook can optimistically update the
change. These\r\ncapabilities were not in
use.\r\n\r\n\r\n![image](https://github.com/user-attachments/assets/85df2146-e6d5-4812-b825-bbbca6049215)\r\n\r\n###
Checklist\r\n\r\nDelete any items that are not applicable to this
PR.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials\r\n- [ ] [Unit
or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is
usable by keyboard only (learn more\r\nabout [keyboard
accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI
touched in this PR does not create any new axe failures\r\n(run axe in
browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n-
[ ] If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This renders correctly on smaller devices using a
responsive\r\nlayout. (You can test this [in
your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n-
[ ] This was checked for
[cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n###
Risk Matrix\r\n\r\nDelete this section if it is not applicable to this
PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other
developers to\r\nidentify risks that should be tested prior to the
change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider
some of the following examples\r\nand how they may potentially impact
the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes
|\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n|
Multiple Spaces&mdash;unexpected behavior in non-default Kibana
Space.\r\n| Low | High | Integration tests will verify that all features
are still\r\nsupported in non-default Kibana Space and when user
switches between\r\nspaces. |\r\n| Multiple nodes&mdash;Elasticsearch
polling might have race conditions\r\nwhen multiple Kibana nodes are
polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so
executing them multiple times will not result\r\nin logical error, but
will degrade performance. To test for this case we\r\nadd plenty of unit
tests around this logic and document manual testing\r\nprocedure. |\r\n|
Code should gracefully handle cases when feature X or plugin Y
are\r\ndisabled. | Medium | High | Unit tests will verify that any
feature flag\r\nor plugin combination still results in our service
operational. |\r\n| [See more potential
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
|\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for
breaking API changes and was
[labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)","sha":"faa74d23aa625fca7ace0313386fac4f3134e9c7","branchLabelMapping":{"^v9.0.0$":"main","^v8.16.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","Team:EnterpriseSearch","backport:prev-minor"],"title":"[Onboarding]
delete document
action","number":195263,"url":"https://github.com/elastic/kibana/pull/195263","mergeCommit":{"message":"[Onboarding]
delete document action (#195263)\n\n## Summary\r\n\r\nAbility to delete
documents.\r\n\r\nI had to reduce the capability of the search_documents
hook so the\r\ndelete document hook can optimistically update the
change. These\r\ncapabilities were not in
use.\r\n\r\n\r\n![image](https://github.com/user-attachments/assets/85df2146-e6d5-4812-b825-bbbca6049215)\r\n\r\n###
Checklist\r\n\r\nDelete any items that are not applicable to this
PR.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials\r\n- [ ] [Unit
or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is
usable by keyboard only (learn more\r\nabout [keyboard
accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI
touched in this PR does not create any new axe failures\r\n(run axe in
browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n-
[ ] If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This renders correctly on smaller devices using a
responsive\r\nlayout. (You can test this [in
your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n-
[ ] This was checked for
[cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n###
Risk Matrix\r\n\r\nDelete this section if it is not applicable to this
PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other
developers to\r\nidentify risks that should be tested prior to the
change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider
some of the following examples\r\nand how they may potentially impact
the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes
|\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n|
Multiple Spaces&mdash;unexpected behavior in non-default Kibana
Space.\r\n| Low | High | Integration tests will verify that all features
are still\r\nsupported in non-default Kibana Space and when user
switches between\r\nspaces. |\r\n| Multiple nodes&mdash;Elasticsearch
polling might have race conditions\r\nwhen multiple Kibana nodes are
polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so
executing them multiple times will not result\r\nin logical error, but
will degrade performance. To test for this case we\r\nadd plenty of unit
tests around this logic and document manual testing\r\nprocedure. |\r\n|
Code should gracefully handle cases when feature X or plugin Y
are\r\ndisabled. | Medium | High | Unit tests will verify that any
feature flag\r\nor plugin combination still results in our service
operational. |\r\n| [See more potential
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
|\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for
breaking API changes and was
[labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)","sha":"faa74d23aa625fca7ace0313386fac4f3134e9c7"}},"sourceBranch":"main","suggestedTargetBranches":[],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","branchLabelMappingKey":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/195263","number":195263,"mergeCommit":{"message":"[Onboarding]
delete document action (#195263)\n\n## Summary\r\n\r\nAbility to delete
documents.\r\n\r\nI had to reduce the capability of the search_documents
hook so the\r\ndelete document hook can optimistically update the
change. These\r\ncapabilities were not in
use.\r\n\r\n\r\n![image](https://github.com/user-attachments/assets/85df2146-e6d5-4812-b825-bbbca6049215)\r\n\r\n###
Checklist\r\n\r\nDelete any items that are not applicable to this
PR.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials\r\n- [ ] [Unit
or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is
usable by keyboard only (learn more\r\nabout [keyboard
accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI
touched in this PR does not create any new axe failures\r\n(run axe in
browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n-
[ ] If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This renders correctly on smaller devices using a
responsive\r\nlayout. (You can test this [in
your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n-
[ ] This was checked for
[cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n###
Risk Matrix\r\n\r\nDelete this section if it is not applicable to this
PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other
developers to\r\nidentify risks that should be tested prior to the
change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider
some of the following examples\r\nand how they may potentially impact
the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes
|\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n|
Multiple Spaces&mdash;unexpected behavior in non-default Kibana
Space.\r\n| Low | High | Integration tests will verify that all features
are still\r\nsupported in non-default Kibana Space and when user
switches between\r\nspaces. |\r\n| Multiple nodes&mdash;Elasticsearch
polling might have race conditions\r\nwhen multiple Kibana nodes are
polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so
executing them multiple times will not result\r\nin logical error, but
will degrade performance. To test for this case we\r\nadd plenty of unit
tests around this logic and document manual testing\r\nprocedure. |\r\n|
Code should gracefully handle cases when feature X or plugin Y
are\r\ndisabled. | Medium | High | Unit tests will verify that any
feature flag\r\nor plugin combination still results in our service
operational. |\r\n| [See more potential
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
|\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for
breaking API changes and was
[labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)","sha":"faa74d23aa625fca7ace0313386fac4f3134e9c7"}}]}]
BACKPORT-->

Co-authored-by: Joe McElroy <joseph.mcelroy@elastic.co>
This commit is contained in:
Kibana Machine 2024-10-08 21:21:28 +11:00 committed by GitHub
parent 8c11543663
commit 7b832691e8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 266 additions and 23 deletions

View file

@ -36,6 +36,7 @@ export interface ResultProps {
showScore?: boolean;
compactCard?: boolean;
onDocumentClick?: () => void;
onDocumentDelete?: () => void;
}
export const Result: React.FC<ResultProps> = ({
@ -45,6 +46,7 @@ export const Result: React.FC<ResultProps> = ({
compactCard = true,
showScore = false,
onDocumentClick,
onDocumentDelete,
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const tooltipText =
@ -87,7 +89,10 @@ export const Result: React.FC<ResultProps> = ({
values: { id: metaData.id },
})
}
metaData={metaData}
metaData={{
...metaData,
onDocumentDelete,
}}
/>
)}
{!compactCard && (
@ -101,7 +106,10 @@ export const Result: React.FC<ResultProps> = ({
})
}
onTitleClick={onDocumentClick}
metaData={metaData}
metaData={{
...metaData,
onDocumentDelete,
}}
rightSideActions={
<EuiFlexItem grow={false}>
<EuiToolTip position="left" content={toolTipContent}>

View file

@ -70,6 +70,7 @@ const MetadataPopover: React.FC<MetaDataProps> = ({
size="xs"
iconType="iInCircle"
color="primary"
data-test-subj="documentMetadataButton"
onClick={(e: React.MouseEvent<HTMLElement>) => {
e.stopPropagation();
setPopoverIsOpen(!popoverIsOpen);
@ -121,8 +122,10 @@ const MetadataPopover: React.FC<MetaDataProps> = ({
iconType="trash"
color="danger"
size="s"
data-test-subj="deleteDocumentButton"
onClick={(e: React.MouseEvent<HTMLElement>) => {
e.stopPropagation();
onDocumentDelete();
closePopover();
}}
fullWidth

View file

@ -9,3 +9,5 @@ export const GET_STATUS_ROUTE = '/internal/search_indices/status';
export const GET_USER_PRIVILEGES_ROUTE = '/internal/search_indices/start_privileges';
export const POST_CREATE_INDEX_ROUTE = '/internal/search_indices/indices/create';
export const INDEX_DOCUMENT_ROUTE = '/internal/search_indices/{indexName}/documents/{id}';

View file

@ -13,6 +13,7 @@ import { Result, resultMetaData, resultToField } from '@kbn/search-index-documen
import { EuiSpacer } from '@elastic/eui';
import { RecentDocsActionMessage } from './recent_docs_action_message';
import { useDeleteDocument } from '../../hooks/api/use_delete_document';
export interface DocumentListProps {
indexName: string;
@ -21,6 +22,8 @@ export interface DocumentListProps {
}
export const DocumentList = ({ indexName, docs, mappingProperties }: DocumentListProps) => {
const { mutate } = useDeleteDocument(indexName);
return (
<>
<RecentDocsActionMessage indexName={indexName} />
@ -28,7 +31,14 @@ export const DocumentList = ({ indexName, docs, mappingProperties }: DocumentLis
{docs.map((doc) => {
return (
<React.Fragment key={doc._id}>
<Result fields={resultToField(doc, mappingProperties)} metaData={resultMetaData(doc)} />
<Result
fields={resultToField(doc, mappingProperties)}
metaData={resultMetaData(doc)}
onDocumentDelete={() => {
mutate({ id: doc._id! });
}}
compactCard={false}
/>
<EuiSpacer size="s" />
</React.Fragment>
);

View file

@ -34,7 +34,6 @@ import { SearchIndexDetailsMappings } from './details_page_mappings';
import { SearchIndexDetailsSettings } from './details_page_settings';
import { SearchIndexDetailsPageMenuItemPopover } from './details_page_menu_item';
import { useIndexDocumentSearch } from '../../hooks/api/use_document_search';
import { DEFAULT_PAGE_SIZE } from '../index_documents/constants';
export const SearchIndexDetailsPage = () => {
const indexName = decodeURIComponent(useParams<{ indexName: string }>().indexName);
@ -55,10 +54,7 @@ export const SearchIndexDetailsPage = () => {
error: mappingsError,
} = useIndexMapping(indexName);
const { data: indexDocuments, isInitialLoading: indexDocumentsIsInitialLoading } =
useIndexDocumentSearch(indexName, {
pageSize: DEFAULT_PAGE_SIZE,
pageIndex: 0,
});
useIndexDocumentSearch(indexName);
const navigateToPlayground = useCallback(async () => {
const playgroundLocator = share.url.locators.get('PLAYGROUND_LOCATOR_ID');

View file

@ -9,12 +9,16 @@ export enum QueryKeys {
FetchIndex = 'fetchIndex',
FetchSearchIndicesStatus = 'fetchSearchIndicesStatus',
FetchUserStartPrivileges = 'fetchUserStartPrivileges',
SearchDocuments = 'searchDocuments',
}
export enum MutationKeys {
SearchIndicesCreateIndex = 'searchIndicesCreateIndex',
SearchIndicesDeleteDocument = 'searchIndicesDeleteDocument',
}
export const ELASTICSEARCH_URL_PLACEHOLDER = 'https://your_deployment_url';
export const API_KEY_PLACEHOLDER = 'YOUR_API_KEY';
export const INDEX_PLACEHOLDER = 'my-index';
export const DEFAULT_DOCUMENT_PAGE_SIZE = 50;

View file

@ -0,0 +1,72 @@
/*
* 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 { AcknowledgedResponseBase } from '@elastic/elasticsearch/lib/api/types';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { SearchHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { MutationKeys, QueryKeys } from '../../constants';
import { useKibana } from '../use_kibana';
import { INDEX_SEARCH_POLLING, IndexDocuments } from './use_document_search';
interface DeleteDocumentParams {
id: string;
}
export const useDeleteDocument = (indexName: string) => {
const { http } = useKibana().services;
const queryClient = useQueryClient();
const result = useMutation(
async ({ id }: DeleteDocumentParams) => {
const response = await http.delete<AcknowledgedResponseBase>(
`/internal/search_indices/${indexName}/documents/${id}`
);
return response.acknowledged;
},
{
mutationKey: [MutationKeys.SearchIndicesDeleteDocument, indexName],
onMutate: async ({ id }: DeleteDocumentParams) => {
await queryClient.cancelQueries([QueryKeys.SearchDocuments, indexName]);
const previousData = queryClient.getQueryData<IndexDocuments>([
QueryKeys.SearchDocuments,
indexName,
]);
queryClient.setQueryData(
[QueryKeys.SearchDocuments, indexName],
(snapshot: IndexDocuments | undefined) => {
const oldData = snapshot ?? { results: { data: [] } };
return {
...oldData,
results: {
...oldData.results,
data: oldData.results.data.filter((doc: SearchHit) => doc._id !== id),
},
} as IndexDocuments;
}
);
return { previousData };
},
onSuccess: () => {
setTimeout(() => {
queryClient.invalidateQueries([QueryKeys.SearchDocuments, indexName]);
}, INDEX_SEARCH_POLLING);
},
onError: (error, _, context) => {
if (context?.previousData) {
queryClient.setQueryData([QueryKeys.SearchDocuments, indexName], context.previousData);
}
return error;
},
}
);
return { ...result };
};

View file

@ -28,8 +28,9 @@ export const useDeleteIndex = (indexName: string) => {
);
return response.acknowledged;
},
onSuccess: () => {
onSettled: () => {
queryClient.invalidateQueries([QueryKeys.FetchIndex, indexName]);
queryClient.invalidateQueries([QueryKeys.SearchDocuments, indexName]);
},
});
return { ...result };

View file

@ -10,6 +10,7 @@ import { SearchHit } from '@kbn/es-types';
import { pageToPagination, Paginate } from '@kbn/search-index-documents';
import { useQuery } from '@tanstack/react-query';
import { useKibana } from '../use_kibana';
import { QueryKeys, DEFAULT_DOCUMENT_PAGE_SIZE } from '../../constants';
export interface IndexDocuments {
meta: Pagination;
@ -18,32 +19,29 @@ export interface IndexDocuments {
const DEFAULT_PAGINATION = {
from: 0,
has_more_hits_than_total: false,
size: 10,
size: DEFAULT_DOCUMENT_PAGE_SIZE,
total: 0,
};
const pollingInterval = 5 * 1000;
export const useIndexDocumentSearch = (
indexName: string,
pagination: Omit<Pagination, 'totalItemCount'>,
searchQuery?: string
) => {
export const INDEX_SEARCH_POLLING = 5 * 1000;
export const useIndexDocumentSearch = (indexName: string) => {
const {
services: { http },
} = useKibana();
const response = useQuery({
queryKey: ['fetchIndexDocuments', pagination, searchQuery],
refetchInterval: pollingInterval,
queryKey: [QueryKeys.SearchDocuments, indexName],
refetchInterval: INDEX_SEARCH_POLLING,
refetchIntervalInBackground: true,
refetchOnWindowFocus: 'always',
queryFn: async () =>
queryFn: async ({ signal }) =>
http.post<IndexDocuments>(`/internal/serverless_search/indices/${indexName}/search`, {
body: JSON.stringify({
searchQuery,
searchQuery: '',
}),
query: {
page: pagination.pageIndex,
size: pagination.pageSize,
page: 0,
size: DEFAULT_DOCUMENT_PAGE_SIZE,
},
signal,
}),
});
return {

View file

@ -11,6 +11,7 @@ export function getErrorMessage(error: unknown, defaultMessage?: string): string
if (typeof error === 'string') {
return error;
}
if (isKibanaServerError(error)) {
return error.body.message;
}

View file

@ -0,0 +1,56 @@
/*
* 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 { deleteDocument } from './documents';
import { Logger } from '@kbn/logging';
import type { ElasticsearchClient } from '@kbn/core-elasticsearch-server';
describe('deleteDocument', () => {
let mockClient: jest.Mocked<ElasticsearchClient>;
let mockLogger: jest.Mocked<Logger>;
beforeEach(() => {
mockClient = {
delete: jest.fn().mockResolvedValue({}),
} as unknown as jest.Mocked<ElasticsearchClient>;
mockLogger = {
info: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
trace: jest.fn(),
fatal: jest.fn(),
log: jest.fn(),
} as unknown as jest.Mocked<Logger>;
});
it('should delete a document and return true', async () => {
const index = 'test-index';
const id = 'test-id';
const result = await deleteDocument(mockClient, mockLogger, index, id);
expect(mockClient.delete).toHaveBeenCalledWith({
index,
id,
});
expect(result).toBe(true);
});
it('should log an error and throw when delete fails', async () => {
const index = 'test-index';
const id = 'test-id';
const error = new Error('Delete failed');
mockClient.delete.mockRejectedValue(error);
await expect(deleteDocument(mockClient, mockLogger, index, id)).rejects.toThrow(
'Delete failed'
);
});
});

View file

@ -0,0 +1,22 @@
/*
* 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 type { ElasticsearchClient } from '@kbn/core-elasticsearch-server';
import type { Logger } from '@kbn/logging';
export async function deleteDocument(
client: ElasticsearchClient,
logger: Logger,
index: string,
id: string
): Promise<boolean> {
await client.delete({
index,
id,
});
return true;
}

View file

@ -0,0 +1,51 @@
/*
* 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 { schema } from '@kbn/config-schema';
import { i18n } from '@kbn/i18n';
import type { IRouter } from '@kbn/core/server';
import type { Logger } from '@kbn/logging';
import { INDEX_DOCUMENT_ROUTE } from '../../common/routes';
import { deleteDocument } from '../lib/documents';
export function registerDocumentRoutes(router: IRouter, logger: Logger) {
router.delete(
{
path: INDEX_DOCUMENT_ROUTE,
validate: {
params: schema.object({
indexName: schema.string(),
id: schema.string(),
}),
},
options: {
access: 'internal',
},
},
async (context, request, response) => {
const core = await context.core;
const client = core.elasticsearch.client.asCurrentUser;
const { indexName, id } = request.params;
try {
await deleteDocument(client, logger, indexName, id);
return response.ok();
} catch (e) {
return response.customError({
statusCode: e?.meta && e.meta?.statusCode ? e.meta?.statusCode : 500,
body: {
message: i18n.translate('xpack.searchIndices.server.deleteDocument.errorMessage', {
defaultMessage: 'Failed to delete document',
}),
},
});
}
}
);
}

View file

@ -11,9 +11,11 @@ import type { Logger } from '@kbn/logging';
import { registerSearchApiKeysRoutes } from '@kbn/search-api-keys-server';
import { registerIndicesRoutes } from './indices';
import { registerStatusRoutes } from './status';
import { registerDocumentRoutes } from './documents';
export function defineRoutes(router: IRouter, logger: Logger) {
registerIndicesRoutes(router, logger);
registerStatusRoutes(router, logger);
registerSearchApiKeysRoutes(router, logger);
registerDocumentRoutes(router, logger);
}

View file

@ -180,5 +180,18 @@ export function SvlSearchIndexDetailPageProvider({ getService }: FtrProviderCont
apiKey
);
},
async clickFirstDocumentDeleteAction() {
await testSubjects.existOrFail('documentMetadataButton');
await testSubjects.click('documentMetadataButton');
await testSubjects.existOrFail('deleteDocumentButton');
await testSubjects.click('deleteDocumentButton');
},
async expectDeleteDocumentActionNotVisible() {
await testSubjects.existOrFail('documentMetadataButton');
await testSubjects.click('documentMetadataButton');
await testSubjects.missingOrFail('deleteDocumentButton');
},
};
}

View file

@ -97,7 +97,6 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) {
});
describe('With data', () => {
before(async () => {
await svlSearchNavigation.navigateToIndexDetailPage(indexName);
await es.index({
index: indexName,
body: {
@ -126,6 +125,11 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) {
await pageObjects.svlSearchIndexDetailPage.expectUrlShouldChangeTo('settings');
await pageObjects.svlSearchIndexDetailPage.expectSettingsComponentIsVisible();
});
it('should be able to delete document', async () => {
await pageObjects.svlSearchIndexDetailPage.withDataChangeTabs('dataTab');
await pageObjects.svlSearchIndexDetailPage.clickFirstDocumentDeleteAction();
await pageObjects.svlSearchIndexDetailPage.expectAddDocumentCodeExamples();
});
});
describe('page loading error', () => {