MST

星途 面试题库

面试题:ElasticSearch如何通过脚本实现简单的搜索结果折叠

假设你有一个ElasticSearch索引,文档包含字段 'category' 和 'name',要求使用脚本对 'category' 相同的文档进行折叠,仅返回每个 'category' 下 'name' 字段值按字典序排序后的第一个文档,简述实现思路并给出可能的脚本示例。
20.5万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 首先,使用聚合(Aggregation)来按 category 字段进行分组。
  2. 在每个分组内,对 name 字段进行排序,这里使用 terms 聚合的 order 参数来指定排序。
  3. 从排序后的结果中取第一个文档,使用 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 字段的第一个文档。