How to get the one record from each aggregation group?

We want to get the first record (based on inserted time in ascending order) from each aggregation group. We monitor the servers and events are inserted to elastic search from different sources on same device.

Let us assume that we have two servers(A & B) and 10 events are inserted per each device from different sources. How to get the first record(based one timestamp) from each device.

When I apply the below query, its getting two records from same device(A). I want to get the first event(one from device A and second from device B) from each device. Can anyone help on this?

GET test_elastalert1/_search

{

"sort" : [ { "time" : "asc" } ] ,

"size": 2,

"query": {

"bool": {

"must": [{"match": {"event_sev": "Critical"}},

{"range" : {"time" : {"gte" : "now-8h" , "lt" : "now" , "format": "yyyy-MM-dd HH:mm:ss"}}}]

}

} ,

"aggs": {

"Group_By_host": {

"terms": {

"field": "Hostname.keyword"

}

}

}

}

you could use the top_hit aggregation to get just the 'top' record from your bucket

Thanks peter for your reply. I used below query to get results. but those are displaying under the aggregation section. How can we get them in main hits section?

"aggs": {
"Group_By_host": {
"terms": {
"field": "Hostname.keyword"

},
        "aggs": {
            "group_docs": {
                "top_hits": {
                    "size": 1,
                    "sort": [
                        {
                            "time": {
                                "order": "asc"
                            }
                        }
                    ]
                }
            }
        }

}

}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.