Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElasticSearch Jest client, how to return document id from hit?

I'm using Jest as ElasticSearch client to search documents:

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

Each Hit object looks like:

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

While I can only find hit.source method, it seems no hit.id method.

Parse it as JSON object and retrieve key _id's value is a way, but is there any API that can get the document id?

like image 277
coderz Avatar asked Dec 04 '22 02:12

coderz


2 Answers

Just fyi, was looking for same so took a look at Jest source code and saw that Jest does populate hit.source.es_metadata_id with the "_id" if it exists (see io.searchbox.core.SearchResult, line 115)

So could do something like following as alternative to annotation:

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)
like image 55
D.McClure Avatar answered Dec 28 '22 14:12

D.McClure


It seems no way to get _id via Jest API, have to get _id from _source object.

As @juliendangers mentioned, add @JestId annotation can achieve:

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

And must explicitly set document id: myClass.setDocumentId("some_id");

Each Hit object looks like: {"_index":"some_index","_type":"some_type","_id":"some_id","_score":2.609438,"_source":{"foo":"bar","documentId":"some_id"}}

(If not explicitly set document id, the "documentId":"some_id" pair will be missing from Hit)

While according to my test, if use inheritance, have to explicitly set parent class's document id:

public class ParentClass {
    @JestId private String documentId;
}

public class MyClass extends ParentClass {
    private String foo;
    public MyClass() {
        super.setDocumentId("some_id");
    }
}
like image 22
coderz Avatar answered Dec 28 '22 14:12

coderz