我正在为 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();
}
将从索引中检索正确的实体,包括完整的来源。
例如,这是响应的一个片段:
"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
下面是Java API的maven依赖:
<dependency>
<groupId>com.sksamuel.elastic4s</groupId>
<artifactId>elastic4s_2.11</artifactId>
<version>1.5.5</version>
</dependency>
显然,出于性能原因,我不想检索完整的实体。 有谁知道如何限制对选定字段的检索? 谢谢
最佳答案
您可以使用 setFetchSource(String[] includes, String[] excludes)
method 指定您需要的字段.试试这个吧
SearchResponse response = client.prepareSearch("my-index")
.setTypes("my-type")
.setSearchType(SearchType.QUERY_AND_FETCH)
.setFetchSource(new String[]{"field1"}, null)
.setQuery(QueryBuilders.termsQuery("field1", "1234"))
.execute()
.actionGet();
for (SearchHit hit : response.getHits()){
Map map = hit.getSource();
map.toString();
}
map
将只包含您指定的字段。
请注意 .setFetchSource("field1", null)
(如果您需要单个字段)或 .setFetchSource("field*", null)
(如果您需要几个通配符字段)也可以。
关于elasticsearch - 使用 Elasticsearch Java API 检索特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30476493/