0
0
ElasticsearchHow-ToBeginner · 4 min read

How to Update Document in Elasticsearch: Syntax and Examples

To update a document in Elasticsearch, use the _update API with the document's _id and specify the changes inside a doc object. This allows partial updates without replacing the entire document.
📐

Syntax

The update operation uses the POST method on the endpoint /{index}/_update/{id}. Inside the request body, you provide a doc object with the fields you want to change.

  • {index}: The name of your Elasticsearch index.
  • {id}: The unique ID of the document to update.
  • doc: The partial document with fields to update.
json
POST /my_index/_update/1
{
  "doc": {
    "field": "new value"
  }
}
💻

Example

This example updates the document with ID 1 in the index my_index, changing the field status to "completed".

json
POST /my_index/_update/1
{
  "doc": {
    "status": "completed"
  }
}
Output
{ "_index": "my_index", "_id": "1", "_version": 2, "result": "updated", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 5, "_primary_term": 1 }
⚠️

Common Pitfalls

Common mistakes when updating documents include:

  • Using PUT instead of POST on the _update endpoint.
  • Trying to update a document that does not exist without using doc_as_upsert.
  • Sending the full document instead of partial fields inside doc, which replaces the whole document.

To avoid errors, always use doc for partial updates and check if the document exists or use doc_as_upsert": true to create it if missing.

json
POST /my_index/_update/2
{
  "doc": {
    "status": "pending"
  },
  "doc_as_upsert": true
}
Output
{ "_index": "my_index", "_id": "2", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 6, "_primary_term": 1 }
📊

Quick Reference

OperationDescriptionExample
Update documentPartially update fields in a documentPOST /index/_update/id { "doc": { "field": "value" } }
Upsert documentUpdate or create if missingPOST /index/_update/id { "doc": { "field": "value" }, "doc_as_upsert": true }
Replace documentReplace whole document (not recommended for update)PUT /index/_doc/id { "field": "value" }

Key Takeaways

Use the _update API with POST and the doc object to update fields partially.
Include doc_as_upsert: true to create the document if it does not exist.
Avoid replacing the entire document unless you intend to overwrite it.
Check the update response for result status to confirm success.
Use the document ID and index name correctly in the update request URL.