gpt4 book ai didi

node.js - 从数组 Elasticsearch 中删除对象

转载 作者:IT老高 更新时间:2023-10-28 23:18:30 26 4
gpt4 key购买 nike

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

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[failed to execute script]; nested: ConcurrentModificationException; Error: ElasticsearchIllegalArgumentException[failed to execute script]; nested: ConcurrentModificationException

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

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

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

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

我的 Node 模块 Elasticsearch 版本是2.4.2 Elasticsearch 服务器是1.3.2

最佳答案

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

您需要这样做:

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

关于node.js - 从数组 Elasticsearch 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26257884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com