2016-08-05 75 views
0

我哈瓦在Elasticsearch文檔:如何使用Java改變文檔字段屬性在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": "ccc12","id": 2}取代的items{"class": "ccc","id": 2},如何實現這一目標?

回答

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

UPDATE

如果要更改多個字段,你可以做這樣的:

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(); 
+0

在這種情況下, ,首先找到'id',然後將值設置爲'class'。我的意思是說如果有很多字段,'{「id」:2,「class」:「ccc」,「name」:「dddd」,「field1」: 「value1」,「field1」:「value2」}',如何替換一次? –

+0

你想更改多個字段嗎? – Val

+0

yes.By找到id,更改所有的字段。 –

相關問題