Elasticsearch:按指定年份子记录评分总和排序指定分类父产品
指定分类下产品按指定年份评论评分总和降序查询
你已通过Elasticsearch的parent/child关系存储产品(product)与评论(review)数据,需实现以下查询需求:获取指定category_id下的所有产品,并按指定年份内该产品所有评论的ratings总和降序排序。
查询DSL示例
假设目标分类ID为456,目标年份为2024,查询语句如下:
GET /your_index_name/_search { "size": 0, "query": { "bool": { "filter": [ { "term": { "category_id": "456" } }, { "term": { "join_field": "product" } } ] } }, "aggs": { "products": { "terms": { "field": "product_id", "size": 1000, "order": { "total_ratings": "desc" } }, "aggs": { "product_info": { "top_hits": { "size": 1, "_source": ["product_id", "product_name", "category_id", "type"] } }, "target_year_reviews": { "filter": { "bool": { "must": [ { "term": { "join_field": "review" } }, { "term": { "year": 2024 } } ] } }, "aggs": { "total_ratings": { "sum": { "field": "ratings" } } } } } } } }
语句说明
- 外层查询:通过
bool.filter筛选出指定category_id的父文档(product),确保只处理目标分类下的产品。 - 产品分组聚合:
products聚合按product_id对产品分组,同时指定按total_ratings(评分总和)降序排序。 - 产品详情获取:
product_info的top_hits聚合提取每个产品的核心字段信息。 - 评分总和计算:
target_year_reviews过滤出指定年份的评论子文档,再通过total_ratings的sum聚合计算该产品在目标年份的评分总和。
注意事项
- 将
your_index_name替换为实际使用的索引名称。 - 根据数据量调整
terms聚合的size参数,确保能返回所有目标产品。 - 你的映射中
product_id已设为keyword类型,无需担心父/子文档中ID类型不一致的匹配问题。
内容的提问来源于stack exchange,提问作者Shashank
相关产品推荐
相关产品推荐

