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

基于时间戳获取ElasticSearch最新数据的查询需求

解决方案

一、查询指定StoreID&RackID组合的最新记录

方法1:排序+限制返回数量

直接过滤目标StoreID和RackID,按时间戳倒序排序后仅返回第一条结果,适合快速获取单组最新数据:

{
  "query": {
    "bool": {
      "must": [
        {"term": {"StoreID": "目标门店ID"}},
        {"term": {"RackID": "目标货架ID"}}
      ]
    }
  },
  "sort": [{"timestamp": {"order": "desc"}}],
  "size": 1
}

方法2:Top Hits聚合

如果需要在聚合场景下获取单组最新数据,可使用top_hits聚合,结果会包含在聚合输出中:

{
  "query": {
    "bool": {
      "must": [
        {"term": {"StoreID": "目标门店ID"}},
        {"term": {"RackID": "目标货架ID"}}
      ]
    }
  },
  "aggs": {
    "latest_record": {
      "top_hits": {
        "size": 1,
        "sort": [{"timestamp": {"order": "desc"}}]
      }
    }
  },
  "size": 0
}

设置size:0是为了不返回原始匹配文档,仅查看聚合结果。

二、获取所有StoreID&RackID组合的最新记录

通过双层Terms聚合先按StoreID分组,再按RackID细分,每组内用top_hits聚合提取最新一条记录:

{
  "aggs": {
    "group_by_store": {
      "terms": {"field": "StoreID"},
      "aggs": {
        "group_by_rack": {
          "terms": {"field": "RackID"},
          "aggs": {
            "latest_book_record": {
              "top_hits": {
                "size": 1,
                "sort": [{"timestamp": {"order": "desc"}}]
              }
            }
          }
        }
      }
    }
  },
  "size": 0
}

查询结果层级为:group_by_store → 各StoreID桶 → group_by_rack → 各RackID桶 → latest_book_record → 对应组合的最新图书记录。

注意:若StoreID、RackID为文本类型,需确保字段是keyword类型(或已开启fielddata),否则terms聚合会报错;数字类型字段可直接使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:02:06