最近碰到根据条件批量修改某个属性跟集合里面某个属性的业务,自己摸索,给出以下例子
【批量修改根据条件修改某个属性值】
Map<String,Object> map = new HashMap<String,Object>();
map.put("tags","blue");
String idOrCode = "ctx._source.tags=params.tags"
UpdateByQueryRequestBuilder builder = UpdateByQueryAction.INSTANCE.newRequestBuilder(transportClientForOperate);
builder.source(index).filter(QueryBuilders.termsQuery(key, ids))
.script(new Script(ScriptType.INLINE, "painless", idOrCode, map))
.abortOnVersionConflict(false) // 设置ES版本导致问题失败是否停止运行
.get();
参数介绍
QueryBuilders.termsQuery(key, ids)
key 条件字段
ids 条件值,多个就是集合
new Script(ScriptType.INLINE, "painless", idOrCode, map)
idOrCode : 脚本语法 ctx._source.tags="blue"
map : 存储值 (也可以直接在脚本里硬编码,这里就直接写 Collections.emptyMap())
对应es语句
curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{
"script" : {
"inline": "ctx._source.tags = tag", // 对应api idOrCode
"params" : { // 对应api map里的键值对
"tag" : "blue"
}
}
}'
重点来了,修改对应集合里的数据怎么修改
例如ES数据存储:
"tagInfo": [
{
"tagId": 1,
"name": "标签",
"des": "说明",
"no": 1
},
{
"tagId": 2,
"name": "标签2",
"des": "说明2",
"no": 2
}
]
api写法
String key = "tagInfo";
String update_key = "name";
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","标签1");
String idOrCode =
"if (ctx._source.containsKey('"+ key +"')) {for (int i=0;i<ctx._source."+ key +".size();i++) { ctx._source."+ key +"[i]."+ update_key + "= params.name} }";
重点
if (ctx._source.containsKey('"+ key +"')) {
}
这个判断一定要写不然脚本会报空异常
如果要更改多个值拼接 idOrCode 的时候用;分开就行了哦;
最后看到这里对你有用的话,点个赞分享一下哦~
网友评论