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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github