ElasticSearch Jest客户端,如何从命中返回文档ID?

时间:2015-10-26 18:15:08

标签: elasticsearch jest

我正在使用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?

2 个答案:

答案 0 :(得分:8)

只是fyi,正在寻找相同的,所以看看Jest的源代码,看到Jest用&#34; _id&#34;填充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)

答案 1 :(得分:5)

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

正如@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");
    }
}