Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fkurz/426b698975a4ed24ae5908676fa17919 to your computer and use it in GitHub Desktop.
Save fkurz/426b698975a4ed24ae5908676fa17919 to your computer and use it in GitHub Desktop.
Snippet: Creating instant vectors with arbitrary labels in PromQL

Creating Instant Vectors with Arbitrary Labels in PromQl

Problem

We need to create an instant vector with a given label set.

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

Solution

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment