Nicolas
Nicolas

Reputation: 355

Count labels for which two metrics meet criteria

I have prometheus metrics from N number of hosts, each with two different components as lables:

my_status{host="H1", component="a"}
my_status{host="H1", component="b"}
my_status{host="H2", component="a"}
my_status{host="H2", component="b"}
...
my_status{host="HN", component="a"}
my_status{host="HN", component="b"}

my_status is an integer between 0 and 2.

I want to count how many hosts have a my_status of 2 for both components.

How do I do this in Grafana?

Upvotes: 1

Views: 1049

Answers (1)

anemyte
anemyte

Reputation: 20176

EITHER component 'a' or 'b' status == 2:

count(
  count by (host) (my_status{component=~"a|b"} == 2)
)

BOTH component 'a' and 'b' status == 2:

count(
  count by (host) (my_status{component="a"} == 2 and my_status{component="b"} == 2)
)

The inner query counts the number of my_status time series, where the value is 2 and the component condition is met. The result is grouped per host, so if you ran it you would see something like this:

{host="A"} 1
{host="B"} 2
{host="D"} 4

The outer query simply counts the number of values returned by the inner query. Since there is only one value per host, it gives you the number of hosts matching the criteria.

Upvotes: 1

Related Questions