This is a multiple group by scenario where data are being sorted by the key descending order.
{
"size": 0,
"aggs": {
"categories": {
"filter": {
"exists": {
"field": "organization_industries"
}
},
"aggs": {
"names": {
"terms": {
"field": "organization_revenue_in_thousands_int.keyword",
"size": 200,
"order": {
"_key": "desc"
}
},
"aggs": {
"industry_stats": {
"terms": {
"field": "organization_industries.keyword"
}
}
}
}
}
}
}
}
Yes, you can do it by adding another sub-aggregation on the max document score and sorting the `unique` `terms` aggregation by that score.
curl -XGET "http://localhost:9200/myidx/product/_search?search_type=count" -d '{
"size": 2,
"query": {
"function_score": {
"field_value_factor": {
"field": "relevance",
"factor": 2.0
},
"query": { "term": { "title": "abcd" } },
"score_mode": "multiply",
"boost_mode": "multiply"
}
},
"aggs": {
"unique": {
"terms": {
"field": "groupid",
"size": 2,
"order": {
"max_score": "desc"
}
},
"aggs": {
"max_score": {
"max": {
"script": "doc.score"
}
},
"sample": {
"top_hits": {
"size": 1
}
}
}
}
}
}'