Can ES support to add a new item into the nested objects of existing document?

Hi all,

I have a ES document like:

{
  "title": "Nest eggs",
  "comments": [ 
    {
      "name":    "John Smith",
      "comment": "Great article",
    },
    {
      "name":    "Alice White",
      "comment": "More like this please",
    }
  ]
}

and now I'd like to add a new "comments" in this document and finially the document will be:

{
  "title": "Nest eggs",
  "comments": [ 
    {
      "name":    "John Smith",
      "comment": "Great article",
    },
    {
      "name":    "Alice White",
      "comment": "More like this please",
    },
	{
      "name":    "New guy",
      "comment": "something here",
    }
  ]
}

Does someone know how to do it?

Thanks a lot

1 Like

Any one knows it?

You can update the comments array, but you would have to send an array with the two comments that already exist plus the new comment.

https://www.elastic.co/guide/en/elasticsearch/guide/current/partial-updates.html

Thanks, Dan. It should have a more smart way :smile:

I know probably this is not the solution you are looking for. But it might help you!

You can try parent child relationship instead of nested object: https://www.elastic.co/guide/en/elasticsearch/guide/current/parent-child.html

It will allow you to add/update/delete child in each parent. But you have to put them all in the same shard!

Cheers, Ramy

Thanks, Ramy! It looks quite nice for adding/updating/delete.
But seems it hard to got parent and child docment in same query.

Still, appreciate your suggestion.

Cheers, Gin

Hi Gin,
What do you mean with it?

You are able to query parents by their children and on the opposite way as well!

You can use the inner hits functionality to get the child documents in the same query when you use the has_child query.

The parent/child approach will allow you to index a child document individually which is more efficient if you have large documents and a requirement to update frequently. However, parent/child queries are 5-10 times slower than nested queries. So it is worth keeping that in mind when deciding what is the best approach for your use case.

Ramy and Dan,

Thanks for your suggestion and those help a lot :smile:

BR. Gin