Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append string to variable in a grafana query?

In Grafana I have a drop down for variable $topic with values "topic_A" "topic_B"

"topic_A" is selected so $topic = "topic_A"

I want to query prometheus using

function{topic=$topic}

and that works fine.

How would I implement

function{topic="$topic" + "_ERROR"}

(this fails) where what I want to query would be "topic_A_ERROR" if "topic_A" is selected.

How do I combine variable $topic and string "_ERROR" in the query?

like image 994
wizardzz Avatar asked Jan 17 '20 18:01

wizardzz


People also ask

How do I use variables in Grafana Query?

To create a new variable, go to your Grafana dashboard settings, navigate to the 'Variable' option in the side-menu, and then click the 'Add variable' button. In this case, we use the 'Query' type, where your variable is defined as the results of SQL query.

How do I set variables in Grafana?

To create a new variable, go to your Grafana dashboard settings, navigate to the Variable option in the side-menu, and then click the Add variable button. In this case, we use the Query type, where our variable will be defined as the result of an SQL query.

How do you add a Query variable?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.


1 Answers

UPDATE 2020-08-17:

There is a new syntax for Grafana variables, new format is to use curly braces after dollar sign:

function{topic=~"${topic}_ERROR"}

Double brackets syntax is deprecated and will be deleted soon.

Also now you can define the format of the variable, which may help to solve some spacial characters issues. Example: ${topic:raw}

Docs: https://grafana.com/docs/grafana/latest/variables/syntax/


If you want to include text in the middle you need to use a different syntax:

function{topic=~"[[topic]]_ERROR"}

Note not only the double brackets but also the change from = to =~. It is documented on the link at the end of my comment, basically it says:

When the Multi-value or Include all value options are enabled, Grafana converts the labels from plain text to a regex compatible string. Which means you have to use =~ instead of =.

You can check the official explanation here: https://grafana.com/docs/grafana/latest/features/datasources/prometheus/#using-variables-in-queries

like image 55
Alberto Martin Avatar answered Oct 07 '22 02:10

Alberto Martin