面试题答案
一键面试实现思路
- 首先,使用聚合(Aggregation)来按
category
字段进行分组。 - 在每个分组内,对
name
字段进行排序,这里使用terms
聚合的order
参数来指定排序。 - 从排序后的结果中取第一个文档,使用
top_hits
子聚合来实现。
脚本示例
{
"size": 0,
"aggs": {
"category_groups": {
"terms": {
"field": "category",
"order": {
"sorted_name": "asc"
}
},
"aggs": {
"sorted_name": {
"terms": {
"field": "name",
"order": {
"_key": "asc"
}
}
},
"top_name": {
"top_hits": {
"size": 1
}
}
}
}
}
}
在上述示例中:
terms
聚合根据category
字段分组。- 内部的
terms
聚合对每个category
分组内的name
字段按字典序升序排序。 top_hits
聚合从排序后的结果中只取第一个文档。最终返回的结果是每个category
下按字典序排序name
字段的第一个文档。