问题描述
我有一个包含嵌套对象的弹性搜索文档,我想通过java更新api来删除它们。这里是包含脚本的代码: UpdateRequest updateRequest = new UpdateRequest(INDEX,thread,String.valueOf(threadId) );
updateRequest.script(for(int i = 0; i {ctx._source.messages.remove(i); i--;}},ScriptService.ScriptType.INLINE);
client.update(updateRequest).actionGet();
这是我的文档的映射:
{
thread_and_messages:{
mappings:{
thread:{
properties:{
message:{
type:nested,
include_in_parent:true,
properties:{
message_id:{
type:string
},
message_nick:{
type:string
},
message_text b $ btype:string
}
}
},
thread_id:{
type:long
}
}
}
}
}
}
我没有收到任何错误消息,但是当我在索引上运行查询以查找该嵌套文档时尚未被删除。有人可以让我知道我做错了什么?
由于 message_id
是一个字符串
您的脚本需要解释它,并像这样修改(请参阅 message_id
字段)。有一个第二个错字,因为您的映射声明一个 message_id
字段,但您在脚本中将其命名为 _message_id
: | | |
没有下划线添加转义双引号
最后还要确保你有在您的ES配置
更新
您可以尝试groovy-er从列表中删除元素,即循环和如果
不再有,只需使用groovy权限:
ctx._source.messages.removeAll {it.message_id == \+ messageId +\}
通常,这将通过删除所有元素来修改消息
其 message_id
字段匹配 messageId
值。
I have an elasticsearch documents which contain nested objects within them, I want to be able to remove them via the java update api. Here is the code containing the script:
UpdateRequest updateRequest = new UpdateRequest(INDEX, "thread", String.valueOf(threadId));
updateRequest.script("for (int i = 0; i < ctx._source.messages.size(); i++){if(ctx._source.messages[i]._message_id == " + messageId + ")" +
"{ctx._source.messages.remove(i);i--;}}", ScriptService.ScriptType.INLINE);
client.update(updateRequest).actionGet();
This is the mapping of my document:
{
"thread_and_messages": {
"mappings": {
"thread": {
"properties": {
"messages": {
"type": "nested",
"include_in_parent": true,
"properties": {
"message_id": {
"type": "string"
},
"message_nick": {
"type": "string"
},
"message_text": {
"type": "string"
}
}
},
"thread_id": {
"type": "long"
}
}
}
}
}
}
I'm not receiving any error messages, but when I run a query on the index to find that nested document it hasn't been removed. Could someone let me know what I am doing wrong?
Since message_id
is a string
your script needs to account for it and be modified like this (see the escaped double quotes around the message_id
field). There is a second typo, in that your mapping declares a message_id
field but you name it _message_id
in your script:
"for (int i = 0; i < ctx._source.messages.size(); i++){if(ctx._source.messages[i].message_id == \"" + messageId + "\")"
^ ^ ^
| | |
no underscore here add escaped double quotes
Finally also make sure that you have dynamic scripting enabled in your ES config
UPDATE
You can try a "groovy-er" way of removing elements from lists, i.e. no more for
loop and if
, just use the groovy power:
"ctx._source.messages.removeAll{ it.message_id == \"" + messageId + "\"}"
Normally, that will modify the messages
array by removing all elements whose message_id
field matches the messageId
value.
这篇关于Elasticsearch - 使用java api删除嵌套对象不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!