最近碰到根據(jù)條件批量修改某個屬性跟集合里面某個屬性的業(yè)務(wù),自己摸索彼妻,給出以下例子
【批量修改根據(jù)條件修改某個屬性值】
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) // 設(shè)置ES版本導(dǎo)致問題失敗是否停止運行
.get();
參數(shù)介紹
QueryBuilders.termsQuery(key, ids)
key 條件字段
ids 條件值,多個就是集合
new Script(ScriptType.INLINE, "painless", idOrCode, map)
idOrCode : 腳本語法 ctx._source.tags="blue"
map : 存儲值 (也可以直接在腳本里硬編碼儒溉,這里就直接寫 Collections.emptyMap())
對應(yīng)es語句
curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{
"script" : {
"inline": "ctx._source.tags = tag", // 對應(yīng)api idOrCode
"params" : { // 對應(yīng)api map里的鍵值對
"tag" : "blue"
}
}
}'
重點來了桥嗤,修改對應(yīng)集合里的數(shù)據(jù)怎么修改
例如ES數(shù)據(jù)存儲:
"tagInfo": [
{
"tagId": 1,
"name": "標(biāo)簽",
"des": "說明",
"no": 1
},
{
"tagId": 2,
"name": "標(biāo)簽2",
"des": "說明2",
"no": 2
}
]
api寫法
String key = "tagInfo";
String update_key = "name";
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","標(biāo)簽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 的時候用;分開就行了哦埂伦;
最后看到這里對你有用的話煞额,點個贊分享一下哦~