Search code examples
elasticsearchelasticsearch-painless

elastic search - update specific nested object


I have hotel documents that each have rooms of nested type.

{
id: hotel_id,
   rooms: [
     {
        id: room_id_1,
        name: "room 1 name"
      },
      {
        id: room_id_2,
        name: "room 2 name"
      },
      ....
  ]
}

And I want to update only single field from a specific room. I am trying with the Update api, update the room with id 2 from the hotel document with id 1:

POST hotels/_update/1
{
  "script" : {
    "source" : "if(ctx._source.rooms.id == 2) { ctx._source.rooms.name = params.new_name }",
    "lang" : "painless",
    "params" : {
        "new_name" : "new room name"
    }  
  } 
}

I get this error "Illegal list shortcut value [id]" from ES.

Thanks!


Solution

  • You need to loop through rooms like this:

    POST hotels/_update/1
    {
      "script" : {
        "source" : "for (int i=0; i < ctx._source.rooms.length; i++) {if(ctx._source.rooms[i].id == 2) { ctx._source.rooms[i].name = params.new_name; break } }",
        "lang" : "painless",
        "params" : {
            "new_name" : "new room name"
        }  
      } 
    }