Search code examples
prometheusgrafana

Prometheus Count unique label with all the other label combinations


I want to setup a grafana table visualization to group different label values and show the counts.

For e.g, a metric vouchers_total has labels currency, channel and voucher_id. Each of them has many but limited values. I want the table visualization to display values of channel and currency in the first 2 columns, and then show the count of distinct voucher_ids under the current currency, channel pair in the 3rd column.

vouchers_total is a counter. I increment its value by 1 each time it is used. And a voucher_id of a currency-channel pair is considered a valid count if it has been incremented at least once in the past 24 hours (rate(vouchers_total[24h]) > 0).


Solution

  • You can use query like this:

    count by(currency, channel) (
     count by(currency, channel, voucher_id) (
      increase(vouchers_total[24h]) > 0
     )
    )
    

    Here:

    • increase(vouchers_total[24h]) > 0 returns only metrics which where incremented over last 24 hours,
    • count by(currency, channel, voucher_id) ( .. ) return count of metrics with distinct triads (currency, channel, voucher_id) among results of previous step. Aggregation function selected on this step doesn't matter, and can be any of them. Out goal is to simply get list of distinct triads, with no interest in produced value,
    • count by(currency, channel) ( .. ) counts number of voucher_ids per every pair of (currency, channel) among results of previous step.