Node.js 从数组弹性搜索中删除对象
我需要从满足条件的数组中删除对象,我可以根据条件更新数组的对象,如下所示:Node.js 从数组弹性搜索中删除对象,node.js,elasticsearch,mvel,Node.js,elasticsearch,Mvel,我需要从满足条件的数组中删除对象,我可以根据条件更新数组的对象,如下所示: PUT twitter/twit/1 {"list": [ { "tweet_id": "1", "a": "b" }, { "tweet_id": "123", "a": "f" } ] } POST /twitter/twit/1/_up
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"}
我的节点模块elastic search版本是2.4.2 elastic search server版本是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"}
}
对于需要在elasticsearch 2.0及更高版本中使用此功能的用户,groovy无法识别
nil
和foreach
这是一个更新版本,包括用新对象替换具有相同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"}]
}
谢谢Andrei Stefan,这是有效的,如果列表中只包含一个tweet_id=123的对象,但这是无效的,如果我想删除多个具有相同tweet_id=123的对象,我需要做些什么???另外,如果你能对答案进行投票,我将不胜感激。非常感谢Andrei Stefan,这正在起作用,在这之后,我非常高兴,因为昨天我花了几乎一整天的时间在这上面,再次感谢你……我怎么知道列表有'remove'方法,它是否有
append
你能不能也加入groove语言,以删除多个值作为列表,而不是单个删除?