Updating Elasticsearch field value with a Query

Views: 50   

This tutorial shows you how to update an Elasticsearch field value based on a Query. Let say following is your document in Elasticsearch

{
  "id" : 123,
  "name" : "foo",
  "age" : 45
}

and you want to set the use age to 50 where name is foo i.e the following sql query

update user set age = 50 where name = 'foo'

Following is the CURL you need to run to do the same in Elasticsearch

curl -XPOST "http://localhost:9200/your_index_name/_update_by_query" -H 'Content-Type: application/json' -d'
{
    "script" : {
      "source": "ctx._source.age=50;",
      "lang": "painless"  
    },
    "query": {
        "term" : {
            "name.keyword": "foo"
        }
    }
}'

If you are using the Kibana's DevTools then you can run the following statement

POST your_index_name/_update_by_query
{
    "script" : {
      "source": "ctx._source.age=50;",
      "lang": "painless"  
    },
    "query": {
        "term" : {
            "name.keyword": "foo"
        }
    }
}

On successful run you will get a response like following

{
  "took": 4,
  "timed_out": false,
  "total": 1,
  "updated": 1,
  "deleted": 0,
  "batches": 1,
  "version_conflicts": 0,
  "noops": 0,
  "retries": {
    "bulk": 0,
    "search": 0
  },
  "throttled_millis": 0,
  "requests_per_second": -1,
  "throttled_until_millis": 0,
  "failures": []
}
On By