# How to sort and limit aggregations in ElasticSearch

**URL:** <https://discuss.elastic.co/t/how-to-sort-and-limit-aggregations-in-elasticsearch/29731>\
**Category:** Elasticsearch\
**Created:** [September 21, 2015, 8:55pm UTC](https://discuss.elastic.co/t/how-to-sort-and-limit-aggregations-in-elasticsearch/29731 "2015-09-21T20:55:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jack\_Wang](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jack_wang/32/4886_2.png) [@Jack\_Wang](https://discuss.elastic.co/u/Jack_Wang)\
**Post date:** [September 21, 2015, 8:55pm UTC](https://discuss.elastic.co/t/how-to-sort-and-limit-aggregations-in-elasticsearch/29731/1 "2015-09-21T20:55:36Z")

</div>

For example I have the following records with the columns as:(Country,City,Date,Income)

```
USA SF 2015-01 80
USA SF 2015-03 60
USA SF 2015-05 20
USA NY 2015-09 70
USA NY 2015-02 30
U.K LD 2015-05 30
U.K LD 2015-01 20

```

My sql as: `select country,city,max(date) as maxDate,sum(income) as sumIncome from testTable group by country,city order by maxDate desc,sumIncome desc limit 2`.  
So the result should be:

```
USA NY 2015-09 100
USA SF 2015-05 160

```

I wrote the ES aggregates as following, but it's wrong:

```
"aggs":{"sub1": {"terms":{"field":"contry"},
   "aggs":{"sub2":{"terms":{"field":"city",
       "order":[{"submax":"DESC"},{"subsum":"DESC"}]},
     "aggs":{"submax":{"max":{"field":"date"}},"subsum":{"sum":{"field":"income"}}}}}}}

```

First Problem: it's not sorted globally, it seems that just sort in each bucket,  
Another problem is that I don't know how to limit the size to 2. Thanks in Advance!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 11:48pm UTC](https://discuss.elastic.co/t/how-to-sort-and-limit-aggregations-in-elasticsearch/29731/2 "2017-07-05T23:48:56Z")

</div>


