如何在PromQL中获取范围向量的第一个与最后一个元素
PromQL 获取范围向量首尾采样点查询方案
前置条件
Prometheus 版本 >= v2.29.0,该版本首次正式提供 first_over_time、last_over_time 两个区间聚合函数。
单条查询语句
- 获取1小时区间内每个Pod的**最早(第一条)**内存使用记录:
first_over_time(container_memory_usage_bytes[1h])
- 获取1小时区间内每个Pod的**最新(最后一条)**内存使用记录:
last_over_time(container_memory_usage_bytes[1h])
同时返回首尾两条记录
如果需要单次查询同时拿到同一个Pod的首尾两条记录,可以通过label_replace函数新增标识标签区分两种数据:
label_replace(first_over_time(container_memory_usage_bytes[1h]), "record_type", "first", "", "") or label_replace(last_over_time(container_memory_usage_bytes[1h]), "record_type", "last", "", "")
返回结果会自带record_type标签,取值为first/last分别对应首条、末条记录。
低版本兼容方案
如果你的Prometheus版本低于v2.29.0没有内置上述函数,可以用以下方式替代:
- 末条记录直接查询瞬时向量即可,默认返回最新采样点:
container_memory_usage_bytes
- 首条记录可以通过偏移查询配合
min_over_time+子查询实现(采样间隔按需调整,以下示例为15s):
min_over_time((container_memory_usage_bytes offset 1h)[1h:15s])
内容的提问来源于stack exchange,提问作者Faheem Sohail
相关产品推荐
相关产品推荐

