使用Elasticsearch Java API检索特定字段

use*_*610 15 elasticsearch

我正在使用Java API进行Elasticsearch.将实体保存到索引中后,可以将它们与完整的源一起检索.但是,我只想检索选定的字段,这是行不通的.

下面的示例代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

将从索引中检索正确的实体,包括完整的源.

例如,这是响应的片段:

"hits" : {
  "total" : 1301,
  "max_score" : 0.99614644,
  "hits" : [ {
  "_index" : "my-index",
  "_type" : "my-type",
  "_id" : "AU2P68COpzIypBTd80np",
  "_score" : 0.99614644,
  "_source":{"field1":"1234", ...}]}
}, {
Run Code Online (Sandbox Code Playgroud)

然而,虽然response.getHits()回报命中的预期数量,fields以及source每个命中内是空的.

我期望每个匹配包含行中指定的字段:

.addFields("field1")
Run Code Online (Sandbox Code Playgroud)

评论出来

.setFetchSource(true)
Run Code Online (Sandbox Code Playgroud)

将导致响应根本不包括源.

Elasticsearch的版本是1.5.0

以下是Java API的maven依赖:

<dependency>
   <groupId>com.sksamuel.elastic4s</groupId>
   <artifactId>elastic4s_2.11</artifactId>
   <version>1.5.5</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

很明显,出于性能原因,我不想检索完整的实体.有谁知道如何限制检索到选定的字段?谢谢

Val*_*Val 40

您可以使用该setFetchSource(String[] includes, String[] excludes)方法指定所需的字段.试试这个

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();
}
Run Code Online (Sandbox Code Playgroud)

map 将仅包含您指定的字段.

请注意.setFetchSource("field1", null)(如果您需要单个字段)或.setFetchSource("field*", null)(如果您需要多个通配字段)也可以.

  • @ user1052610你能使用建议的解决方案吗? (3认同)