【发布时间】:2018-09-26 05:05:55
【问题描述】:
我正在为 Elasticsearch 使用 Java API。 将实体保存到索引中后,可以将它们与完整的源一起检索。但是,我只想检索选定的字段,这是行不通的。
以下示例代码:
SearchResponse response = client.prepareSearch("my-index")
.setTypes("my-type")
.setSearchType(SearchType.QUERY_AND_FETCH)
.setFetchSource(true)
.setQuery(QueryBuilders.termsQuery("field1", "1234"))
.addFields("field1")
.execute()
.actionGet();
for (SearchHit hit : response.getHits()){
Map<String, SearchHitField> fields = hit.getFields();
System.out.println(fields.size());
Map map = hit.getSource();
map.toString();
}
将从索引中检索正确的实体,包括完整的源代码。
例如,这是一个sn-p的响应:
"hits" : {
"total" : 1301,
"max_score" : 0.99614644,
"hits" : [ {
"_index" : "my-index",
"_type" : "my-type",
"_id" : "AU2P68COpzIypBTd80np",
"_score" : 0.99614644,
"_source":{"field1":"1234", ...}]}
}, {
但是,虽然 response.getHits() 返回预期的命中数,但每个命中中的 fields 和 source 为空。
我希望每个命中都包含该行中指定的字段:
.addFields("field1")
注释掉一行
.setFetchSource(true)
将导致响应根本不包括源。
Elasticsearch 的版本是 1.5.0
以下是maven对Java API的依赖:
<dependency>
<groupId>com.sksamuel.elastic4s</groupId>
<artifactId>elastic4s_2.11</artifactId>
<version>1.5.5</version>
</dependency>
显然,出于性能原因,我不想检索完整的实体。 有谁知道如何将检索限制在选定的字段? 谢谢
【问题讨论】:
标签: elasticsearch