ElasticSearch 搜索,获取返回产品的唯一类别

ElasticSearch search, get unique categories of returned products

在拥有数千种产品的网店中,我们在顶部有一个搜索栏。搜索的预期输出是一个类别列表,其中有与查询匹配的产品。

例如,搜索 'iphone' 应该 return 包含具有该关键字的产品的类别列表。 例如 - 手机 - 手机电池 - 手机壳 - 等等

我所做的是在产品索引中搜索关键字,然后获取结果,提取每个产品的 category_id,删除重复项并使用我应该使用的 ID 在类别索引中执行 /_mget显示。

然而,这似乎是无用的,因为第一次搜索可能 return 10k 个结果(如果它太笼统)然后我循环获取它的 category_id.

我正在寻找更好的方法来完成上述操作。

关于如何提高上述效率的任何想法?

看看 Elasticsearch Aggregationshttps://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html

一个好的起点是 Terms Aggregation,它是一个 bucket 聚合 https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html

一个例子:

GET /_search
{
    "query": {...},
    "aggs" : {
        "categories" : {
            "terms" : { "field" : "category_name" }
        }
    }
}

响应应该看起来像这样,它将字段值和计数放入 buckets

{
    ...
    "aggregations" : {
        "categories" : {
            "doc_count_error_upper_bound": 0, 
            "sum_other_doc_count": 0, 
            "buckets" : [ 
                {
                    "key" : "Mobile phones",
                    "doc_count" : 6
                },
                {
                    "key" : "Batteries for phones",
                    "doc_count" : 3
                },
                {
                    "key" : "Cases for phones",
                    "doc_count" : 2
                }
            ]
        }
    }
}