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

如何在ElasticSearch聚合查询中获取各桶对应的文档?

解决方法:在Terms聚合中嵌套Top Hits聚合

可以实现你要的效果,核心是在terms聚合内部嵌套top_hits子聚合,用来获取每个颜色分组下的具体文档。

修改后的查询语句

{
  "aggs": {
    "distinct_colours": {
      "terms": {
        "field": "colour"
      },
      "aggs": {
        "top_docs": {
          "top_hits": {
            "size": 1, // 控制每个颜色桶返回的最大文档数,按需调整
            "_source": ["id", "availability"] // 指定仅返回需要的字段,减少数据冗余
          }
        }
      }
    }
  }
}

关键参数说明

  • top_hits:专门用于在聚合桶内返回匹配的文档,是实现需求的核心。
  • size:设置每个桶返回的文档数量,比如设为5就会返回每个颜色下的前5条文档。
  • _source:指定需要返回的字段,避免返回整个文档的不必要数据,提升性能。

对应的返回结果(匹配你的期望结构)

{
  "took" : 2037,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 10000,
      "relation" : "gte"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "distinct_colours" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 34,
      "buckets" : [
        {
          "key" : "BLACK",
          "doc_count": 123,
          "top_docs": {
            "hits": {
              "total": {
                "value": 123,
                "relation": "eq"
              },
              "max_score": 1.0,
              "hits": [
                {
                  "_index": "your_index",
                  "_id": "block_doc_key",
                  "_score": 1.0,
                  "_source": {
                    "id": "block_doc_key",
                    "availability": true
                  }
                }
              ]
            }
          }
        },
        {
          "key" : "GREEN",
          "doc_count": 456,
          "top_docs": {
            "hits": {
              "total": {
                "value": 456,
                "relation": "eq"
              },
              "max_score": 1.0,
              "hits": [
                {
                  "_index": "your_index",
                  "_id": "green_doc_key",
                  "_score": 1.0,
                  "_source": {
                    "id": "green_doc_key",
                    "availability": false
                  }
                }
              ]
            }
          }
        }
      ]
    }
  }
}

额外扩展

如果需要对每个桶内的文档排序,可以在top_hits中添加sort配置,比如按availability字段倒序:

"top_hits": {
  "size": 1,
  "_source": ["id", "availability"],
  "sort": [{"availability": "desc"}]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 16:05:25