It's even easier
sum by (group) (my_metric)
Answer from uamanager on Stack OverflowIt's even easier
sum by (group) (my_metric)
Yes, you can you use label replace to group all the misc together:
sum by (new_group) (
label_replace(
label_replace(my_metric, "new_group", "$1", "group", ".+"),
"new_group", "misc", "group", "misc group.+"
)
)
The inner label_replace copies all values from group into new_group, the outer overwrites those which match "misc group.+" with "misc", and we then sum by the "new_group" label. The reason for using a new label is the series would no longer be unique if we just overwrote the "group" label, and the sum wouldn't work.
How to use group by in PromQL?
How can I group labels in a Prometheus query?
How do I use the "group by" function with labels in Prometheus queries?
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+)*)-.*"
)
)
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.
There is no need to use two label_replace() functions - a single label_replace() would be enough:
sum by (type_group) (
label_replace(
sample_metric,
"type_group", "$1", "type", "some-(\\w+(-\\w+)*)-.*"
)
)
It matches the type label with the given regexp - some-(\w+(-\w+)*)-.* - and then puts the matched outer group into type_group label. Then sum by (type_group) (...) sums results grouped by the constructed type_group label.