Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting elasticsearch top hits results

I am trying to execute a query in elasticsearch to get reuslt of specific users from certain date range. the results should be grouped by userId and sorted on trackTime field, I am able to use group by using aggregation but i am not able to sort aggregation buckets on tracktime, i write down the following query

GET _search
{
"size": 0,
"query": {
    "filtered": {
        "query": {
            "bool": {
                "must": [
                    {
                        "range": {
                            "trackTime": {
                                "from": "2016-02-08T05:51:02.000Z"
                            }
                        }
                    }
                ]
            }
        },
        "filter": {
            "terms": {
                "userId": [
                    9,
                    10,
                    3
                ]
            }
        }
    }
},
"aggs": {
    "by_district": {
        "terms": {
            "field": "userId"
        },
        "aggs": {
            "tops": {
                "top_hits": {
                    "size": 2
                }
            }
        }
    }
}
 }

what more should i have to use to sort the top hits result? Thanks in advance...

like image 658
Adarsh Bajpai Avatar asked Feb 11 '16 04:02

Adarsh Bajpai


People also ask

How do I sort Elasticsearch results?

You can sort Elasticsearch results using the sort keyword. The sort query requires you to provide a field under which to sort. Elasticsearch does not support sorting on fields of type text.

What is top hit aggregation?

A top_hits metric aggregator keeps track of the most relevant document being aggregated. This aggregator is intended to be used as a sub aggregator, so that the top matching documents can be aggregated per bucket.

What are hits in Elasticsearch?

A search consists of one or more queries that are combined and sent to Elasticsearch. Documents that match a search's queries are returned in the hits, or search results, of the response. A search may also contain additional information used to better process its queries.


1 Answers

You can use sort like .

"aggs": {
"by_district": {
    "terms": {
        "field": "userId"
    },
    "aggs": {
        "tops": {
            "top_hits": {
                "sort": [
                    {
                        "fieldName": {
                            "order": "desc"
                        }
                    }
                ],
                "size": 2
            }
        }
        }
     }
 }

Hope it helps

like image 179
Richa Avatar answered Oct 10 '22 08:10

Richa