java - elasticsearch group by ID field and perform max on date field -
my index has data mentioned below.
id version_number groupid indexdate 1 v1 1 2016-11-15t12:00:00 2 v1 2 2016-11-20t12:00:00 3 v2 2 2016-12-01t12:00:00 4 v1 3 2016-13-01t12:00:00 5 v1 4 2016-11-01t12:00:00 6 v2 4 2016-13-01t12:00:00 7 v1 5 2016-14-01t12:00:00
how can write elasticsearch query in java. if search date 2016-13-01t12:00:00 expect see latest version per groupid has indexdate less or equal date searched?
output expected:
id version_number groupid indexdate 1 v1 1 2016-13-01t12:00:00 2 v2 2 2016-11-20t12:00:00 6 v3 3 2016-10-01t12:00:00 7 v2 4 2016-10-01t12:00:00
i dont see max function on date field in elasticsearch achieve this.
i first aggregate on version_number
and use top_hits
sub-aggregation sorted on descending indexdate
, returning id of first document of bucket.
{ "size": 0, "aggs": { "by_version": { "terms": { "field": "version_number" }, "aggs": { "max_date": { "top_hits": { "size": 1, "sort": { "indexdate": "desc" }, "_source": [ "id" ] } } } } } }
Comments
Post a Comment