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

Elastic Search多品牌查询:按比例分配结果数量需求

Elasticsearch 查询优化与比例结果限制方案

一、返回指定格式的查询语句

你当前的查询可以通过添加_source字段精准控制返回字段,确保结果匹配需求格式。修改后的查询如下:

{
  "size": 100,
  "_source": ["brand", "contentType", "expirationDate", "pubdate", "editorial"],
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "should": [
            {"term": {"brand": "brandA"}},
            {"term": {"brand": "brandB"}}
          ]
        }
      }
    }
  }
}

添加_source后,ES只会返回你指定的字段,结构完全符合你给出的示例。

二、按比例限制各品牌结果数量

可以实现按比例分配结果,比如总100条时brandA占60%(60条)、brandB占40%(40条),推荐两种方案:

方案1:聚合+Top Hits

通过terms聚合按brand分组,搭配top_hits子聚合分别获取对应数量的结果,一次查询完成:

{
  "size": 0,
  "aggs": {
    "brandA_group": {
      "filter": {"term": {"brand": "brandA"}},
      "aggs": {
        "top_docs": {
          "top_hits": {
            "size": 60,
            "_source": ["brand", "contentType", "expirationDate", "pubdate", "editorial"]
          }
        }
      }
    },
    "brandB_group": {
      "filter": {"term": {"brand": "brandB"}},
      "aggs": {
        "top_docs": {
          "top_hits": {
            "size": 40,
            "_source": ["brand", "contentType", "expirationDate", "pubdate", "editorial"]
          }
        }
      }
    }
  }
}

查询结果会在聚合节点下分别返回两个品牌的目标数据,合并两部分即可得到总结果。

方案2:多查询(Multi Search)

通过_msearch接口发起两次独立查询,分别获取对应数量的结果后合并:

{}
{
  "size": 60,
  "_source": ["brand", "contentType", "expirationDate", "pubdate", "editorial"],
  "query": {"term": {"brand": "brandA"}}
}
{}
{
  "size": 40,
  "_source": ["brand", "contentType", "expirationDate", "pubdate", "editorial"],
  "query": {"term": {"brand": "brandB"}}
}

这种方式逻辑更直观,适合需要为不同品牌配置额外查询条件的场景。

内容的提问来源于stack exchange,提问作者Saby

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:59:51