How Do I Write a Prometheus Query That Returns the Value of a Label?

Better Stack Team
Updated on December 2, 2024

To write a Prometheus query that returns the value of a specific label, you need to use the basic syntax for querying metrics and utilize the appropriate label matchers. Here’s how to construct a query to extract the value of a label from a specific metric.

Basic Query Structure

The general structure for querying metrics in Prometheus is:

 
metric_name{label_name="label_value"}

Example Scenario

Let’s say you have a metric called http_requests_total, which counts the total number of HTTP requests and has labels such as method, status, and instance. Here’s how you can query to return values based on these labels.

Step 1: Query a Metric with Specific Labels

To get the total number of HTTP requests for a specific method (e.g., GET), you would write:

 
http_requests_total{method="GET"}

This query returns the total number of GET requests, including all instances of the metric. If you want to see this value aggregated by status code, you could use:

 
sum(http_requests_total{method="GET"}) by (status)

This returns the sum of GET requests grouped by their status codes.

Step 2: Return Values of All Unique Labels

If you want to return all the unique values of a specific label (e.g., method) from the http_requests_total metric, you can use the label_values function in conjunction with the Prometheus UI or Grafana.

For example, to get unique methods used in the requests:

 
label_values(http_requests_total, method)

Step 3: Using the group Function

To focus specifically on extracting label values, you can also use the group function to return a list of unique label values. This is particularly useful when visualizing metrics or generating reports.

For example, if you want to see the unique values of the instance label:

 
count(http_requests_total) by (instance)

This counts the number of occurrences of http_requests_total for each unique instance label.