0

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?

1 Answer 1

1

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"
                }
            }
        }
     }
  } 
 }  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.