How Do I Write an "Or" Logical Operator on Prometheus or Grafana

Better Stack Team
Updated on December 2, 2024

In Prometheus and Grafana, you can implement an "OR" logical operation using the or operator in Prometheus Query Language (PromQL) or by structuring queries appropriately in Grafana. Here’s how to use the "OR" operator effectively in both contexts.

Using the or Operator in PromQL

The or operator allows you to combine multiple metrics or expressions. When either condition is true, the combined result will be true.

Syntax

 
metric1 or metric2

Example 1: Basic Usage of or

Assuming you have two metrics, http_requests_total{status="200"} and http_requests_total{status="500"}, and you want to retrieve data where either status is present:

 
http_requests_total{status="200"} or http_requests_total{status="500"}

This query will return results for both the 200 and 500 HTTP status codes.

Example 2: Combining Metrics with or

You can also use the or operator to combine different metrics. For example, if you have a metric for HTTP requests and another for error rates:

 
http_requests_total or http_errors_total

This will return data from both metrics where either exists.

Step 2: Using the or Operator in Grafana

When writing queries in Grafana using Prometheus as a data source, you can use the or operator in the query editor just as you would in a standard Prometheus query.

  1. Open your Grafana dashboard and add a new panel.
  2. In the query editor, enter your PromQL expression using the or operator.
  3. Execute the query to see the combined results.

Example in Grafana

If you want to visualize requests or errors, you can input:

 
sum(rate(http_requests_total[5m])) or sum(rate(http_errors_total[5m]))

This query would provide a time series showing either the rate of requests or the rate of errors over the last 5 minutes.

Considerations

  • Label Matching: When using or, ensure that the metrics being combined share relevant labels if you expect to compare them directly. Mismatched labels may result in empty results.
  • Result Handling: The result of an or operation will be a vector that combines the matching time series, which can be useful for comparisons or aggregations in Grafana visualizations.