Grafana查询获取唯一标签值

Grafana query to get unique tag values

我想为某些指标的特定标签获取唯一值。 例如,如果我有指标 'metric_name' 有标签 'tag_name1' 和 'tag_name2':

metric_name{tag_name1='a',tag_name2='b'}
metric_name{tag_name1='c',tag_name2='d'}
metric_name{tag_name1='e',tag_name2='f'}

我想获取 'tag_name1' 标签的唯一值:a、c、e

有点喜欢:

select distinct tag_name1 from metric_name

TLDR;

带有查询 label_values(tag_name1) 的模板可以完成这项工作。

更多详情:

根据 prometheus 标签,我猜你正在使用这个数据库。

您可以使用 Grafana templating 获取某些指标的特定标记的唯一值。

Query is the most common type of Template variable. Use the Query template type to generate a dynamic list of variables, simply by allowing Grafana to explore your Data Source metric namespace when the Dashboard loads.

For example a query like prod.servers.* will fill the variable with all possible values that exists in that wildcard position (in the case of the Graphite Data Source).

因此您可以使用 label_values 添加模板并查询 Prometheus query in Grafana

  • 如果您需要获取唯一的标签值以便在 Grafana template variable, then use label_values(metric_name, tag_name1) function for variable of type Query 中使用它们。请注意,label_values() 函数在 Grafana 端执行 - PromQL 中不存在此函数。

  • 如果您需要在图表或 table 上显示唯一的标签值,请使用以下 PromQL 查询:

count(metric_name) by (tag_name1)

它 returns 每个唯一 tag_name1 值具有 metric_name 名称的时间序列的数量。有关详细信息,请参阅有关 count() function and about aggregate functions 的文档。

  • 如果需要通过自定义程序或脚本获取唯一的标签值,那么可以使用Prometheus提供的以下API:

    • /api/v1/label/<label_name>/values - 例如,curl http://prometheus:9090/api/v1/label/tag_name1/values returns tag_name1 标签在 Prometheus 中存储的所有时间序列中的所有唯一值。
    • /api/v1/series 例如,curl 'http://prometheus:9090/api/v1/series?match[]=metric_name' returns 所有带有metric_name 的时间序列。然后您可以从此响应中收集唯一的 tag_name1 标签值。

实际上,Grafana 在处理上述 label_values() 功能时使用了这些 API。