Field Note

Creating Arbitrary Vector Labels in PromQL

promql prometheus vector-label
Posted on Sunday, June the 02, 2019
1 min read

A relatively unknown feature of PromQL is that we can create arbitrary vector labels. This can be useful if we need to for example provide a default value for a time series with given labels.

An example use case would be supplying a default value in combination with or.

Using label_replace to create arbitrary labels

PromQL’s label_replace function can be used to create arbitrary labels by using the empty string as the target label. Combining this with the use of vector to create an instance vector for a given scalar let’s us create an instance vector with an arbitrary label set by

label_replace(
  ...label_replace(vector(<s>), "<name-1>", "<value-1>", "", "")...,
  "<name-n>", "<value-n>", "", ""
)

where <s> is the scalar value for the initial vector as well as <name-i> and <value-i> are placeholders for the target label names and values to create.

Note: The values <value-i> can use variables.

Example

The following expression

label_replace(label_replace(vector(1), "pod_name", "$pod", "", ""), "namespace", "$namespace", "", "")

will create an instant vector with scalar value 1 and pod name $pod as well as namespace $namespace.

friedrichkurz.me

© 2025 Friedrich Kurz

Privacy Policy