4

working on ES 5.x version, and need to update multiple fields update using script.Also share , have any better solution .

POST ../100/_update
    {
    "script" : {
        "inline": "ctx._source.student.hobbies.add(params.tag)",
        "lang": "painless",
        "params" : {
            "tag" : "cricket"
        }
    }
}

also the same student i need to update phone no. now i am calling 2 api for update hobbies and phone number. looking for better solution to update both in single query

Learn Hadoop
  • 2,760
  • 8
  • 28
  • 60
  • Just add a semicolon after the first statement and add a second statement ;-) – Val Feb 23 '18 at 12:21
  • `{ "script" : { "inline": "ctx._source.student.hobbies.add(params.tag)", "lang": "painless", "params" : { "tag" : "cricket" } } } ------ { "script" : { "inline": "ctx._source.student.phone.add(params.tag)", "lang": "painless", "params" : { "tag" : "122-33-4567" } } } ` - where to add semicolon – Learn Hadoop Feb 23 '18 at 12:31
  • `{ "script" : { "inline": "ctx._source.student.hobbies.add(params.tag)", "lang": "painless", "params" : { "tag" : "cricket" } } }; { "script" : { "inline": "ctx._source.student.phone.add(params.tag)", "lang": "painless", "params" : { "tag" : "122-33-4567" } } }` - i tried this . The first script hobbies got updated. but not phone number. – Learn Hadoop Feb 23 '18 at 12:34
  • See my answer below – Val Feb 23 '18 at 12:36

1 Answers1

17

Just add a semicolon between both statements, like this:

{
  "script": {
    "inline": "ctx._source.student.hobbies.add(params.hobby); ctx._source.student.phone.add(params.phone)",
    "lang": "painless",
    "params": {
      "hobby": "cricket",
      "phone" : "122-33-4567"
    }
  }
}

If you have more than one value to add to an array, you can do it like this

{
  "script": {
    "inline": "ctx._source.student.hobbies.addAll(params.hobbies); ctx._source.student.phone.add(params.phone)",
    "lang": "painless",
    "params": {
      "hobbies": ["football", "cricket"],
      "phone" : "122-33-4567"
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • But i couldn't add more hobbies. here hobbies field type is array.. if add "cricket,football" then it will treat as single value and stored as "cricket,football", but i am excepting "cricket" , "football" – Learn Hadoop Feb 23 '18 at 12:43