Ways to delete documents from elasticsearch

Prashant Khunt
2 min readJun 29, 2019

Elasticsearch is a widely used indexing and searching tool. To search documents from the elasticsearch, we need to index those documents first, but sometimes while doing indexing, we may have done mistakes or after some time some of the documents are not useful for us in those cases we need to delete documents from elasticsearch.

Once the documents have been deleted searching will not be performed on those documents.

Let check documents which are available in my index: http://127.0.0.1:9200/document-index/_search

Here index name is document-index which have two documents as below:

Let’s learn different ways to delete documents from elasticsearch with different examples:

Elastic search provides ways to delete a single document as well as delete documents in bulk using _delete_by_query query.

1. Delete single document using document id

To delete a single document using document id, we should have an id of the particular document. Here is an example of deleting document using document id. Make sure that here request a type is a DELETE.

In the above REST API, document-index is the name of the elasticsearch index. _doc is document type and 1 is a document id.

2. Delete all documents from the index

We can delete all the documents from the index using _delete_by_query. when we pass “match_all”:{} then it will match all the documents so _delete_by_query will delete all the documents from the index.

3. Delete documents based on the query or specific criteria

Elasticsearch provides _delete_by_query REST API to delete multiple documents based on a specified query, Here we need to pass JSON as the request body with POST method, It will delete those document which fulfills by specified query.

2.1 Delete using range query, It will delete all the document whose id is great than or equals to 1.

2.2 Delete using match criteria, Here it will delete all the document whose firstName is Prashant.

Concussion

In this article, We learned about different approaches to delete the document’s indexes, another important point is that elasticsearch is using Lucene index and as per Lucene characteristic t will not directly delete and document from index but only mark as delete and after sometimes rearrange the documents at that time it will remove from the index.

--

--

Prashant Khunt

I have skills for Hadoop, Spark, Elastic and Solr development. Founder of www.javadeveloperzone.com