You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Elasticsearch查询实现单店铺最多返回3条商品结果?

问题:限制Elasticsearch查询中每个店铺最多返回3条商品结果

我正在从Elasticsearch数据库查询商品链接,库中已导入多电商平台的商品数据。当前查询返回123条记录,但包含大量套装、不同颜色等同类变体商品。我希望限制每个店铺最多返回3条商品结果,但多次尝试后仍返回全部数据,请问如何修改查询语句实现该限制?

当前查询语句:

{
  "size": 100,
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "key": {
              "query": "Some Keyword",
              "fuzziness": "1",
              "prefix_length": "0",
              "max_expansions": 3,
              "operator": "and",
              "analyzer": "product_analyzer"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "group_by_shop": {
      "terms": {
        "field": "shop_id.keyword",
        "size": 100
      },
      "aggs": {
        "top_hits_per_shop": {
          "top_hits": {
            "size": 100,
            "sort": [
              { "_score": { "order": "desc" } }
            ]
          }
        }
      }
    }
  }
}

解决方案

你当前的聚合配置中,top_hits的size被设为100,这会返回每个店铺下所有匹配的商品。只需修改两处即可实现每个店铺最多返回3条结果:

  • 将top_hits聚合内的size值从100改为3,这样每个店铺分组仅保留评分最高的3条商品
  • 若不需要返回根级的原始hits数据,可将根级的size设为0,避免冗余数据返回

修改后的完整查询语句:

{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "key": {
              "query": "Some Keyword",
              "fuzziness": "1",
              "prefix_length": "0",
              "max_expansions": 3,
              "operator": "and",
              "analyzer": "product_analyzer"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "group_by_shop": {
      "terms": {
        "field": "shop_id.keyword",
        "size": 100
      },
      "aggs": {
        "top_hits_per_shop": {
          "top_hits": {
            "size": 3,
            "sort": [
              { "_score": { "order": "desc" } }
            ]
          }
        }
      }
    }
  }
}

修改后,聚合结果里每个shop_id对应的top_hits_per_shop只会包含该店铺下评分最高的3条商品,完全满足你的需求。

内容的提问来源于stack exchange,提问作者Michael Müller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 06:03:09