34

I'm using Grafana with Prometheus and I'd like to build a query that depends on the selected period of time selected in the upper right corner of the screen.

Is there any variable (or something like that) to use in the query field?

In other words, If I select 24hs I'd like to use that data in the query.

Facundo Chambo
  • 3,088
  • 6
  • 20
  • 25

3 Answers3

49

There are two ways that I know:

  1. You can use the $__interval variable like this:

    increase(http_requests_total[$__interval])
    

There is a drawback that the $__interval variable's value is adjusted by resolution of the graph, but this may also be helpful in some situations.

  1. This approach should fit your case better:

Go to Dashboard's Templating settings, create new variable with the type of Interval. Enable "Auto Option", adjust "Step count" to be equal 1. Then ensure that the "auto" is selected in corresponding drop-down list at the top of the dashboard.

Let's assume you name it timeRange, then the query will look like this:

increase(http_requests_total[$timeRange])

This variable will not be adjusted by graph resolution and if you select "Last 10 hours" its value will be 10h.

Yoory N.
  • 4,881
  • 4
  • 23
  • 28
  • the 1st option does not work when querying in the Grafana tile (I wanted to create a pie chart). the 2nd option shows me 1s for 1m, 1h, 1d chosen time ranges. How to see the values in right values? – Arseniy Sleptsov Jul 24 '23 at 16:03
19

If you are looking at using prometheus as data source, $__range supports your dashboard time is great.

 increase(gin_total_requests[$__range])

Why create your variable when you can use inbuilt Global variable.

I have added links to documentations to back up my answer Grafana 5.3+

Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
Adedapo Ajuwon
  • 323
  • 2
  • 6
  • 3
    This is the answer to the question and should be on top, even if the answer actually on top works and provides an interesting approach. – jmary Mar 25 '21 at 16:24
  • Do you know why I am not working `increase` when I do a 24h range through the picker time range? The data exists because if I remove `increase ` and `$__range `, it shows me data. – jcarlosweb May 15 '21 at 22:34
1

count_over_time({job="gerrit-sshd"}[$__interval])

It works for me and what's more, you should set Max data point as 1 ,in query option.

Then the $__interval is the same Time-Range from the Panel on Grafana top right corner.

B.Kingsun
  • 350
  • 3
  • 11