A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

elasticsearch script update based on existing doc value

From the elastic.co documentation I came to know that it is easy to search documents using the script on _search API, e.g Here I can use the existing doc value while making script condition.

GET /_search
{
    "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : {
                        "source": "doc['num1'].value > 1",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}

To update documents using the Update API we can do like this,

POST test/_doc/1/_update
{
    "script" : "ctx._source.new_field = 'value_of_new_field'"
}

What I expect Is that possible on ES query? (I've tried but not succeeds)

POST test/_doc/1/_update
{
    "script" : "ctx._source.image_count = doc['images'].length;"
}

Why I need? Actually I have 2 fields on my document. One called images with multiple value e.g ["1.jpg","2.jpg","3.png"] and another called image_count with 3 based on the length of images field. Here I can get the length of images field while using the _search API.

  1. But I just want to know is there any facility on ES that I can update the every document by dynamically calculating the images length and set the value of image_count field?

OR

  1. Is there any bulk update API to do that task easily without specifying each and every document id on _update API?

Upvotes: 0

Views: 2850

Answers (1)

sramalingam24
sramalingam24

Reputation: 1337

What you are looking for is _update_by_query API. Be careful if you have a huge number of docs to update, you can use the sliced scroll approach. This works in latest, might have to tweak it depending on your version

POST /images_index/_update_by_query
{
    "script":{
        "source": "ctx._source['images_count'] = ctx._source['images'].length"
    }
}

See here for doc: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html

Upvotes: 1

Related Questions