Prometheus topk函数返回所有结果

Prometheus topk function returning all results

我正在尝试根据过去 24 小时内的登录次数绘制出排名前 5 位的用户。但是当我使用下面的 topk 函数时,我得到了那个时间范围内的所有用户登录。

查询: topk(10, sum(my_app_login) by (User_Name) != 0)

如何将其限制为前 10 名?

首先,您需要在Grafana中启用instant query。在这种情况下,Grafana 将只 return 每个结果时间序列中所选时间范围内的最后一个数据点,而不是 return 所选时间范围内每个时间序列的许多数据点。

其他注意事项:

  • 如果 my_app_logincounter,则以下查询应该 return 过去 24 小时内登录操作最多的用户:
topk(10, sum(increase(my_app_login[24h])) by (User_Name))

请注意,即使 my_app_login 仅包含整数值,Prometheus 也可能 return 此查询的小数结果。这是因为 Prometheus 中 increase() 函数的数据模型怪癖 - 请参阅 this comment and this article for details. If you need exact integer results, then take a look at MetricsQL from VictoriaMetrics

  • 如果 my_app_logingauge,其中包含自上一个示例以来的应用登录次数,则以下查询应该有效:
topk(10, sum(sum_over_time(my_app_login[24h])) by (User_Name))

有关详细信息,请参阅 sum_over_time() docs

请注意 MetricsQL 中的 topk(N, ...) function may return more than N time series when this function is used for building a graph over time (aka range query). This is because it returns top N time series independently per each timestamp on the graph. If you need no more than top N time series on the graph, then take a look at topk_max, topk_last 和其他 topk_* 函数。