Search code examples
prometheusgrafanapromql

Prometheus query to get % of each range


We are storing the number of chars entered by the user using prometheus histogram in the following fashion. I'm having hard time to get % of 1 char entered compared to the total chars entered.

number_of_char_distribution_bucket{country="GB",le="1.0",} 1
number_of_char_distribution_bucket{country="GB",le="2.0",} 3
number_of_char_distribution_bucket{country="GB",le="3.0",} 5
number_of_char_distribution_bucket{country="GB",le="4.0",} 5
number_of_char_distribution_bucket{country="GB",le="5.0",} 5

number_of_char_distribution_count 9

I have the following query and it shows only the number of char distribution

sum(increase(number_of_char_distribution_bucket{_namespace_="addautcmp",vendor_name="ADA"}[24h])) by (le)

I need to get this data in a bar graph, currently it is a guage.


Solution

  • The following query returns the number of times users entered one char over the last 24 hours:

    sum(increase(number_of_char_distribution_bucket{le="1.0"}[24h]))
    

    The following query returns the total number of times users entered any number of chars over the last 24 hours:

    sum(increase(number_of_char_distribution_count[24h]))
    

    Just divide the first query by the second query in order to get percentage (in the range [0...1]) of times when users entered just one char:

    sum(increase(number_of_char_distribution_bucket{le="1.0"}[24h]))
      /
    sum(increase(number_of_char_distribution_count[24h]))
    

    If you need calculating the percentage of times users entered exactly two chars, then use the following query:

    (
      sum(increase(number_of_char_distribution_bucket{le="2.0"}[24h]))
        -
      sum(increase(number_of_char_distribution_bucket{le="1.0"}[24h]))
    )
      /
    sum(increase(number_of_char_distribution_count[24h]))
    

    This query subtracts the number of times users entered 1 (le="1.0") from the number of times users entered 1 or 2 chars (le="2.0") in order to get the number of times users entered exactly 2 chars, and then divides it by the total number of times users entered any number of chars.

    See these docs about Prometheus histograms for more details.