基于正则表达式对 Prometheus 查询中的标签进行分组 [英] Group labels in a Prometheus query based on regex

查看:319
本文介绍了基于正则表达式对 Prometheus 查询中的标签进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有这样的指标:

Imagine I have metrics like this:

sample_metric{type="some-type1-1234"} 2
sample_metric{type="some-type1-5678"} 1
sample_metric{type="some-type2-9876"} 4
sample_metric{type="some-type2-4321"} 3

现在我想根据遵循相同模式的类型对指标值求和.因此,对于上面的示例,所需的结果是有 2 个总和:

Now I would like to sum the metric values based on types that follow the same pattern. So, for the above example the desired result would be to have 2 sums:

type1: 3
type2: 7

这个问题有点类似于这个,但是就我而言,我事先不知道这些组.我只知道他们遵循的模式.有没有办法通过使用正则表达式的一个查询来实现这一点?

This question is somewhat similar to this one, however in my case I don't know the groups in advance. I just know the pattern that they follow. Is there a way to achieve this with one query using regex?

推荐答案

我再次在 的帮助下找到了方法这篇文章中接受的答案.为将来遇到相同问题的人发布答案:

I figured out how to do it, again with the help of the accepted answer from this post. Posting the answer for those who will have come across the same problem in the future:

sum by (type_group) (
  label_replace(
    label_replace(sample_metric, "type_group", "$1", "type", ".+"),
    "type_group", "$1", "type", "some-(\\w+(-\\w+)*)-.*"
  )
)

因此,内部 label_replace 引入了一个名为 type_group 的新标签,而外部 label_replace 将值替换为 type 在正则表达式的帮助下从原始标签中提取.因此,type_group 将包含值,例如 type1type2($1 指的是要拉取的正则表达式组).内部组 (-\\w+)* 表示您的组可能由几个部分组成,例如type1-type12,它会将其视为另一个组.

So, the inner label_replace introduces a new label called type_group, whereas the outer label_replace replaces the values with the type pulled from the original label, with the help of regex. So, type_group will contain values, such as type1 and type2 ($1 refers to the regex group to pull). The inner group (-\\w+)* indicates that your group might be comprised of several parts, e.g. type1-type12, and it will treat it as yet another group.

这篇关于基于正则表达式对 Prometheus 查询中的标签进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆