prometheuspromqlthanos

Return 1 or 0 from PromQL query if the output out both PromQL result are same


I have two Prometheus metrics,

First PromQL

sum by (cluster) (
    cnp_pg_replication_slots_active{
       role="primary",
       cluster="p-vpt7bgc20z"
    } == 1
)  

which gives me result like

{cluster="p-vpt7bgc20z"}    2

Second PromQL

sum by (cluster) (
    cnp_collector_up { 
        role="replica",
        cluster="p-vpt7bgc20z"
    }
)

which also gives me result like

{cluster="p-vpt7bgc20z"}    2

Now I want to return 1 if both results are same or return 0 if any mismatch. how can I archive that?

If I write

sum by (cluster) (
    cnp_pg_replication_slots_active{
       role="primary",
       cluster="p-vpt7bgc20z"
    } == 1
)  == sum by (cluster) (
    cnp_collector_up { 
        role="replica",
        cluster="p-vpt7bgc20z"
    }
)

it gives me result as but I want result as boolean value 1 & 0.

{cluster="p-vpt7bgc20z"}    2

Solution

  • In promQL you can use bool modifier after comparison operator to return 0 or 1 instead of filtering. For example, metric > bool 100.

    Demo for use in query can be seen here.

    Documentation for this matter here.

    Your query will be

    sum by (cluster) (
        cnp_pg_replication_slots_active{
           role="primary",
           cluster="p-vpt7bgc20z"
        } == 1
    )  == bool sum by (cluster) (
        cnp_collector_up { 
            role="replica",
            cluster="p-vpt7bgc20z"
        }
    )