Details of Top N records

Hi,

I have an index with following schema:

GroupName,Time,Value

Example values:

G1 2020-01-01 1:00:00. 10
G2 2020-01-01 1:00:00. 15
G3 2020-01-01 1:00:00. 20
G1 2020-01-01 2:00:00. 10
G2 2020-01-01 2:00:00. 20
G3 2020-01-01 2:00:00. 30
G1 2020-01-01 3:00:00. 25
G2 2020-01-01 3:00:00. 10
G3 2020-01-01 3:00:00. 10

Out of above records G3 and G1 has top 2 values 30 and 25 respectively. So, need the all records of G1 and G2.

G1 2020-01-01 1:00:00. 10
G3 2020-01-01 1:00:00. 20
G1 2020-01-01 2:00:00. 10
G3 2020-01-01 2:00:00. 30
G1 2020-01-01 3:00:00. 25
G3 2020-01-01 3:00:00. 10

Is it possible to get this in single elastic query by using aggregations?

not on top of my head. You could go with a terms agg on the groupname field, that contains a max aggregation for the maximum value for each groupname and sort the terms agg based on that.

Then with a second query you could filter by groupname G1 or G3 if those are the top two max values from the first request.