gpt4 book ai didi

java - 带参数的 Elasticsearch java HighLevel 客户端更新脚本

转载 作者:行者123 更新时间:2023-11-30 05:49:36 25 4
gpt4 key购买 nike

我想通过在我的用户列表中添加一个元素来进行部分更新:

"users" : [
{
"password" : "pwd",
"level" : "admin",
"user_name" : "XX",
"last_name" : "YY",
"first_name" : "ZZ"
}
]

使用 Kibana 我尝试过此请求:

POST my_index/user/1/_update
{
"script" : {
"source": "ctx._source.users.add(params.user)",
"lang": "painless",
"params" : {
"user": {
"user_name" : "user",
"first_name" : "XX",
"last_name" : "XX",
"level" : "simple",
"password" : "pwd!#"
}
}
}
}

工作正常:

 "users" : [
{
"password" : "pwd",
"level" : "admin",
"user_name" : "XX",
"last_name" : "YY",
"first_name" : "ZZ"
},
{
"password" : "pwd!#",
"level" : "simple",
"user_name" : "user",
"last_name" : "XX",
"first_name" : "XX"
}
]

我想使用java客户端来做到这一点,我已经尝试过这段代码:

XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.field("user_name", user.getUserName());
builder.field("first_name", user.getFirstName());
builder.field("last_name", user.getLastName());
builder.field("level", user.getLevel());
builder.field("password", user.getPassword());
}
builder.endObject();
params.put("user", Strings.toString(builder));

UpdateByQueryRequest setScript = request.setScript(
new Script(
ScriptType.INLINE, "painless",
"ctx._source.users.add(params)",
params));
request.setScroll(TimeValue.timeValueMinutes(10));

BulkByScrollResponse bulkResponse = restHighLevelClient.updateByQuery(request, RequestOptions.DEFAULT);

结果,我得到了:

"users" : [
{
"password" : "pwd",
"level" : "admin",
"user_name" : "XX",
"last_name" : "YY",
"first_name" : "ZZ"
},
{
"user" : """{"user_name":"XX","first_name":"XX","last_name":"XX","level":"XX","password":"XX"}""",
"ctx" : {
"_routing" : null,
"_parent" : null,
"_index" : "administration",
"_type" : "environnement",
"_id" : "1",
"_version" : 24
}
}
]

所以这是不正确的,我只想将用户信息添加到用户中,并且我不想索引 ctx 信息。

谢谢!

最佳答案

有点晚了,但是......您的脚本中有一个拼写错误,您添加了 params 而不是 params.user。

UpdateByQueryRequest setScript = request.setScript(
new Script(
ScriptType.INLINE, "painless",
"ctx._source.users.add(params.user)", <-- here
params));
request.setScroll(TimeValue.timeValueMinutes(10));

无论如何,这可能无法解决它,我遇到过类似的问题,并发现最简单的解决方案是将每个值作为参数传递并在脚本中创建一次对象,这将给出:

parameters.put("user_name", user.getUserName());
parameters.put("first_name", user.getFirstName());
parameters.put("last_name", user.getLastName());
parameters.put("level", user.getLevel());
parameters.put("password", user.getPassword());
request.setScript(new Script(
ScriptType.INLINE,
"painless",
"ctx._source.users.add(params)",
parameters));
request.setScroll(TimeValue.timeValueMinutes(10));
BulkByScrollResponse bulkResponse = restHighLevelClient.updateByQuery(request,RequestOptions.DEFAULT);

关于java - 带参数的 Elasticsearch java HighLevel 客户端更新脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54172523/

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