Grafana: Allow custom mapping of template variable value -> display text

Created on 7 Nov 2014  ·  145Comments  ·  Source: grafana/grafana

Use Case: You may store metrics based on an 'ID' property but wish to have the template variable selection UI use a more human friendly label. e.g. You track metrics by domain with an internal domain ID but wish to use the domain's URL in the template variable selector UI.

@torkelo I can take a cut at implementing this, what are your thoughts on implementation? For my specific use case I would want to be able to provide an arbitrary JS function to perform the value -> text conversion as I need to hit an external service for the lookup. I was thinking an initial implementation could be adding a config value in the dashboard JSON that defines the mapping function. UI support could be added later to handle more trivial mappings with pre built mapping functions (e.g. regex substitutions).

Also connected to this would be the ability to edit the full dashboard JSON via the UI, although export -> edit -> import would function as a workaround if this proves to be difficult.

aredashboard aredashboartemplating typfeature-request

Most helpful comment

Implementing the workaround from @thinrope properly would be a really elegant fix imho.
If we could use JSON in a custom variable, or have a variable type "JSON", we could solve this without hacks and I don't see any drawbacks.

All 145 comments

You could do this with scripted dashboards. But you are welcomed to try to implement it into regular/saved json dashboards.

+1

I too could use at least a simpler version of this. Something like a configured mapping from A -> B

In my scenario I want to select an entity name in the variable dropdown (CustomerName1, CustomerName2, etc.) but use a numeric id internally when it comes to the metric name.
app.requests.$customer1_ID.count

+1

Merging from #3138

E.g. when creating a custom template variable with values fooBar and baz_quuxInternal, to be able to have the UI display the checkboxes as "Foo bar" and "Baz".

This is especially common when using repeated rows and a custom variable to reduce duplication, but the top level metrics may not be user-friendly.

One could potentially support this for queried template values (e.g. graphite properties) as well by using a regex (if the replacement is generic). Regex support already exists, but it applies to both the value used and the label. Having it used for the value only would be valuable.

For example, if a graphite query expands kafka.messagesByTopic.myservice_* for use in templates, then one may want the user interface to strip the prefix. But when used in the actual panels, the prefix should be included. This can be worked around (in Grafana 2.x and later) now that template variables can be embedded in a metric property, so one could hardcode the prefix in all metrics in all panels and rows, but that's better to avoid.

Once these "label" values exist, it would be useful to be able to access them inside the panels as well. Such when embedding a variable in a Row and/or Panel title. Either we can make it use the label by default (if embedded in a title field), or perhaps with some alternate syntax (e.g. $$Variable, or some whatever)

http://play.grafana.org/dashboard/db/test?editview=templating shows "Variable Label" as an option. Can this be closed?

EDIT: I misunderstood the bug, sorry! :) Carry on.

that is just an option to have a friendly name for the variable, not the variable values

+1

+1

+1

+1

+1

+1

What's the status of this ?
Is it possible to do so ?

Is this possible for the 3.0 final ?
It looks like a feature many people are waiting for. Including me :-)

+1
I normally use part of regular expressions which looks awful for users.

+1

+1

+1
Without this, regex expressions are unusable in template variables.

+1

+1

+1

+1

+1

+1

@mbell697 @torkelo

I've implemented this for an internal service that uses Grafana. As we use uuids for hosts (so a change in hostname does not lose metrics history and a number of other things), it was unacceptable to show those uuids to the user. I did a specific patch for our use case where we detect uuid values and translate them using an http endpoint of our application. That is working well for us but I'd prefer doing something that is generic and accepted upstream.

Would it be acceptable to add a 'variable_translation_url' option that points to a url that can perform the mapping? (with an optional authorization token if needed) or a variable_translation_script that points to javascript src that can be downloaded and hook into templateValuesSrv.js at the points where translation is required (if that option is set) ?

Can you share you templateValuesSrv.js code? I want try it.

@ZhuWanShan This is basically it:

https://github.com/sangoma/grafana/commit/fa109c23bc92c3121173579afbd87a04d7e2f523

Note you'll see 2 approaches there. The first was meant to be more general, introducing a new template variable type 'http', with a 'query' property that points to an HTTP url to perform the mapping (see _getHttpVariableOptions). Later I implemented a second method that detects if an option text (display value) matches a UUID regex, and forces mapping of whatever variable is that using a hard-coded HTTP call to /api/v1/nodes/grafana-hosts/ that returns the mapping of all the options. That has worked well so far, just need to have direction as of how to convert this into a generic method.

+1

+1

For anyone who is interested I was able to solve my particular use case by using the Simple JSON Datasource plugin.

That said the plugin didn't presently support template variable queries but my pull request that fixes the issue has been merged into master. An updated Grafana.net release of the plugin should follow at some point.

With it you can use custom HTTP endpoints as data sources in Grafana. They just have to implement 4 methods. When used with query-based template variables the HTTP endpoint will receive a /search API request and the body will be a JSON object in the form: { "target": "{template query content here}" }. You can parse the query content however you'd like.

Returning an array of values from your endpoint will create an underlying list of template variable values ["custom value 1", "custom value 2"] in the form of: [{ "text": "custom value 1", value: 0 }] where the text property is the returned value per array item and the value property is the index of the variable in the return array.

Alternatively you can return an array of text/value objects [{ "text": "label", "value": 123 }] and Grafana will use the text property as a the template variable's label, and the value property as the raw value of the template variable.

It is possible to dynamically inject other template variables into the query in regex form and send them into the endpoint dynamically for processing.

This won't solve all aliasing scenarios, but having an arbitrary HTTP data source that can be used for template variables, including dynamically injecting other template variables into the template query is a nice tool to have.

I am human.

+1

+1

+1

+1

+1

+1

+1000

+1

+2

Would be immensely useful to have this. In effect, I have a bunch of objects that have both a name and a uuid. I'd like to display the name, but store the uuid in the variable.

It would be great if we could do something like have:

Query (existing): SHOW TAG VALUES FROM "vcd_vm" WITH KEY = "uuid" where "OrgVdc" =~ /^$vDC$/)

Label (new): SHOW TAG VALUES FROM "vcd_vm" WITH KEY = "name" where "uuid" =~ /^$tag$/)

+1

+1

+1

+1

+1

+1

+1

Would be great if the 'Custom' template variable took as input both a list of 'values' and a list of 'labels' (essentially, a custom hash/dict)

+1

+1

This would be useful for AWS CloudFront data, as exported by the official cloudwatch exporter. Data for CloudFront is displayed by IDs, which no human uses. Much easier for humans looking at graphs to see "foo.example.com; bar.example.com" instead of "EAUUWLGUQEPFWV; EVWWU9PGWIB"...

+1

First off, thank you for developing an awesome product and sharing it with the world!

Any indication on what the likelihood is of this being implemented in the coming months? I'm just trying to weigh up to what extent it makes sense to go ahead and implement @meverett's suggested workaround or wait for this.

Implementing this via an HTTP endpoint is a neat solution to a highly generalized version of this problem, but seems like overkill for many of the use cases described here (including mine) where all that's needed is basic static mapping on a modest number of "friendly display name" -> "not friendly database name" pairs.

@svet-b fwiw, we moved to use @meverett's suggestion and it was painless and clean. Just a few hours to build the datasource plugin.

+1

+1

+1

+1

+1

+1

+1

+1

+1

+1

+1

@meverett's workaround works pretty good, but falls short when used with multi value variables because the series can only be labeled with tags from (in my case) influxdb. Any suggestions for workarounds there? :)

+1

+1

+1

+1

+1

Hey all, since this issue gets bumped pretty regularly I decided to throw together an example Node.js web application that uses my solution above.

It's pretty basic, but it fully implements the pattern I mention in my original comment. And if you can get by with putting your look-up data into a single JSON file that wouldn't get updated very often, it might just work out-of-box for you.

Otherwise you can use it as a starting point and extend it to access your aliasing data from whatever source you'd like (programmed by you of course) and serve it up through the app in such a way that the SimpleJson datasource plugin can consume it and it can be used to drive template variable aliasing/mapping.

The repository for the example web app is here.

Hope it helps. I've had some requests from time to time asking for more help/explanation setting up the solution.

Cheers

+1

+1

Thanks for your makeshift solution, @meverett . I've made a repository with Dockerfile for creating a Docker container to run your solution. It is set up to take a custom data.json from alongside the Dockerfile upon build. Hope it helps people:

https://github.com/shirakaba/GrafanaSimpleJsonValueMapper-docker

+1

+1

+1

When you want to +1 this, please keep in mind you will annoy the 74 people that are currently subscribed to this issue and are hoping for someone to step forward and implement a fix.
GitHub added reactions for a reason...

+1

+1

+1

this would be great! a have a list of long numeric values but should be much better to show a label human friendly for each one than the value itself
variable: myListOfLongs {name: toyota value: 122321312332, name: renault value: 6666666}

+1!

+1

+1
Any updates about #11534 (Allow dynamic titles when using repeated panels/rows)

+1

+111111

+1

+1

+1, Very much in need of this feature.

+1

+1

+1

+1

+1

This works for MySql and PostgreSQL:

Another option is a query that can create a key/value variable. The query should return two columns that are named __text and __value. The __text column value should be unique (if it is not unique then the first value is used). The options in the dropdown will have a text and value that allows you to have a friendly name as text and an id as the value. An example query with hostname as the text and id as the value:

SELECT hostname AS __text, id AS __value FROM my_host

http://docs.grafana.org/features/datasources/mysql/#query-variable

I would suggest custom variable to be:

[{
        "__text": "Server 1",
        "__value": 1
    },
    {
        "__text": "Server 2",
        "__value": 2
    }
]

Maybe new type called JSON?

Thanks @johnymachine! That worked beautifully with the PostgreSQL datasource.

As an extension of this, is there any way to retrieve the __text section of the variable? This would be really useful for repeating graphs.

Hey @MGinshe, this works fine (displays text uses value) for me:

image

EDIT: misunderstood the initial context of this bug, ignore the comment below, it was more meant for #9292

@torkelo @nmaniwa

https://github.com/grafana/grafana/pull/12609 seems to implement what most people are asking for here, any reason why that is closed and never got merged?

No, that issue is about something totally different, or did you link to wrong issue?

Still no news about this? Come on, we are in 2018 !! Thanks!

@dmayan it was answered by @johnymachine . You can use this.

This works for MySql and PostgreSQL:

Another option is a query that can create a key/value variable. The query should return two columns that are named __text and __value. The __text column value should be unique (if it is not unique then the first value is used). The options in the dropdown will have a text and value that allows you to have a friendly name as text and an id as the value. An example query with hostname as the text and id as the value:

SELECT hostname AS __text, id AS __value FROM my_host

http://docs.grafana.org/features/datasources/mysql/#query-variable

I would suggest custom variable to be:

[{
      "__text": "Server 1",
      "__value": 1
  },
  {
      "__text": "Server 2",
      "__value": 2
  }
]

Maybe new type called JSON?

I don't use MySQL nor PostgreSQL. This should be a Grafana feature. Not
some sort of hack.

Thanks!

El jue., 27 de sep. de 2018 05:52, Muhammad Hendri notifications@github.com
escribió:

@dmayan https://github.com/dmayan it was answered. You can use this.

This works for MySql and PostgreSQL:

Another option is a query that can create a key/value variable. The query
should return two columns that are named __text and __value. The __text
column value should be unique (if it is not unique then the first value is
used). The options in the dropdown will have a text and value that allows
you to have a friendly name as text and an id as the value. An example
query with hostname as the text and id as the value:

SELECT hostname AS __text, id AS __value FROM my_host

http://docs.grafana.org/features/datasources/mysql/#query-variable

I would suggest custom variable to be:

[{
"__text": "Server 1",
"__value": 1
},
{
"__text": "Server 2",
"__value": 2
}
]

Maybe new type called JSON?


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/grafana/grafana/issues/1032#issuecomment-425011676,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AWcYqEwxjXiXE07uM0ZG-A284TghEIR2ks5ufJG4gaJpZM4C4cjS
.

pretty useful feature, If this feature is out there, It could help us a lot here. Because graphite can not store Chinese character. So we have to use English in Graphite, but we would really like to show the Chinese in the grafana dashboard, so the user experience would be much better.

Hope this feature will come true shortly.

I managed to do the ID->name mapping by using two variables. The first variable lists all possible IDs (value) while the second variable lists the name (display text) that matches the ID. It's not the ideal or pretty, but it does the trick.

I reckon it's called nested variables. And then you can hide one of the variable selectors.

+1

+1

@FdeFabricio You used InfluxDB? Does it automatically update one value when changing the other? If so, how do you do that?

@bassie1995

You used InfluxDB?

Yes

Does it automatically update one value when changing the other?

Yes

If so, how do you do that?

You create a query type variable that selects the item that matches the already selected value (e.g. SELECT "name" FROM playlists WHERE ("id" =~ /^$playlist_id$/). So now you will have two variables: one with the ID and other with the name.

@bassie1995 @FdeFabricio You could also do this in reverse:

  • A visible variable, which lets you select the playlist name (i.e. Girl Power)
  • A hidden variable, which finds the playlist ID from the name (something like SELECT "id" FROM playlists WHERE ("name" =~ /^$playlist_name$/))

This way, your users see an option to select the playlist by its name, but the playlist ID is hidden. You can still access the playlist ID programatically, in order to search for playlist items, etc.

The __name and __value syntax from the PostgreSQL/MySQL datasource is still ideal though, as it prevents any id->name ambiguity, and reduces the number of database queries required. It should be a base feature IMO.

I found another workaround based off @johnymachine 's comment above. There is support for this in some data sources. If it's not supported in your data source you can create a MySQL database, add the data there and write a query to return __value and __text. This works if the data is static, in my case state (geographic state). For anyone who wants this feature for variables defined as custom then I think this is a good workaround and possibly a better solution anyway. It allows all variable lists to be stored in 1 location and changed more easily. Only downside is it requires installing MySQL.

SELECT SingleChar AS __value, ShortName AS __text FROM TSDB.State

I should add this solution works for repeated graphs, repeated rows and also if the variable has multi-select. The example above using 2 variable to show "Girl Power" doesn't work in these situations.

I was just fiddling with that issue and found a somewhat hackinsh workaround...
I needed a hash, that in Perl notation is written as:
Perl %units = ( 'μSv/h' => 1.0, 'mrem/h' => 0.1 );
I created a dashboard variable Type:Custom, Values separated by comma:mrem/h, μSv/h and then edited the JSON Model like that:
JSON { "allValue": null, "current": { "tags": [], "text": "mrem/h", "value": "0.1" }, "hide": 0, "includeAll": false, "label": null, "multi": false, "name": "units", "options": [ { "selected": true, "text": "mrem/h", "value": "0.1" }, { "selected": false, "text": "μSv/h", "value": "1.0" } ], "query": "mrem/h, μSv/h", "skipUrlSync": false, "type": "custom" }

While this does work (for some time), editing the dashboard via the GUI changes it back to non-working state :-|

Another option for working around this if you have another system that can provide the data:

Use a JSON datasource plugin, I'm using: https://grafana.com/plugins/simpod-json-datasource

Implement only the / health-check endpoint and the /search endpoint in some system that has the needed data. The /search endpoint should return JSON that looks like: [{ "text": "A Human Name", "value": "123456" }, ...]. The text property will be what appears in the variable select drop down and the value will be what is used in the metrics query.

Then setup your dashboard variable to query against this new datasource, it's kinda hacky but you can use the target field for the datasource to tell the backend what it should return if you have multiple datasets you want to use this with.

+1 on this. I would really like a way to do this, but one that was not backend-dependent (we use graphite).

+1 any working solution ?

@BlackRider97 Please have a look through the comments above - there are several working solutions for PostgreSQL (and probably MySQL, MSSQL, etc).

Solution 1: https://github.com/grafana/grafana/issues/1032#issuecomment-409124505

Solution 2: https://github.com/grafana/grafana/issues/1032#issuecomment-453242766

Implementing the workaround from @thinrope properly would be a really elegant fix imho.
If we could use JSON in a custom variable, or have a variable type "JSON", we could solve this without hacks and I don't see any drawbacks.

+1 any update on this?

+1

+1

This is definitly a must have feature.
I use variables to filter some hosts using regex on hostname. As my servers cotains patterns in hostname, I can have a regex to get the list of all servers of a given group. Instead of showing a ugly regexp, I would like to display a pretty name, like "Servers of group A" as label of the dropdown menu.

The way to enter this in custom value could be as simple as:
label1:value1, value2, label3:value3, label5:value5

The label would be optional. If a : is present in string, then everything before : is the label and everything after is the value.
We should have a way to escape : if we need it in label name or value, as we can do for , character.

Another option for working around this if you have another system that can provide the data:

Use a JSON datasource plugin, I'm using: https://grafana.com/plugins/simpod-json-datasource

Implement only the / health-check endpoint and the /search endpoint in some system that has the needed data. The /search endpoint should return JSON that looks like: [{ "text": "A Human Name", "value": "123456" }, ...]. The text property will be what appears in the variable select drop down and the value will be what is used in the metrics query.

Then setup your dashboard variable to query against this new datasource, it's kinda hacky but you can use the target field for the datasource to tell the backend what it should return if you have multiple datasets you want to use this with.

I did this implementation and it works for me, but I'm stucked at the labeling the trend (legend)... I get either id (number) or not defined or some other non-sense.
Can you advise?

M

+1

I am also using now the described JSON-hack by @mbell697 in my company's Grafana. But there seems a strange regex problem IMHO.

I set up a small python flask app which is providing me the needed groups for Graphite queries my search data looks like

@app.route('/search', methods=['POST'])
def search():
    data = [
        {"text": "fs-servers", "value": "{FS-server-1,FS-server-2,FS-server-3}"},
        {"text": "db-a-servers", "value": "{db-server-1,}"},
        {"text": "db-b-servers", "value": "{db-server-2,db-server-3}"}
    ]
    return jsonify(data)

So in the dashboard I created a query variable called "group" using the json-source and then tried to filter for the "fs-servers" group with the regex-field by using /fs-.*/ - but this is not working as expected - after fiddling around I recognized that the regex is somehow applied to the "value"- and not to the "text"-field. Has anybody maybe some workaround or an idea?

+1

+1

My take on the requirements for this:

In our case I think of two variants of the same thing. What we would want is essentially alias'es. In both cases, the dashboard owner wants to provide the user with a template variable list that is easy for the end-user to understand. However the value used in the query is the underlying value.

Example 1 - simple one to one name conversions. So in this case we have numeric country codes published as metric values. But know one memorizes the numeric codes. So we want to display "US" or "Canada"

{ "US" == "01" }
{ "Canada" == "02" }

If "Canada" is selected the template variable value passed to any query is "02"

Example 2 - is a one to many mapping. Internally we have stages for deployment, e.g. s0, s1, s2, s3, s4. However end-users may use this as "dev, beta, prod"
So they want to map them as:

{ "dev" == ["s1"] }
{ "beta" == ["s2", "s3"] }
{ "prod" == ["s4", "s5", "s6"] } or better yet "prod" == s[456]

So if "prod" is selected "s4,s5,s6" is passed to the query

From a query perspective (taking Example 2) where the variable name is stageVar
and the metric tag name is stage:

We don't see so much the need for aliasBy() like calls but more things like:
stage=~${stageVar.value:regex}
alias($stageVar.label)

To filter results by the selected template variable values. It is certainly possible that someone might try and use it in something like an aliasBy() function but if it is a syntax error that is fine. I wouldn't expect you to magically fix a conversion of an array passed to a function that expects a single value.

As for the mappings I think having the user statically define those is sufficient.
Ideally you would have a query to MT to get the list of values that need to be mapped, for you, e.g. "01", "02", "03" and then you would have an easy to add the mappings / aliases. Unmapped values would go into a "default" bucket.

+1

+1

I'm very surprised this hasn't been included - I spent quite a bit of time trying to figure out how do this "obvious" thing and eventually found my way here to discover it doesn't exist.

The ability to dynamically re-write as described by some above would be fantastic. However, I'd even be happy with a short-term hack (or permanent "easy" model) that is an extended version of the "Custom" field, that statically mapped choices to single or multiple choice results.

Our example is country codes. We often wish to view clusters of systems based on geographic regions, but not by country. But we only store country codes as keys in our Prometheus server. So right now, if I want to view all systems in North America, I have to select US, CA, MX manually from a Query-based list of options out of nearly 100 countries. I can't even tell you how much time I spend selecting every country in Europe, or Asia, or Africa to do analysis. It's almost worth setting up entirely different dashboards for each region, which is absurd but is the only way to solve the problem short of hard-coding graphs. Making an entirely new database with mappings and then doing hidden queries seems also to be very, very far from ideal.

My fever dream:
It would seem that this would be a "Custom List" option as a possible new type of Variable. The Custom List would start empty if selected, but would look very much like the "Custom" model looks today. An "Add" button would appear. Clicking "Add" would create a two-field input array with "Display Value:" and "Search Value:" where each could be filled in. The "Display Value" would be whatever the user wanted to show in the picklist - in our case, "North America". Then the "Search Value" would be what would be presented in the query - again, in this example for North America it would be "us,ca,mx". At any time, a "delete" icon (trash can?) would remote individual lines. Clicking the "Add" button again would create a new pairing, until the user had completed their list of options. The "Multi-Value" and "Select all" options would remain, similar to the existing Custom model.

I'm very surprised this hasn't been included - I spent quite a bit of time trying to figure out how do this "obvious" thing and eventually found my way here to discover it doesn't exist.

I have solved this by creating a MySQL database, I create a table with the items I want in the dropdown, eg Europe, North America etc. In a second field I have a regex that will match the entries I want to match. Then add the MySQL as a datasource and use them to create the variables. It is a hack but actually works quite well. I use it for pretty much the exact thing you are trying to do.

I appreciate the clever hack, but for us it's not really a solution. Setting up an entirely new database (we don't use MySQL at all, which means operationally this is impossible) to perform a simple key/value substitution that is quite static seems like a lot of hoops to jump through.

I was thinking about this a bit more, and there is an even more elegant way of providing this functionality than what I describe above. I'd call it a "variable macro". This again looks like a Custom list, except it allows the administrator to specify that when one (or more) of these macros are selected, then the Variables named will be set, and the Values given will be appended to the existing set of values. This would entirely be a UI-driven model, and would not change the actual variable concept at all - it would just create an auto-completion sugar layer on top of the existing variables. This makes it backwards-compatible with no additional variables needed for creation or integration into queries.

A macro that sets the variables would allow the user to see the values as they're being selected, and then would allow the user to open up each variable and see/manipulate the selections or data instead of creating a separate variable as my previous comments imply. This would be much more intuitive.

Example:

So a variable macro called "North America - Primary Cluster" would set my "Country" variables to "us,ca,mx" and would set my "Cluster:" variable to "primary". Those settings would be visible if I were to pull down each named variable (or not, if they're hidden) so I could add or subtract countries to the Country: list as long as I didn't touch the Macro variable pulldown again.

Possibly there is a boolean of "clear named variables before setting" so that if a change is made in the picklist for this Macro, then any other settings of the variables specified would be cleared. This could be useful for lists where it's not obvious that you might include something that was previously set. I suppose that if more than one Variable Macro option were chosen, then the last one in the list to be examined "wins" if there are competing settings of a particular value; no way around that problem. (it's arguable that this clearing action should be specified on a variable-by-variable basis, but that seems to sound a little cluttered... but is it?)

Here's my hypothetical example again, where I have pre-existing variables of "Country" and "Cluster".

Variable Macro Name: Region

Name1: North America - Primary Cluster
Clear Named variables before setting: Y
Variable1: Country
Value1: us,ca,mx
Variable2: Cluster
Value2: primary

Name2: Nordics - Secondary Cluster
Clear Named variables before setting: Y
Variable1: Country
Value1: se,fi,no,dk,is
Variable2: Cluster
Value2: secondary

I appreciate the clever hack, but for us it's not really a solution. Setting up an entirely new database (we don't use MySQL at all, which means operationally this is impossible) to perform a simple key/value substitution that is quite static seems like a lot of hoops to jump through.

I was expecting you would say something like this. The reality is you asked for a hack and this hack does solve the problem, it's not difficult to setup and it's not difficult to reverse in the future. I actually find it quite handy having the MySQL there as we keep adding new data sets to it, it's a convenient place to keep track and update them. If you think about it, if you're going to use these data sets in multiple dashboards and want to have them maintained centrally, then they need to be stored somewhere. If your time series database can't store them then you need something setup to store them. So it actually makes perfect sense to have MySQL. The added bonus is its also very easy to automate the population of MySQL.

If you have PostgreSQL, you don't need to create an actual table for the mapping, you can do something like:

SELECT *
FROM
(
    VALUES
        ('London server 1', 'london_srv_1'),
        ('London server 2', 'london_srv_2'),
        ('New York server 1', 'ny_srv_1'),
        ('New York server 2', 'ny_srv_2')
) AS t (__text, __value)

But it doesn't work with numeric values:

SELECT * FROM ( VALUES ( 'OK', '0'), ( 'ERROR', '1') ) AS t (__text, __value)

When loading dashboard:

imagen

And when selecting another parameter

imagen

When selecting: OK + ERROR

imagen

If you want numeric values you need to remove the single quotes, otherwise it is interpreted as text, ie

SELECT * FROM ( VALUES ( 'OK', 0), ( 'ERROR', 1) ) AS t (__text, __value)

Thanks @GlennMatthys glenn for the answer, but i already found where the problem occurs.

SELECT * FROM ( VALUES ( 'OK', 0), ( 'Warning', 1), ('Critical', 2) ) AS t (__text, __value)

Configuring Multi-value on:

imagen

It happens
imagen

Selecting 3 states
imagen

And Multi-value off:

imagen

GlennMatthys - your solution is perfect, many thanks

For MySQL its:
SELECT * FROM ( VALUES row('a', 1), row('b', 2) ) AS t (__text, __value)

What about Mariadb? It is not working for me (mariaDB version: 10.5.5)

SELECT * FROM ( VALUES row('a', 1), row('b', 2) ) AS t (__text, __value);
ERROR 1064 (42000)..............

Or the one before:

SELECT * FROM ( VALUES ( 'OK', 0), ( 'Warning', 1), ('Critical', 2) ) AS t (__text, __value);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your 
MariaDB server version for the right syntax to use near '(__text, __value)' at line 1

It looks like the Values statement is no longer available...

Or is there something else that I do wrong?

@radoeka For older MariaDB/MySQL

SELECT * FROM
(
    SELECT 'London server 1' AS '__text', 'london_srv_1' AS '__value'
    UNION ALL SELECT 'London server 2', 'london_srv_2'
    UNION ALL SELECT 'New York server 1', 'ny_srv_1'
    UNION ALL SELECT 'New York server 2', 'ny_srv_2'
) AS t;

@GlennMatthys wow wow wow, what a swift response! And this works.
I thought that I was running a rather new version of mariadb, but that is not case (using a linux distribution that is only 2 months old).
Thanks.

This seems to not be supported for Prometheus.

Reopening this issue as #27829 only solves this for static data.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

torkelo picture torkelo  ·  83Comments

matthgyver picture matthgyver  ·  90Comments

marshell08 picture marshell08  ·  115Comments

torkelo picture torkelo  ·  168Comments

costimuraru picture costimuraru  ·  162Comments