How to Delete Document in Elasticsearch: Syntax and Examples
To delete a document in Elasticsearch, use the
DELETE HTTP method with the document's index and id. The syntax is DELETE /index/_doc/document_id, which removes the specified document from the index.Syntax
The basic syntax to delete a document in Elasticsearch uses the DELETE HTTP method targeting the document's index and id. Here is the pattern:
- DELETE: HTTP method to remove data.
/index/_doc/document_id: URL path whereindexis the name of your index,_docis the document type (default in modern Elasticsearch), anddocument_idis the unique ID of the document to delete.
http
DELETE /my_index/_doc/1Example
This example shows how to delete a document with ID 1 from the index my_index using curl command line tool. It demonstrates the request and the expected JSON response.
bash
curl -X DELETE "http://localhost:9200/my_index/_doc/1" { "_index": "my_index", "_type": "_doc", "_id": "1", "_version": 2, "result": "deleted", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 5, "_primary_term": 1 }
Output
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"_version": 2,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 5,
"_primary_term": 1
}
Common Pitfalls
Common mistakes when deleting documents in Elasticsearch include:
- Using the wrong
indexordocument_id, which results in a404 Not Founderror. - Not specifying the correct document type; modern Elasticsearch uses
_docas the default type. - Assuming the document is deleted immediately; Elasticsearch deletes are eventually consistent and may take a moment to reflect.
- Not handling the response properly to confirm deletion succeeded.
bash
curl -X DELETE "http://localhost:9200/wrong_index/_doc/1" # Correct way: curl -X DELETE "http://localhost:9200/my_index/_doc/1"
Quick Reference
| Action | Syntax Example | Description |
|---|---|---|
| Delete document | DELETE /my_index/_doc/1 | Deletes document with ID 1 from my_index |
| Check if deleted | GET /my_index/_doc/1 | Returns 404 if document is deleted |
| Delete with curl | curl -X DELETE "http://localhost:9200/my_index/_doc/1" | Command line delete request |
Key Takeaways
Use the DELETE HTTP method with the index and document ID to remove a document.
Always specify the correct index and document ID to avoid errors.
Modern Elasticsearch uses _doc as the document type in the URL.
Check the response to confirm the document was deleted successfully.
Deleted documents may not disappear instantly due to Elasticsearch's eventual consistency.