0
0
Elasticsearchquery~5 mins

Updating documents in Elasticsearch

Choose your learning style9 modes available
Introduction
Updating documents lets you change information already saved in Elasticsearch without deleting and adding it again.
You want to fix a typo in a saved record.
You need to add new details to an existing document.
You want to increase a count or score stored in a document.
You want to change the status of an order or task.
You want to update a timestamp to show the last change.
Syntax
Elasticsearch
POST /index_name/_update/document_id
{
  "doc": {
    "field_name": "new_value"
  }
}
Use POST method with _update endpoint to change a document.
Inside the JSON body, use "doc" to specify only the fields you want to update.
Examples
This updates the price field of the document with ID 1 in the products index.
Elasticsearch
POST /products/_update/1
{
  "doc": {
    "price": 19.99
  }
}
This sets the last_login field to a new date for user with ID 42.
Elasticsearch
POST /users/_update/42
{
  "doc": {
    "last_login": "2024-06-01T12:00:00"
  }
}
This changes the status of order 100 to shipped.
Elasticsearch
POST /orders/_update/100
{
  "doc": {
    "status": "shipped"
  }
}
Sample Program
This updates the document with ID 123 in the library index, changing the title and availability.
Elasticsearch
POST /library/_update/123
{
  "doc": {
    "title": "Learn Elasticsearch",
    "available": true
  }
}
OutputSuccess
Important Notes
If the document does not exist, Elasticsearch can create it if you add "doc_as_upsert": true.
Only the fields inside "doc" are changed; other fields stay the same.
You can also use scripts to update fields based on their current values.
Summary
Use the _update API to change parts of a saved document.
Send only the fields you want to change inside the "doc" object.
Elasticsearch updates the document without replacing it fully.