首页 > 解决方案 > Elasticsearch:搜索分组结果

问题描述

我在 elasticsearch 索引中加载了来自不同类别的产品目录 - 衬衫、裤子、鞋子等。

我想支持一个用例,允许按名称搜索产品并获得按类别分组的结果。例如,当我搜索“红色”时,我想查看前 5 件红色衬衫、前 5 件红色裤子、前 5 件红色鞋子

我在这里找到了一种使用 top hits 聚合的方法。但我不确定这是否是正确的进步方式。这是一个 2 级聚合,我担心这会使查询变慢。

有没有更好(更快?)的方法来实现这一目标?

编辑:添加示例数据

样本目录

[
    {
        "title": "Red Shirt",
        "category": "Shirt",
        "id": 1
    },
    {
        "title": "Blue Shirt",
        "category": "Shirt",
        "id": 2
    },
    {
        "title": "Green Shirt",
        "category": "Shirt",
        "id": 3
    },
    {
        "title": "Black Shoes",
        "category": "Shoes",
        "id": 4
    },
    {
        "title": "White Shoes",
        "category": "Shoes",
        "id": 5
    },
    {
        "title": "Red Shoes",
        "category": "Shoes",
        "id": 6
    },
    {
        "title": "Red and White Shoes",
        "category": "Shoes",
        "id": 7
    },
    {
        "title": "Red Bag",
        "category": "Bag",
        "id": 8
    },
    {
        "title": "Red and Blue Bag",
        "category": "Bag",
        "id": 9
    },
    {
        "title": "Yello Bag",
        "category": "Bag",
        "id": 10
    }
]

搜索“红色”时的预期响应

[
    {
        "category": "Shirt",
        "results": [
            {
                "title": "Red Shirt",
                "category": "Shirt",
                "id": 1
            }
        ]
    },
    {
        "category": "Shoes",
        "results": [
            {
                "title": "Red Shoes",
                "category": "Shoes",
                "id": 6
            },
            {
                "title": "Red and White Shoes",
                "category": "Shoes",
                "id": 7
            }
        ]
    },
    {
        "category": "Bag",
        "results": [
            {
                "title": "Red Bag",
                "category": "Bag",
                "id": 8
            },
            {
                "title": "Red and Blue Bag",
                "category": "Bag",
                "id": 9
            }
        ]
    }
]

标签: elasticsearch

解决方案


推荐阅读