Elasticsearch Elasticsearch Update Document Field

By Opster Team

Updated: Aug 24, 2023

| 2 min read

Quick Links

Introduction 

Elasticsearch allows for the updating of document fields. This feature is crucial for maintaining the accuracy and relevance of the data stored in Elasticsearch indices. This article will delve into the intricacies of updating document fields in Elasticsearch, providing examples and step-by-step instructions to guide you through the process.

Updating a document field

To update a document field in Elasticsearch, you can use the Update API. This API allows you to update a document based on its ID. The following is an example of how to use the Update API:

POST /index_name/_update/document_id
{
  "doc": {
    "field_name": "new_value"
  }
}

In this example, `index_name` is the name of the index, `document_id` is the ID of the document you want to update, `field_name` is the name of the field you want to update, and `new_value` is the new value you want to set for the field.

Partial document update

Elasticsearch also allows for partial document updates. This means you can update specific fields within a document without affecting the rest of the document. Here’s an example of how to perform a partial document update:

POST /index_name/_update/document_id
{
  "doc": {
    "field_name1": "new_value1",
    "field_name2": "new_value2"
  }
}

In this example, `field_name1` and `field_name2` are the names of the fields you want to update, and `new_value1` and `new_value2` are the new values you want to set for these fields. No other fields of the document will be updated or removed.

Upserts

In some cases, you might want to update a document field, but the document does not exist yet. In such cases, you can use the `upsert` option. The `upsert` option allows you to specify a new document that will be added if the document does not exist. Here’s an example of how to use the `upsert` option:

POST /index_name/_update/document_id
{
  "doc": {
    "field_name": "new_value"
  },
  "upsert": {
    "field_name": "default_value"
  }
}

In this example, if the document with the ID `document_id` does not exist, a new document will be created with the field `field_name` set to `default_value`.

Scripted updates

Elasticsearch also supports scripted updates. This means you can use a script to update a document field. This is useful when the new value of the field depends on the current value of the field. Here’s an example of how to perform a scripted update:

POST /index_name/_update/document_id
{
  "script": {
    "source": "ctx._source.field_name += params.count",
    "params": {
      "count": 1
    }
  }
}

In this example, the script increases the current value of the field `field_name` by 1.

How helpful was this guide?

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?