JAVA API: get the oldest document within a time range

Hello everyone,

I can't manage to query with the java api while I can do it with logstash for instance.
Here is the context: I have an index where documents have fields called 'size' and 'time'. What I would like to do is to get the oldest document within a time range. Do you know how to do that with the java API ?

I know that i have to use the function rangeQuery("time").from("xxx").to("yyyy")
to set the time range, but i don't find any function 'sort'..

Thank you for your attention and your help.


It should look like .addSort("field", SortOrder.ASC). Here is an example from the tests.

Thanks Nik.
Actually, in my log I also have the field device. So i would like to get my specific value for every device. Tha'ts why I use sub aggregation but it does not work.

Here is the code:
SearchResponse response1 = (SearchResponse) client.prepareSearch(index)
.subAggregation((BytesReference) QueryBuilders.termsLookupQuery("size"))
.addSort("time", SortOrder.ASC)

Exception in thread "main" java.lang.ClassCastException: org.elasticsearch.index.query.TermsLookupQueryBuilder cannot be cast to org.elasticsearch.common.bytes.BytesReference

Maybe you need the min bucket pipeline aggregation? I don't know aggregations super well but it seems more likely than a sort.