elasticsearch,Java,elasticsearch" /> elasticsearch,Java,elasticsearch" />

Java 从elasticsearch索引或更新查询返回特定字段

Java 从elasticsearch索引或更新查询返回特定字段,java,elasticsearch,Java,elasticsearch,这是我的索引或更新文档代码的一部分。我想获取一个特定的字段值“documentID”,它位于“\u source”中。这里的“json”是文档模型的JSONObject String jsonForUpdate = json.toString(); String uuid = UUID.randomUUID().toString(); json.put("documentID", uuid); String jsonForIndex = json.toString();

这是我的索引或更新文档代码的一部分。我想获取一个特定的字段值“documentID”,它位于“\u source”中。这里的“json”是文档模型的JSONObject

 String jsonForUpdate = json.toString();
    String uuid = UUID.randomUUID().toString();
    json.put("documentID", uuid);
    String jsonForIndex = json.toString();   
    IndexRequest indexRequest = new IndexRequest(indexName, typeName, documentModel.getId());
    indexRequest.source(jsonForIndex);
    UpdateResponse updateResponse = elasticsearchTemplate.getClient().prepareUpdate(indexName, typeName , documentModel.getId()).setDoc(jsonForUpdate).setUpsert(indexRequest).setFields("documentID").get();
我尝试使用此代码来获取文档字段的值

updateResponse.getGetResult().getFields().get("documentID").getValue().toString();
但它在更新文档时对我不起作用。在为文档编制索引时效果很好。

如果您查看:

您可以看到更新时可以传递的以下参数:

_source

Allows to control if and how the updated source should be returned in the response. By default the updated source is not returned. See source filtering for details.
这意味着在
prepareUpdate
中,您可以使用
setFetchSource(true)
方法,尽管这会带来完整的文档

更新: 对于2.3.3版,您仍然可以使用:

/**
 * Explicitly specify the fields that will be returned. By default, nothing is returned.
 */
public UpdateRequestBuilder setFields(String... fields) {
    request.fields(fields);
    return this;
}
Elasticsearch文档:


该方法在UpdateRequestBuilder上可用,UpdateRequestBuilder是prepareUpdate返回的对象的类。

我使用的是ElasticsearchTemplate。setFetchSource没有选项(true)您是否尝试过:UpdateResponse UpdateResponse=ElasticsearchTemplate.getClient().prepareUpdate(indexName,typeName,documentModel.getId()).setFetchSource(true).setDoc(jsonForUpdate).setU psert(indexRequest).setFields(“documentID”).get()?setFetchFields(true)没有选项。它不是setFetchFields(true),而是setFetchSource(true),我之前测试过它,所以我觉得这很可疑,除非您使用的是非常旧的版本。setFetchSource(true)也没有选项