Elasticsearch update by query method to add field into existing documents of Elasticsearch
In this tutorial we are going to add fields into existing Elasticsearch index by using the painless script of Elasticsearch. The painless script of Elasticsearch is very powerful and it can be used to process the data stored in Elasticsearch index.
If you use the painless script then you can achieve many functionality very fast in Elasticsearch. For example you can add news columns into Elasticsearch index, also give values to it based on by calculating the values from other columns.
For example you can easily add a new field in Elasticsearch by summing up two or more integer fields. This is very simple example but people are writing Elasticsearch painless script to do a lot of work.
In this example we are going to add a location field in existing Elasticsearch index with lat and lon value in it. We will create a location field in Elasticsearch with following structure:
"location" : {
"lat": "2.01",
"lon": "1.05"
}
This type of field you can easily add with the Elasticsearch painless script.
Elasticsearch comes with the painless script which can be used to add new fields
into existing without complete updating of data. You can just add the fields you
want into the index of Elasticsearch.
PUT store { "settings": { "index": { "number_of_shards": 1, "number_of_replicas": 1 } }, "mappings": { "mobile": { "properties": { "phone_name": { "type": "text" } } } } }
Then add data with following code:
POST /store/mobile/1 { "phone_name":"iPhone" } POST /store/mobile/2 { "phone_name":"Samsung Galaxy S 10" }
Now if you want to add location of the store then you can use following:
POST /store/_update_by_query?pretty { "query" : { "match_all":{} }, "script" : { "inline" : "ctx._source.location = params.value", "params" : { "value" : { "lat": "2.01", "lon": "1.05" } } } }
Check more tutorials at Elasticsearch Tutorial page.