Top 20 paths sorted by latency

I am using Grafana v10.4.1 (d94d597d84) set up on k8s.

I am trying to see the top 20 paths sorted by latency. I am having troubles using sort_desc and topk. It’s not working, the results it shows are not sorted and not showing 20 top results but more.

I am using bar gauge visualization. I’m using Loki as a datasource.

Here’s the query I am using:

sort_desc(topk(20, sum by(path_endpoint) (rate({namespace=~"$namespace", stream=~"$stream", container=~"$container"} 
| json 
|= `$query` 
| path_endpoint =~ `.+` 
| path_endpoint !~ `/api/internal.+` 
| path_endpoint !~ `/ws` 
| __error__=`` 
| unwrap latency [5m]
))))

Does anybody have an idea what could be wrong?