Search code examples
grafanagrafana-loki

Grafana count of unique values by field


Using Grafana with the Loki source, I would like to know how to group rows by ctx_username and have a ctx_username_count

It would transform my data from

| ctx_username | ... |
| -------------|-----|
| username_1   | ... |
| username_1   | ... |
| username_2   | ... |
| username_1   | ... |

to

| ctx_username | ctx_username_count | ... |
| -------------|--------------------|-----|
| username_1   |         3          | ... |
| username_2   |         1          | ... |

in order to have a bar gauge diagram showing the number of requests made by each user (ctx_username) over the timerange.


Solution

  • I had it working using this query

    sum by (ctx_username) (
        count_over_time(
            {service_type="my-app"} | json | ctx_username !="" | __error__="" [$__interval]
        )
    )
    

    Calculation: Total, Numeric Fields
    Transform: Join by labels ctx_username

    When using bargauge, I also had to reduce Query Options > Max data points to 1 in order to have the right scale, it also made my query much faster.