从数组弹性搜索中删除对象

Raj*_*arg 11 mvel node.js elasticsearch

我需要从满足条件的数组中删除对象,我能够根据条件更新数组的对象,如下所示:

PUT twitter/twit/1
{"list": 
     [
        {
            "tweet_id": "1",
            "a": "b"
        },
        {
            "tweet_id": "123",
            "a": "f"
        }
    ]
}

POST /twitter/twit/1/_update
{"script":"foreach (item :ctx._source.list) {
                if item['tweet_id'] == tweet_id) {
                      item['new_field'] = 'ghi';
                }
           }",
 "params": {tweet_id": 123"}
}
Run Code Online (Sandbox Code Playgroud)

这是有效的

删除我这样做

POST /twitter/twit/1/_update
{ "script": "foreach (item : ctx._source.list) {
                    if item['tweet_id'] == tweet_id) {
                          ctx._source.list.remove(item); 
                    }
            }",
  "params": { tweet_id": "123" }
}
Run Code Online (Sandbox Code Playgroud)

但是这不起作用并且给出了这个错误,

ElasticsearchIllegalArgumentException [无法执行脚本]; 嵌套:ConcurrentModificationException; 错误:ElasticsearchIllegalArgumentException [无法执行脚本]; 嵌套:ConcurrentModificationException

我可以使用删除整个数组或整个字段

"script": "ctx._source.remove('list')"
Run Code Online (Sandbox Code Playgroud)

我也可以通过使用指定对象的所有键来从数组中删除对象

"script":"ctx._source.list.remove(tag)",
     "params" : {
        "tag" : {"tweet_id": "123","a": "f"}
Run Code Online (Sandbox Code Playgroud)

我的节点模块弹性搜索版本是2.4.2弹性搜索服务器是1.3.2

And*_*fan 17

你得到它,因为你试图在迭代它时修改一个列表,这意味着你想要更改一个对象列表,同时列出这些对象.

你需要这样做:

POST /twitter/twit/1/_update
{
  "script": "item_to_remove = nil; foreach (item : ctx._source.list) { if (item['tweet_id'] == tweet_id) { item_to_remove=item; } } if (item_to_remove != nil) ctx._source.list.remove(item_to_remove);",
  "params": {"tweet_id": "123"}
}
Run Code Online (Sandbox Code Playgroud)

如果您有多个符合条件的项目,请改用列表:

POST /twitter/twit/1/_update
{
  "script": "items_to_remove = []; foreach (item : ctx._source.list) { if (item['tweet_id'] == tweet_id) { items_to_remove.add(item); } } foreach (item : items_to_remove) {ctx._source.list.remove(item);}",
  "params": {"tweet_id": "123"}
}
Run Code Online (Sandbox Code Playgroud)


Lud*_*ord 8

对于需要在elasticsearch 2.0及以上版本中工作的人来说,nil并且foreach不会被groovy认可.

所以这是一个更新版本,包括用新对象替换具有相同id的项目的选项.

并且还传递它将upsert确保即使文档尚不存在也会添加项目

{
  "script": "item_to_remove = null; ctx._source.delivery.each { elem -> if (elem.id == item_to_add.id) { item_to_remove=elem; } }; if (item_to_remove != null) ctx._source.delivery.remove(item_to_remove); if (item_to_add.size() > 1) ctx._source.delivery += item_to_add;",
  "params": {"item_to_add": {"id": "5", "title": "New item"}},
  "upsert": [{"id": "5", "title": "New item"}]
}
Run Code Online (Sandbox Code Playgroud)