我需要从满足条件的数组中删除对象,我可以根据条件更新数组的对象,如下所示:
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 [无法执行脚本]; 嵌套:ConcurrentModificationException; 错误:ElasticsearchIllegalArgumentException [无法执行脚本]; 嵌套:ConcurrentModificationException
我可以使用删除整个数组或整个字段
"script": "ctx._source.remove('list')"
我还可以通过使用指定对象的所有键来从数组中删除对象
"script":"ctx._source.list.remove(tag)", "params" : { "tag" : {"tweet_id": "123","a": "f"}
我的节点模块elasticsearch版本是2.4.2elasticsearch服务器是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"} }