After much research I have managed to develop this trick to be able to invoke a library panel (for example, table type), where the query uses one or more variables as filters in an optional way.
In this way I can use the same library panel from several dashboards in which I can use a filter for a tag (or several) without having to change the query.
So for example if I have 5 tags that I can search, I can generate a query that can use 1 to 5 variables each filtering by a different tag, so that in a dashboard I can have only 2 of the 5 possible filters defined, or all, or none (and show all the data).
The query would be like this (modify to suit needs):
SELECT β¦
FROM βmeasurementβ
WHERE $timeFilter
AND (β${var1:raw}β =~ /^${var1:raw}$/ OR βtag1β =~ /^${var1}$/)
AND (β${var2:raw}β =~ /^${var2:raw}$/ OR βtag2β =~ /^${var2}$/)
AND (β${var3:raw}β =~ /^${var3:raw}$/ OR βtag3β =~ /^${var3}$/)
AND (β${var4:raw}β =~ /^${var4:raw}$/ OR βtag4β =~ /^${var4}$/)
AND (β${var5:raw}β =~ /^${var5:raw}$/ OR βtag5β =~ /^${var5}$/)
GROUP BY β¦
The operation is as follows. If any of the variables (var1 for example) does not exist, grafana will NOT replace β${var1:raw}β with its respective value, performing a comparison with a regex that contains THAT unmodified string.
Otherwise, it enters the OR condition in which the tag is already evaluated with the value or values ββof said variable.
Same approach on PostgreSQL queryβ¦
WHEREβ¦
AND (
β${var1:raw}β ~ β${var1:raw}β β If variable is not defined, this whill be TRUE
OR field = ANY(string_to_array(β${var1:raw}β, β,β))
)
After more tests and found mistakes on query I finally found that this query works when:
- There is no variables defined (one or more).
- There is one or more variables that have no values.
- There is one or more variables that have values (and may apply this for filter series)
SELECT β¦
FROM βmeasurementβ
WHERE $timeFilter
AND (β${var1:percentencode}β =~ /${.}/ OR β${var1:percentencode}β = ββ OR β${var1:percentencode}β = βAllβ OR βtag1β =~ /^${var1:regex}$/)
AND (β${var2:percentencode}β =~ /${.}/ OR β${var2:percentencode}β = ββ OR β${var1:percentencode}β = βAllβ OR βtag1β =~ /^${var2:regex}$/)
AND (β${var3:percentencode}β =~ /${.}/ OR β${var3:percentencode}β = ββ OR β${var3:percentencode}β = βAllβ OR βtag1β =~ /^${var3:regex}$/)
AND (β${var4:percentencode}β =~ /${.}/ OR β${var4:percentencode}β = ββ OR β${var4:percentencode}β = βAllβ OR βtag1β =~ /^${var4:regex}$/)
AND (β${var5:percentencode}β =~ /${.*}/ OR β${var5:percentencode}β = ββ OR β${var5:percentencode}β = βAllβ OR βtag1β =~ /^${var5:regex}$/)
Detected a mistake:
final filter should be:
AND (β${var1:percentencode}β =~ /${var1:percentencode}$/ OR β${var1:percentencode}β = ββ OR β${var1:percentencode}β = βAllβ OR βtag1β =~ /(?i)^${var1:regex}$/)
AND (β${var2:percentencode}β =~ /${var2:percentencode}$/ OR β${var2:percentencode}β = ββ OR β${var2:percentencode}β = βAllβ OR βtag2β =~ /(?i)^${var2:regex}$/)
β¦