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

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


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.


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);    }}