Update by query gives java error

Hello,

I am trying to update several documents based on a search query. My use case is to search for documents where two fields match certain values and then add a new field with a certain value. So let's say I want to search all employees with first name "John" and last name "Smith" and add a new field "job" to their profiles with the value "Engineer" in it.
To do this, I am using the update by query API with the "script" option. My code looks like follows:

curl -XPOST -s 'http://localhost:9200/test_index/_update_by_query?conflicts=proceed' -d'
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"bool": {
"must": [
{
"match": { "first_name" : "John" }
},
{
"match": { "last_name" : "Smith" }
}
]
}
}
}
},
"script" : "ctx._source.job = "Engineer""
}'

Whenever I run this on ubuntu terminal I get the following error:

{"error":{"root_cause":[{"type":"class_cast_exception","reason":"java.lang.String cannot be cast to java.util.Map"}],"type":"class_cast_exception","reason":"java.lang.String cannot be cast to java.util.Map"},"status":500}

However, sending the same query (without the "script" field) using the count API works fine and gives the correct number of documents.

My questions:

  • Where is exactly the error in the code I'm using? Unfortunately the error message does not specify in which line the problem is
  • Is it possible to use "doc" instead of "script" in the update by query API exactly the same way this is used in Update API?

Elasticsearch version is 2.3.4

I have the same issue with elasticsearch 2.3.4

curl -XPOST 'localhost:9200/watch/_update_by_query' -d '{
    "query":{ "type" : {"value" : "doc"} },
    "script" : "if (ctx._source[\"topics\"] != null) {ctx._source.remove(\"topics\")"}
}'

and result:

{"error":{"root_cause":[{"type":"class_cast_exception","reason":"java.lang.String cannot be cast to java.util.Map"}],"type":"class_cast_exception","reason":"java.lang.String cannot be cast to java.util.Map"},"status":500}

topics field is a nested object (if it can help).

I'm facing same issue while appeding data in array type using script,

using update_by_query:

POST /srk/demo_array/_update_by_query
{
"script" : "ctx._source.array += arr",
"params" : {
"arr" : ["a", "b"]
}
}

java error:

{
"error": {
"root_cause": [
{
"type": "class_cast_exception",
"reason": "java.lang.String cannot be cast to java.util.Map"
}
],
"type": "class_cast_exception",
"reason": "java.lang.String cannot be cast to java.util.Map"
},
"status": 500
}

I had this same problem but figured it out. You need to add "inline" to make it work:

POST /logstash-*/_update_by_query
{
  "script": {
    "inline": "ctx._source.remove(\"ENTERFIELD\")"
  },
  "query": {
    "bool": {
      "must": [
        {
          "exists": {
            "field": "ENTERFIELD"
          }
        }
      ]
    }
  }
}