如何使用java更改Elasticsearch中文档的字段属性?

时间:2016-08-05 06:52:49

标签: elasticsearch

我在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},如何实现这一目标?

1 个答案:

答案 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();