How to delete all documents from index in an elasticsearch using RestHighLevelClient
Asked Answered
G

2

5

I have tried below code it works fine but it uses TransportClient to delete all documents.

DeleteByQueryRequestBuilder deleteByQueryRequestBuilder = DeleteByQueryAction.INSTANCE.newRequestBuilder(transportClient)
                 .filter(QueryBuilders.matchAllQuery())
                 .source(indexName);
         BulkByScrollResponse response = deleteByQueryRequestBuilder
                .filter(QueryBuilders.matchAllQuery()).get()

I am using elasticsearch 6.1.4. What is the way to delete all documents from index using RestHighLevelClient.

Gat answered 29/10, 2018 at 7:44 Comment(1)
It will be supported as of ES 6.5.0: github.com/elastic/elasticsearch/pull/32782Martensite
P
8

I am using elasticsearch 6.5.4. In this snippet I use the client RestHighLevelClient.

DeleteByQueryRequest request = new DeleteByQueryRequest(indexName);
request.setQuery(QueryBuilders.matchAllQuery());
BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);

The class RestHighLevelClient have the method deleteByQuery that need a request. In this request you can define the filters you need it.

You can find more information here.

Priscella answered 9/1, 2019 at 8:41 Comment(1)
Can you add some explanation to your answer ?Hetzel
T
0

In case anyone wondering how to delete list of documents by id, following approach can be used with RestHighLevelClient. I've come across this issue and couldn't find any helpful resources, therefore here I am posting my answer which doesn't directly answer OP's question.

Delete API with BulkRequest

public void deleteIndexes() {

    List<String> websitePageList = new ArrayList<>();
    websitePageList.add("3123123123"); //Test Data
    websitePageList.add("8756785678");
    websitePageList.add("9673563456");

    if (websitePageList != null && !websitePageList.isEmpty()) {
        BulkRequest request = new BulkRequest();
        websitePageList.forEach(pageId -> request.add(new DeleteRequest("content", pageId))); //Where content is index & pageId is Document Id
        ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() {
            @Override
            public void onResponse(BulkResponse bulkItemResponses) {
                long deleted = bulkItemResponses.getItems().length;
                LOG.info("Deleted documents : " + deleted);
            }

            @Override
            public void onFailure(Exception e) {
                LOG.error("Index has not been correctly removed");
            }
        };

        client.bulkAsync(request, RequestOptions.DEFAULT, listener);
    }
}
Tyndall answered 17/1, 2020 at 9:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.