简体   繁体   中英

How to sort inner aggregate of date_histogram aggregation in Elasticsearch?

How to write a simple Elasticsearch aggregation query to get the equivalent of this simple MySQL query:

SELECT
    `date`,
    `total`
FROM `table`
GROUP BY `date`
ORDER BY `total` DESC
LIMIT 10;

The most straightforward way in Elasticsearch is:

{
    "size": 0,
    "aggregations": {
        "date_agg": {
            "date_histogram": {
                "field": "date",
                "interval": "day"
            },
            "aggregations": {
                "total_agg": {
                    "sum": {
                        "field": "total"
                    }
                }
            }
        }
    }
}

However, that would yield all days from a huge index, which might be not efficient. Also I'd have to manually find the top 10 sums result manually.

What's the efficient way to do all this in Elasticsearch?

Use below query and you are good to go :

{
"size": 0,
"aggregations": {
    "date_agg": {
        "date_histogram": {
            "field": "date",
            "interval": "day",
            "order" : {
                "total_agg" :"desc"   ====> Notice this
            }
        },
        "aggregations": {
            "total_agg": {
                "sum": {
                    "field": "total"
                }
            }
        }
     }
  } 
 }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM