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

Elasticsearch terms聚合如何让include指定词和其他按doc_count排序结果同时返回

实现方案

你可以通过自定义排序规则满足需求,核心逻辑是给指定的mazda、honda两个值设置更高的排序优先级,保证二者必然出现在结果中,剩余位置按doc_count从高到低填充,最终符合size=10的返回限制。

示例DSL

GET /_search
{
  "size": 0,
  "aggs": {
    "JapaneseCars": {
      "terms": {
        "field": "make",
        "size": 10,
        "order": [
          { "fixed_top": "desc" },
          { "_count": "desc" }
        ]
      },
      "aggs": {
        "fixed_top": {
          "script": {
            "source": "return ['mazda', 'honda'].contains(doc['make'].value) ? 1 : 0"
          }
        }
      }
    }
  }
}

逻辑说明

  • 新增子聚合fixed_top,通过脚本判断当前make字段值是否属于指定列表,是则返回1,否则返回0
  • 排序规则优先按fixed_top倒序排列,确保两个指定值永远排在结果最前列,之后再按文档计数倒序排列其余品牌
  • 最终返回的10条结果中,前2位为指定品牌,剩余8位为其他品牌按文档计数排序的TOP结果,指定品牌内部也会自动按文档计数排序

备选方案(无需开启脚本权限)

如果你所在的集群没有开启inline脚本权限,可以拆分两个聚合后自行合并结果:

GET /_search
{
  "size": 0,
  "aggs": {
    "fixed_brands": {
      "filters": {
        "filters": {
          "mazda": { "term": { "make": "mazda" } },
          "honda": { "term": { "make": "honda" } }
        }
      }
    },
    "other_brands": {
      "terms": {
        "field": "make",
        "size": 8,
        "exclude": ["mazda", "honda"],
        "order": { "_count": "desc" }
      }
    }
  }
}

将fixed_brands和other_brands的返回结果合并,即可得到10条符合要求的聚合数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:09:01