弹性搜索搜索,获取唯一类别的退货产品



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

例如,搜索"iphone"应该返回一个类别列表,其中有带有该关键字的产品。 例如 -手机 - 手机电池 - 手机保护套 -等。

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

然而,这似乎是无效的,因为第一次搜索可能会返回 10k 个结果(如果它太通用(,然后我循环访问以获取其category_id。

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

关于如何使上述更有效的任何想法?

看看 ElasticsearchAggregationshttps://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
}
]
}
}
}

最新更新