Sorting after aggregation in Elasticsearch
You almost had it. You just need to add an order
property to your a1
terms aggregations, like this:
GET myindex/_search
{
"size":0,
"aggs": {
"a1": {
"terms": {
"field": "FIELD1",
"size":0,
"order": {"a2": "desc"} <--- add this
},
"aggs":{
"a2":{
"sum":{
"field":"FIELD2.SUBFIELD"
}
}
}
}
}
}
Brilliant from Val https://stackoverflow.com/users/4604579/val
Basically the same thing, but here's what worked for me to find the largest "size" for each "name", and to show the top 25 largest:
{
"size": 0,
"aggs": {
"agg1": {
"terms": {
"field": "name.keyword",
"order": {
"agg2": "desc"
},
"size": 25
},
"aggs": {
"agg2": {
"max": {
"field": "size"
}
}
}
}
}
}