Search code examples
elasticsearchelasticsearch-jest

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?


Solution

  • 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)