【问题标题】:ElasticSearch Jest client, how to return document id from hit?ElasticSearch Jest客户端,如何从命中返回文档ID?
【发布时间】:2015-10-26 18:15:08
【问题描述】:

我使用 Jest 作为 ElasticSearch 客户端来搜索文档:

JestClient client = ...;
Search search = ...;
SearchResult searchResult = client.execute(search);
List<Hit<T, Void>> hits = searchResult.getHits(klass);

每个Hit 对象看起来像:

{"_index":"some_index","_type":"some_type","_id":"some_id","_score":2.609438,"_source":{"foo1":"bar1","foo2":"bar2"}}

虽然我只能找到hit.source 方法,但似乎没有hit.id 方法。

将其解析为JSON对象并检索键_id的值是一种方法,但是有没有可以获取文档ID的API?

【问题讨论】:

  • 如果你使用注解@JestId向你的Class klass添加一个id,它应该被直接映射

标签: elasticsearch elasticsearch-jest


【解决方案1】:

仅供参考,正在寻找相同的内容,因此查看了 Jest 源代码,发现 Jest 确实使用“_id”填充 hit.source.es_metadata_id(如果存在)(请参阅 io.searchbox.core.SearchResult,第 115 行)

所以可以做如下的事情来代替注释:

List<Hit<Map,Void>> hits = client.execute(search).getHits(Map.class)
Hit hit = hits.get(0)
Map source = (Map)hit.source
String id = (String)source.get(JestResult.ES_METADATA_ID)

【讨论】:

    【解决方案2】:

    似乎无法通过Jest API 获取_id,必须从_source 对象获取_id

    正如@juliendangers所说,添加@JestId注解可以实现:

    public class MyClass {
        @JestId private String documentId;
        private String foo;
    }
    

    并且必须显式设置文档 id: myClass.setDocumentId("some_id");

    每个Hit 对象看起来像: {"_index":"some_index","_type":"some_type","_id":"some_id","_score":2.609438,"_source":{"foo":"bar","documentId":"some_id"}}

    (如果没有明确设置文档 ID,"documentId":"some_id" 对将在 Hit 中丢失)

    根据我的测试,如果使用继承,必须显式设置父类的文档ID:

    public class ParentClass {
        @JestId private String documentId;
    }
    
    public class MyClass extends ParentClass {
        private String foo;
        public MyClass() {
            super.setDocumentId("some_id");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 2020-08-27
      • 2013-03-31
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多