Skip to content

Commit

Permalink
[Onboarding] delete document action (elastic#195263)
Browse files Browse the repository at this point in the history
## Summary

Ability to delete documents.

I had to reduce the capability of the search_documents hook so the
delete document hook can optimistically update the change. These
capabilities were not in use.


![image](https://github.com/user-attachments/assets/85df2146-e6d5-4812-b825-bbbca6049215)

### 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—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—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)
  • Loading branch information
joemcelroy authored Oct 8, 2024
1 parent b5bc989 commit faa74d2
Show file tree
Hide file tree
Showing 16 changed files with 266 additions and 23 deletions.
12 changes: 10 additions & 2 deletions packages/kbn-search-index-documents/components/result/result.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export interface ResultProps {
showScore?: boolean;
compactCard?: boolean;
onDocumentClick?: () => void;
onDocumentDelete?: () => void;
}

export const Result: React.FC<ResultProps> = ({
Expand All @@ -45,6 +46,7 @@ export const Result: React.FC<ResultProps> = ({
compactCard = true,
showScore = false,
onDocumentClick,
onDocumentDelete,
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const tooltipText =
Expand Down Expand Up @@ -87,7 +89,10 @@ export const Result: React.FC<ResultProps> = ({
values: { id: metaData.id },
})
}
metaData={metaData}
metaData={{
...metaData,
onDocumentDelete,
}}
/>
)}
{!compactCard && (
Expand All @@ -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}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/search_indices/common/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}';
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -21,14 +22,23 @@ export interface DocumentListProps {
}

export const DocumentList = ({ indexName, docs, mappingProperties }: DocumentListProps) => {
const { mutate } = useDeleteDocument(indexName);

return (
<>
<RecentDocsActionMessage indexName={indexName} />
<EuiSpacer size="m" />
{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>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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');
Expand Down
4 changes: 4 additions & 0 deletions x-pack/plugins/search_indices/public/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Original file line number Diff line number Diff line change
@@ -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 };
};
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/search_indices/public/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
56 changes: 56 additions & 0 deletions x-pack/plugins/search_indices/server/lib/documents.test.ts
Original file line number Diff line number Diff line change
@@ -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'
);
});
});
22 changes: 22 additions & 0 deletions x-pack/plugins/search_indices/server/lib/documents.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Loading

0 comments on commit faa74d2

Please sign in to comment.