如何在 Elasticsearch 中创建嵌套对象并将其添加到嵌套字段中?

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

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

考虑:

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"
    }
  ]
}

当我 运行 像这样的无痛脚本时:

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

它不起作用。我试过了,但找不到任何相关文件或其他人发起的讨论。

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

您可以像 ['first': 'Foo', 'last': 'Bar', 'sthElse': 100] 一样创建地图然后添加它。

所以:

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

请注意,painless 中的地图可以是混合类型。

POST my_index/_doc/1/_update
{
   "script": {
      "lang": "painless",
      "inline": "ctx._source.user.add(params.object)",
      "params": {
         "object": {
            "first" : "Foo",
            "last" : "Bar"
         }
      }
   }
}