5

I need to update several documents in my Elasticsearch index and I tried the following using the the _update_by_query plugin.

What I need to do is to add a new field to several existing documents matching a certain condition. The new field is a nested JSON. So after adding it document source should look like

_source: {
    ...existing fields,
    "new_field" : {
        "attrName1" : "value",
        "attrName2" : "value",
    }
}  

I tried using the _update_by_query API to get this done. But so far I only could add String fields and arrays with it. When trying to add a JSON with the following query it gives me an error.

Query

curl -XPOST "http://xxx.xxx.xxx.xxx:pppp/my_index_name/_update_by_query" -d'
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "team.keyword": "search_phrase"
          }
        }
      ]
    }
  },
  "script" : {
    "inline":"ctx._source.field_name = {\"a\":\"b\"}"
  }
}'

Error

{
  "error": {
    "root_cause": [
      {
        "type": "script_exception",
        "reason": "compile error",
        "script_stack": [
          "ctx._source.field_name = {\"a\":\"b\"}",
          "                         ^---- HERE"
        ],
        "script": "ctx._source.field_name = {\"a\":\"b\"}",
        "lang": "painless"
      }
    ],
    "type": "script_exception",
    "reason": "compile error",
    "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "invalid sequence of tokens near ['{'].",
      "caused_by": {
        "type": "no_viable_alt_exception",
        "reason": null
      }
    },
    "script_stack": [
      "ctx._source.field_name = {\"a\":\"b\"}",
      "                         ^---- HERE"
    ],
    "script": "ctx._source.field_name = {\"a\":\"b\"}",
    "lang": "painless"
  },
  "status": 500
}

So far I could only add Strings as a new field. What is the correct way to achieve this?

1 Answer 1

7

Instead of direct assignment, use params to achieve the same.

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "team.keyword": "search_phrase"
          }
        }
      ]
    }
  },
  "script": {
    "inline": "ctx._source.field_name = params.new_field",
    "params": {
      "new_field": {
        "a": "b"
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.