我在Elasticsearch中有一份文件:
{
"_index": "test",
"_type": "document",
"_id": "1",
"_score": 1,
"_source": {
"class": "aaa",
"id": 1,
"items": [{
"class": "aaa",
"id": 1
}, {
"class": "ccc",
"id": 2
}],
"bianhao": "123"
}
}
我想将{"class": "ccc","id": 2}
items
替换为{"class": "ccc12","id": 2}
,如何实现这一目标?
答案 0 :(得分:1)
你可以这样做:
Map<String, Object> params = new HashMap<>();
params.put("idParam", 2);
params.put("classParam", "ccc12");
client.prepareUpdate("test", "document", "1")
.setScript(new Script(
"ctx._source.items.find{ it.id == idParam }['class'] = classParam",
ScriptService.ScriptType.INLINE, null, params))
.get();
<强>更新强>
如果你想改变多个字段,你可以这样做:
Map<String, Object> params = new HashMap<>();
params.put("idParam", 2);
params.put("classParam", "ccc12");
params.put("field1Param", "value2");
params.put("field2Param", "value3");
client.prepareUpdate("test", "document", "1")
.setScript(new Script(
"def item = ctx._source.items.find{ it.id == idParam}; if (item) {item['class'] = classParam; item['field1'] = field1Param; item['field2'] = field2Param}",
ScriptService.ScriptType.INLINE, null, params))
.get();