Grafana query to get unique tag values
Asked Answered
D

2

8

I want to get unique values for specific tag of some metric. For example if I have metric 'metric_name' has tags 'tag_name1' and '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'}

I want to get unique values of 'tag_name1' tag: a,c,e

Kind of like:

select distinct tag_name1 from metric_name
Dowry answered 28/11, 2018 at 10:29 Comment(0)
P
7

TLDR;

Template with query label_values(tag_name1) would do the job.

More details:

By the prometheus tag I guess you are working with this db.

You can use the Grafana templating to get the unique values for specific tag of some metric.

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).

So you can add template and query using label_values for Prometheus query in Grafana.

Petepetechia answered 28/11, 2018 at 11:52 Comment(0)
M
3
  • If you need to get unique label values for using them in Grafana template variable, then use label_values(metric_name, tag_name1) function for variable of type Query. Note that label_values() function is executed at Grafana side - this function doesn't exist in PromQL.

  • If you need to display unique label values on a graph or table, then use the following PromQL query:

count(metric_name) by (tag_name1)

It returns the number of time series with metric_name name per each unique tag_name1 value. See docs about count() function and about aggregate functions for more details.

  • If you need to get unique label values via a custom program or script, then the following APIs provided by Prometheus can be used:

    • /api/v1/label/<label_name>/values - for example, curl http://prometheus:9090/api/v1/label/tag_name1/values returns all the unique values for tag_name1 label across all the time series stored in Prometheus.
    • /api/v1/series for example, curl 'http://prometheus:9090/api/v1/series?match[]=metric_name' returns all the time series with metric_name. Then you can collect unique tag_name1 label values from this response.

Actually, Grafana uses these APIs when it processes label_values() function mentioned above.

Mella answered 9/4, 2022 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.