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

Elasticsearch中如何对composite聚合的facets按supplierTitle筛选

解决方案

方案1:查询阶段前置过滤(性能最优,优先推荐)

直接把supplierTitle的匹配条件加入顶层bool查询,这样聚合阶段只会基于同时满足productName和supplierTitle匹配规则的文档生成分桶,无需后续过滤,性能损耗最低。
示例代码如下:

GET /_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "productName": "A product name"
          }
        },
        {
          "match": {
            "supplierTitle": "你的自定义匹配内容"
          }
        }
      ]
    }
  },
  "size": 0,
  "aggs": {
    "my_buckets": {
      "composite": {
        "sources": [
          { "_id": {"terms": {"field": "supplierId"}}},
          { "supplierTitle": {"terms": {"field": "supplierTitle"}}}
        ]
      }
    }
  }
}

方案2:聚合后分桶过滤(适合无法前置过滤的特殊场景)

如果业务逻辑要求必须先统计所有匹配productName的文档的供应商组合,再对分桶做supplierTitle的过滤,可以在composite聚合下新增一个filter子聚合执行match查询,再通过bucket_selector管道聚合只保留命中match规则的分桶。
示例代码如下:

GET /_search
{
  "query": {
    "match": {
      "productName": "A product name"
    }
  },
  "size": 0,
  "aggs": {
    "my_buckets": {
      "composite": {
        "sources": [
          { "_id": {"terms": {"field": "supplierId"}}},
          { "supplierTitle": {"terms": {"field": "supplierTitle"}}}
        ]
      },
      "aggs": {
        "title_match_check": {
          "filter": {
            "match": {
              "supplierTitle": "你的自定义匹配内容"
            }
          }
        },
        "filter_buckets": {
          "bucket_selector": {
            "buckets_path": {
              "match_count": "title_match_check._count"
            },
            "script": "params.match_count > 0"
          }
        }
      }
    }
  }
}

注意:该方案需要在集群配置中开启inline script支持,且性能比方案1低,仅在业务确实需要先全量聚合再过滤的场景下使用。

内容的提问来源于stack exchange,提问作者domen hočevar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:45:03