我有这样的ES文档。

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

现在我想在此文档中添加一个新的“注释”,最后该文档将是
{
   "title": "Nest eggs",
   "comments": [
{
  "name":    "John Smith",
  "comment": "Great article",
},
{
  "name":    "Alice White",
  "comment": "More like this please",
},
{
  "name":    "New guy",
  "comment": "something here",
}
]
}

我不想在每次追加过程中都提供现有的“comments”对象,因此什么是每次向此嵌套字段添加新对象的最佳方法?

我的解决方案:
 POST test_v2/_update/Z_nM_2wBjkGOA-r6ArOb
 {
  "script": {
  "lang": "painless",
  "inline": "ctx._source.nested_field.add(params.object)",
  "params": {
     "object": {
        "model" : "tata nano",
        "value" : "2"
     }
  }
 }
}

最佳答案

检查脚本本身是否为空字段。如果字段不存在,则首先创建

 POST test3/_update/30RaAG0BY3127H1HaOEv
{
  "script": {
    "lang": "painless",
    "inline": "if(!ctx._source.containsKey('comments')){ctx._source['comments']=[]}ctx._source.comments.add(params.object)",
    "params": {
      "object": {
        "model": "tata nano",
        "value": "2"
      }
    }
  }
}

关于elasticsearch - ES是否支持将新项目添加到现有文档的嵌套字段中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57799098/

10-13 07:46
查看更多