How to display top 10 IPs in descending order in Grafana/Loki table?

I’m trying to show the top 10 IPs by request count in a Grafana table panel, sorted from highest to lowest. My current query returns more than 10 IPs and doesn’t sort them correctly. The big problem is that he returns me more than 10 ip, this happen because topk work in this way, how to make it show me just 10 ip and no more?

Log Format

$remote_addr $geoip2_data_country_code - $remote_user [$time_local] “$request” …

Current Query

topk(10,
sum by (ip) (
count_over_time(
{job=“cisi”, filename=“/var/log/nginx/cisi/access.log”}
| pattern <ip> <_>
[5m]
)
)
)

Issue
Returns >10 rows even with topk(10).

Not sorted descending (values appear random).

Expected Result
A table (or something else its not important) with exactly 10 rows, ordered from highest to lowest:

IP Requests
192.168.1.100 1500
192.168.1.101 1200
… (top 8 more)

Try this…

1. Loki Log Query

Use this Loki query to extract IPs and count their frequency:

{job="cisi", filename="/var/log/nginx/cisi/access.log"}
| pattern <ip> <_>
| unwrap ip
| stats count() by ip

2. Grafana Table Setup

  • Query returns fields: ip and count
    In Table Panel > Transformations, apply these in order:
  • Sort by
    • Field: count
    • Order: Descending
  • Limit
  • Rows: 10

You will get exactly 10 rows, sorted from most to least requests like: