PromQL 如何统计某个标签的唯一值数量?
统计标签唯一值数量的标准写法是嵌套 count:count(count(metric) by (label))——内层按标签分组,外层统计组数。本文给出实例、变体与常见错误写法。
标准写法:count(count(http_requests_total) by (instance))——内层 by (instance) 把序列按实例分组,外层 count 数出有多少个组,即 instance 的唯一值个数。
分解理解
count(http_requests_total) by (instance) # 每个 instance 一条结果(值是该实例的序列数)
外层再包一层 count(...)(不带 by),把"多少个分组"聚成一个数字:
count(count(http_requests_total) by (instance)) # 输出:42
常用变体
# 有多少种不同的状态码
count(count(http_requests_total) by (status))
# 每个 job 下有多少个实例
count by (job) (count by (job, instance) (up))
# 数健康的up序列;若同instance有多个job/重复抓取,不等于唯一实例数
count(up == 1)
常见错误
- ❌
count(http_requests_total)——数的是序列总数,不是标签唯一值; - ❌ 忘记内层
by——外层无从得知按什么维度去重。
常见问题(FAQ)
Q:能列出这些唯一值而不只是数量吗? 可以用 group by (instance) (http_requests_total),唯一值保留在结果标签中;API 的 label values 端点或 Grafana 查询变量的 label_values() 也是选择,后者不是 PromQL 函数。
Q:标签值很多时这个查询慢吗? 需要处理所选序列并聚合,耗时依序列数、查询范围和资源而异,不能仅按唯一值数量保证秒出。