In this tutorial, we will understand how to update documents in Elasticsearch.
This is an important topic because updating data behaves slightly differently compared to traditional relational databases.
Step 1: First, Read the Existing Document
Before updating anything, it is always a good idea to read the document first.
Let’s assume we already have a document with ID 3 in the books index.
Get the document
GET /books/_doc/3
This returns something like:
{
"_source": {
"title": "Some Book",
"author": "Some Author",
"year": 1925
}
}
Now let’s say we realize that the year is incorrect and it should be 1926, not 1925.
Step 2: Updating a Document Using PUT
To update a document, we use the same endpoint that we used to create it:
PUT /books/_doc/3
And provide the updated object in the request body:
{
"title": "Some Book",
"author": "Some Author",
"year": 1926
}
Once you send this request, Elasticsearch updates the document.
Verify the Update
Now, if you run:
GET /books/_doc/3
You will see:
{
"_source": {
"title": "Some Book",
"author": "Some Author",
"year": 1926
}
}
So the update was successful.
Important Concept: PUT and POST Both Work
In Elasticsearch:
PUTandPOSTboth can be used to update documents.- Both behave in an upsert manner.
What does “Upsert” mean?
Upsert means:
- Update if the document exists
- Insert if the document does not exist
Example: Updating a Non-Existing Document
If you send this request:
PUT /books/_doc/13
With some data:
{
"title": "New Book",
"author": "New Author",
"year": 2024
}
And document 13 does not exist, Elasticsearch will:
- Create a brand new document
- Assign it ID
13
So this is insert behavior, even though you used PUT.
Important Warning: Full Replacement Behavior
This is a very important concept. When you use:
PUT /books/_doc/{id}
You are replacing the entire document.
Example of a Mistake
Suppose your document originally looks like this:
{
"title": "Some Book",
"author": "Some Author",
"year": 1926
}
Now you send this request:
PUT /books/_doc/3
{
"year": 1925
}
What happens?
The entire document is replaced with:
{
"year": 1925
}
All other fields (title, author) are lost.
This is very important to understand.
Why This Happens
Elasticsearch treats this as:
“Replace the entire document with the new one you provided.”
It does not merge fields automatically when using PUT.
How to Update Only One Field (Patch Behavior)
If you want to update only a specific field, such as year, without touching the rest of the document, you must use a different API — the Update API.
This is commonly referred to as a patch operation.
We’ll discuss in the next tutorial.
