Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and add nested object into nested field in Elasticsearch?

https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html

Consider:

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "user": {
          "type": "nested" 
        }
      }
    }
  }
}

PUT my_index/_doc/1
{
  "group" : "fans",
  "user" : [
    {
      "first" : "John",
      "last" :  "Smith"
    },
    {
      "first" : "Alice",
      "last" :  "White"
    }
  ]
}

When I run a painless script like:

ctx._source.user.add({
    "first" : "Foo",
    "last" : "Bar"
})

It is not working. I tried but cannot find any related documents or discussion started by other.

like image 680
tom10271 Avatar asked Mar 20 '18 06:03

tom10271


2 Answers

https://www.elastic.co/guide/en/elasticsearch/reference/5.4/modules-scripting-painless-syntax.html#painless-maps

You can create a map like ['first': 'Foo', 'last': 'Bar', 'sthElse': 100] then add it.

So:

ctx._source.user.add([
    "first" : "Foo",
    "last" : "Bar"
])

Please note that map in painless can be mixed type.

like image 65
tom10271 Avatar answered Sep 28 '22 06:09

tom10271


POST my_index/_doc/1/_update
{
   "script": {
      "lang": "painless",
      "inline": "ctx._source.user.add(params.object)",
      "params": {
         "object": {
            "first" : "Foo",
            "last" : "Bar"
         }
      }
   }
}
like image 44
Bharat Avatar answered Sep 28 '22 07:09

Bharat