我有这样的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" } } } }