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?
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)
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With