【问题标题】:Retrieving specific fields using the Elasticsearch Java API使用 Elasticsearch Java API 检索特定字段
【发布时间】: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() 返回预期的命中数,但每个命中中的 fieldssource 为空。

我希望每个命中都包含该行中指定的字段:

.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


    【解决方案1】:

    您可以使用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)(如果您需要多个通配符字段)也可以。

    【讨论】:

    • @user1052610 你能使用建议的解决方案吗?
    • 不适用于 ElasticSearch 5.x。 :( 它在响应中返回一个空的“_source”字段,并且不会将“field1”复制为真实字段。
    • @cs94njw 这不应该改变according to the source。随意创建一个引用此问题的新问题,以便我们对其进行整理。
    • 可以使用这种方法过滤到 json 字段值的子属性吗?
    • @Yoshimitsu 是的,肯定的,比如parent.child.grandchild
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    相关资源
    最近更新 更多