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

如何在Elasticsearch中获取每个account_id的最新文档?

按account_id获取对应最新文档的实现方法

要实现按account_id分组,获取每个分组下最新的文档,你可以用Elasticsearch的terms聚合搭配top_hits聚合来完成,具体DSL如下:

{
  "size": 0,
  "aggs": {
    "group_by_account": {
      "terms": {
        "field": "account_id"
      },
      "aggs": {
        "latest_doc": {
          "top_hits": {
            "size": 1,
            "sort": [
              {
                "created_at": {
                  "order": "desc"
                }
              }
            ],
            "_source": ["created_at", "account_id", "其他你需要的字段"]
          }
        }
      }
    }
  }
}

关键部分说明:

  • size: 0:关闭搜索结果的hits返回,只保留聚合结果,节省资源
  • terms聚合:按account_id字段对文档进行分组
  • top_hits聚合:在每个account_id分组内,按created_at降序排序,只取第1条数据,也就是该分组下最新的文档
  • _source:可选配置,指定需要返回的字段,避免返回整个文档的冗余数据,按需添加即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 15:17:02