Manish Purohit
Manish Purohit

Reputation: 11

Sort in promql such that all metrics with one lebel appear first in result

I want to perform this promql Instant query

{__name__=~"cpu_usage_value|memory_usage_value|request_rate"}

I want the result in such a way that all metrics with {__name__="cpu_usage_value"} appear first in result and in sorted order.

Upvotes: 0

Views: 3686

Answers (3)

Ashish Singh
Ashish Singh

Reputation: 1

sort({__name__=~"foo.*|bar.*|baz.*"})

Upvotes: 0

valyala
valyala

Reputation: 18010

Try using sort_by_label function from VictoriaMetrics (I'm the author of this Prometheus-like system) in the following way:

sort_by_label({__name__=~"foo|bar|baz"}, "__name__")

It should sort the returned time series by their metric names.

If you need to sort time series with idenrical metric names by their value, then try the following MetricsQL query:

sort_by_label(
  sort({__name__=~"foo|bar|baz"}),
  "__name__"
)

It uses an additional function - sort - for sorting time series by values, before sorting time series by metric names.

Upvotes: 2

You can use the operator "or" to join the PromQLs, like the following:

{__name__=~"cpu_usage_value} or {__name__=~"memory_usage_value"}

This will join the two metrics listing the "cpu_usage_value" elements first and then the "memory_usage_vale" ones.

But...

As shown in the "or" operator documentation:

vector1 or vector2 results in a vector that contains all original elements (label sets + values) of vector1 and additionally all elements of vector2 which do not have matching label sets in vector1

Prometheus will list only the elements of the "memory_usage_value" metric which do not have matching label sets in the "cpu_usage_value" one.

To workaround this, add an extra label to the "memory_usage_value" metric, using the "label_replace" function, like the following:

{__name__=~"cpu_usage_value} or label_replace({__name__=~"memory_usage_value"}, "foo", "boo", "", "")

Upvotes: 0

Related Questions