13

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

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

这是有效的

为了删除我正在这样做

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

但这不起作用并给出此错误,

ElasticsearchIllegalArgumentException[执行脚本失败]; 嵌套:并发修改异常;错误:ElasticsearchIllegalArgumentException[未能执行脚本];嵌套:ConcurrentModificationException

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

"script": "ctx._source.remove('list')"

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

"script":"ctx._source.list.remove(tag)",
     "params" : {
        "tag" : {"tweet_id": "123","a": "f"}

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

4

2 回答 2

20

您之所以会这样,是因为您在迭代列表时尝试修改列表,这意味着您想要更改对象列表,同时列出这些对象。

相反,您需要这样做:

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

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

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"}
}
于 2014-10-08T16:43:36.460 回答
9

对于需要在 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"}]
}
于 2016-06-29T16:33:43.923 回答