mirror of
https://github.com/grafana/grafana.git
synced 2025-07-31 04:12:19 +08:00
Docs: Overhaul of PostgreSQL data source documenation (#99908)
* created new topic docs * added info to config doc * updates to config doc * updates to config doc * finished config doc * updated Query editor doc * final edits * rename, ref URI work * a few more updates prior to PR issue * fixed the double Macros heading issue * final edits and cleanup * edits based on feedback * ran prettier * added updates * updates based on feedback * vale linter issues * more vale linting issues addressed * small addition on main page * ran prettier again * changed title * Update docs/sources/datasources/postgres/query-editor/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/configure/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/configure/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/query-editor/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/configure/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/configure/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/configure/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * changed Grafana's * added changes * Update docs/sources/datasources/postgres/query-editor/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/query-editor/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/query-editor/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/query-editor/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * Update docs/sources/datasources/postgres/query-editor/_index.md Co-authored-by: Jack Baldry <jack.baldry@grafana.com> * ran prettier again * Remove aliases Signed-off-by: Jack Baldry <jack.baldry@grafana.com> * Fix link Signed-off-by: Jack Baldry <jack.baldry@grafana.com> * Put code in `code` Signed-off-by: Jack Baldry <jack.baldry@grafana.com> * Avoid bold for emphasis Signed-off-by: Jack Baldry <jack.baldry@grafana.com> * Fix link Signed-off-by: Jack Baldry <jack.baldry@grafana.com> --------- Signed-off-by: Jack Baldry <jack.baldry@grafana.com> Co-authored-by: Irene Rodríguez <irene.rodriguez@grafana.com> Co-authored-by: Jack Baldry <jack.baldry@grafana.com>
This commit is contained in:
@ -2,7 +2,7 @@
|
||||
aliases:
|
||||
- ../data-sources/postgres/
|
||||
- ../features/datasources/postgres/
|
||||
description: Guide for using PostgreSQL in Grafana
|
||||
description: Introduction to the PostgreSQL data source in Grafana.
|
||||
keywords:
|
||||
- grafana
|
||||
- postgresql
|
||||
@ -16,506 +16,58 @@ menuTitle: PostgreSQL
|
||||
title: PostgreSQL data source
|
||||
weight: 1200
|
||||
refs:
|
||||
provisioning-data-sources:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/administration/provisioning/#datasources
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/administration/provisioning/#datasources
|
||||
variables:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/
|
||||
add-template-variables-interval-ms:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval_ms
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval_ms
|
||||
add-template-variables-interval:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval
|
||||
annotate-visualizations:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/build-dashboards/annotate-visualizations/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/build-dashboards/annotate-visualizations/
|
||||
configure-standard-options-display-name:
|
||||
configure-postgres-data-source:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/panels-visualizations/configure-standard-options/#display-name
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/datasources/postgres/configure/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/panels-visualizations/configure-standard-options/#display-name
|
||||
data-source-management:
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/datasources/postgres/configure/
|
||||
postgres-query-editor:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/administration/data-source-management/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/datasources/postgres/query-editor/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/administration/data-source-management/
|
||||
variable-syntax-advanced-variable-format-options:
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/datasources/postgres/query-editor/
|
||||
alerting:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/variable-syntax/#advanced-variable-format-options
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/alerting/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/variable-syntax/#advanced-variable-format-options
|
||||
destination: /docs/grafana-cloud/alerting-and-irm/alerting/
|
||||
transformations:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/panels-visualizations/query-transform-data/transform-data/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana-cloud/visualizations/panels-visualizations/query-transform-data/transform-data/
|
||||
visualizations:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/panels-visualizations/visualizations/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana-cloud/visualizations/panels-visualizations/visualizations/
|
||||
---
|
||||
|
||||
# PostgreSQL data source
|
||||
|
||||
Grafana ships with a built-in PostgreSQL data source plugin that allows you to query and visualize data from a PostgreSQL compatible database.
|
||||
Grafana includes a built-in PostgreSQL data source plugin, enabling you to query and visualize data from any PostgreSQL-compatible database. You don't need to install a plugin to add the PostgreSQL data source to your Grafana instance.
|
||||
|
||||
For instructions on how to add a data source to Grafana, refer to the [administration documentation](ref:data-source-management).
|
||||
Only users with the organization administrator role can add data sources.
|
||||
Administrators can also [configure the data source via YAML](#provision-the-data-source) with Grafana's provisioning system.
|
||||
Grafana offers several configuration options for this data source as well as a visual and code-based query editor.
|
||||
|
||||
## Get started with the PostgreSQL data source
|
||||
|
||||
The following documents will help you get started with the PostgreSQL data source in Grafana:
|
||||
|
||||
- [Configure the PostgreSQL data source](ref:configure-postgres-data-source)
|
||||
- [PostgreSQL query editor](ref:postgres-query-editor)
|
||||
|
||||
After you have configured the data source you can:
|
||||
|
||||
- Create a variety of [visualizations](ref:visualizations)
|
||||
- Add [annotations](ref:annotate-visualizations)
|
||||
- Set up [alerting](ref:alerting)
|
||||
- Add [transformations](ref:transformations)
|
||||
|
||||
View a PostgreSQL overview on Grafana Play:
|
||||
|
||||
{{< docs/play title="PostgreSQL Overview" url="https://play.grafana.org/d/ddvpgdhiwjvuod/postgresql-overview" >}}
|
||||
|
||||
## PostgreSQL settings
|
||||
|
||||
To configure basic settings for the data source, complete the following steps:
|
||||
|
||||
1. Click **Connections** in the left-side menu.
|
||||
1. Under Your connections, click **Data sources**.
|
||||
1. Enter `PostgreSQL` in the search bar.
|
||||
1. Select **PostgreSQL**.
|
||||
|
||||
The **Settings** tab of the data source is displayed.
|
||||
|
||||
1. Set the data source's basic configuration options:
|
||||
|
||||
| Name | Description |
|
||||
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Name** | The data source name. This is how you refer to the data source in panels and queries. |
|
||||
| **Default** | Default data source means that it will be pre-selected for new panels. |
|
||||
| **Host** | The IP address/hostname and optional port of your PostgreSQL instance. _Do not_ include the database name. The connection string for connecting to Postgres will not be correct and it may cause errors. |
|
||||
| **Database** | Name of your PostgreSQL database. |
|
||||
| **User** | Database user's login/username |
|
||||
| **Password** | Database user's password |
|
||||
| **SSL Mode** | Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server. When SSL Mode is disabled, SSL Method and Auth Details would not be visible. |
|
||||
| **SSL Auth Details Method** | Determines whether the SSL Auth details will be configured as a file path or file content. |
|
||||
| **SSL Auth Details Value** | File path or file content of SSL root certificate, client certificate and client key |
|
||||
| **Max open** | The maximum number of open connections to the database, default `100`. |
|
||||
| **Max idle** | The maximum number of connections in the idle connection pool, default `100`. |
|
||||
| **Auto (max idle)** | If set will set the maximum number of idle connections to the number of maximum open connections. Default is `true`. |
|
||||
| **Max lifetime** | The maximum amount of time in seconds a connection may be reused, default `14400`/4 hours. |
|
||||
| **Version** | Determines which functions are available in the query builder. |
|
||||
| **TimescaleDB** | A time-series database built as a PostgreSQL extension. When enabled, Grafana uses `time_bucket` in the `$__timeGroup` macro to display TimescaleDB specific aggregate functions in the query builder. For more information, see [TimescaleDB documentation](https://docs.timescale.com/timescaledb/latest/tutorials/grafana/grafana-timescalecloud/#connect-timescaledb-and-grafana). |
|
||||
|
||||
### Min time interval
|
||||
|
||||
A lower limit for the [`$__interval`](ref:add-template-variables-interval) and [`$__interval_ms`](ref:add-template-variables-interval-ms) variables.
|
||||
Recommended to be set to write frequency, for example `1m` if your data is written every minute.
|
||||
This option can also be overridden/configured in a dashboard panel under data source options. It's important to note that this value **needs** to be formatted as a
|
||||
number followed by a valid time identifier, e.g. `1m` (1 minute) or `30s` (30 seconds). The following time identifiers are supported:
|
||||
|
||||
| Identifier | Description |
|
||||
| ---------- | ----------- |
|
||||
| `y` | year |
|
||||
| `M` | month |
|
||||
| `w` | week |
|
||||
| `d` | day |
|
||||
| `h` | hour |
|
||||
| `m` | minute |
|
||||
| `s` | second |
|
||||
| `ms` | millisecond |
|
||||
|
||||
### Database user permissions (Important!)
|
||||
|
||||
The database user you specify when you add the data source should only be granted SELECT permissions on
|
||||
the specified database and tables you want to query. Grafana does not validate that the query is safe. The query
|
||||
could include any SQL statement. For example, statements like `DELETE FROM user;` and `DROP TABLE user;` would be
|
||||
executed. To protect against this we **highly** recommend you create a specific PostgreSQL user with restricted permissions.
|
||||
|
||||
Example:
|
||||
|
||||
```sql
|
||||
CREATE USER grafanareader WITH PASSWORD 'password';
|
||||
GRANT USAGE ON SCHEMA schema TO grafanareader;
|
||||
GRANT SELECT ON schema.table TO grafanareader;
|
||||
```
|
||||
|
||||
Make sure the user does not get any unwanted privileges from the public role.
|
||||
|
||||
## Query builder
|
||||
|
||||
{{< figure src="/static/img/docs/screenshot-postgres-query-editor.png" class="docs-image--no-shadow" caption="PostgreSQL query builder" >}}
|
||||
|
||||
The PostgreSQL query builder is available when editing a panel using a PostgreSQL data source. The built query can be run by pressing the `Run query` button in the top right corner of the editor.
|
||||
|
||||
### Format
|
||||
|
||||
The response from PostgreSQL can be formatted as either a table or as a time series. To use the time series format one of the columns must be named `time`.
|
||||
|
||||
### Dataset and table selection
|
||||
|
||||
The dataset dropdown will be populated with the configured database to which the user has access.
|
||||
The table dropdown is populated with the tables that are available within that database.
|
||||
|
||||
### Columns and Aggregation functions (SELECT)
|
||||
|
||||
Using the dropdown, select a column to include in the data. You can also specify an optional aggregation function.
|
||||
|
||||
Add further value columns by clicking the plus button and another column dropdown appears.
|
||||
|
||||
{{< docs/shared source="grafana" lookup="datasources/sql-query-builder-macros.md" version="<GRAFANA_VERSION>" >}}
|
||||
|
||||
### Filter data (WHERE)
|
||||
|
||||
To add a filter, toggle the **Filter** switch at the top of the editor.
|
||||
This reveals a **Filter by column value** section with two dropdown selectors.
|
||||
|
||||
Use the first dropdown to choose whether all of the filters need to match (`AND`), or if only one of the filters needs to match (`OR`).
|
||||
Use the second dropdown to choose a filter.
|
||||
|
||||
To filter on more columns, click the plus (`+`) button to the right of the condition dropdown.
|
||||
|
||||
To remove a filter, click the `x` button next to that filter's dropdown.
|
||||
|
||||
After selecting a date type column, you can choose Macros from the operators list and select timeFilter which will add the $\_\_timeFilter macro to the query with the selected date column.
|
||||
|
||||
### Group By
|
||||
|
||||
To group the results by column, flip the group switch at the top of the editor. You can then choose which column to group the results by. The group by clause can be removed by pressing the X button.
|
||||
|
||||
### Preview
|
||||
|
||||
By flipping the preview switch at the top of the editor, you can get a preview of the SQL query generated by the query builder.
|
||||
|
||||
### Provision the data source
|
||||
|
||||
It's now possible to configure data sources using config files with Grafana's provisioning system. You can read more about how it works and all the settings you can set for data sources on the [provisioning docs page](ref:provisioning-data-sources).
|
||||
|
||||
#### Provisioning example
|
||||
|
||||
```yaml
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Postgres
|
||||
type: postgres
|
||||
url: localhost:5432
|
||||
user: grafana
|
||||
secureJsonData:
|
||||
password: 'Password!'
|
||||
jsonData:
|
||||
database: grafana
|
||||
sslmode: 'disable' # disable/require/verify-ca/verify-full
|
||||
maxOpenConns: 100
|
||||
maxIdleConns: 100
|
||||
maxIdleConnsAuto: true
|
||||
connMaxLifetime: 14400
|
||||
postgresVersion: 903 # 903=9.3, 904=9.4, 905=9.5, 906=9.6, 1000=10
|
||||
timescaledb: false
|
||||
```
|
||||
|
||||
{{% admonition type="note" %}}
|
||||
In the above code, the `postgresVersion` value of `10` refers to version PostgreSQL 10 and above.
|
||||
{{% /admonition %}}
|
||||
|
||||
#### Troubleshoot provisioning
|
||||
|
||||
If you encounter metric request errors or other issues:
|
||||
|
||||
- Make sure your data source YAML file parameters exactly match the example. This includes parameter names and use of quotation marks.
|
||||
- Make sure the `database` name is not included in the `url`.
|
||||
|
||||
## Code editor
|
||||
|
||||
{{< figure src="/static/img/docs/v92/sql_code_editor.png" class="docs-image--no-shadow" >}}
|
||||
|
||||
To make advanced queries, switch to the code editor by clicking `code` in the top right corner of the editor. The code editor support autocompletion of tables, columns, SQL keywords, standard sql functions, Grafana template variables and Grafana macros. Columns cannot be completed before a table has been specified.
|
||||
|
||||
You can expand the code editor by pressing the `chevron` pointing downwards in the lower right corner of the code editor.
|
||||
|
||||
`CTRL/CMD + Return` works as a keyboard shortcut to run the query.
|
||||
|
||||
## Macros
|
||||
|
||||
Macros can be used within a query to simplify syntax and allow for dynamic parts.
|
||||
|
||||
| Macro example | Description |
|
||||
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `$__time(dateColumn)` | Will be replaced by an expression to convert to a UNIX timestamp and rename the column to `time_sec`. For example, _UNIX_TIMESTAMP(dateColumn) as time_sec_ |
|
||||
| `$__timeEpoch(dateColumn)` | Will be replaced by an expression to convert to a UNIX timestamp and rename the column to `time_sec`. For example, _UNIX_TIMESTAMP(dateColumn) as time_sec_ |
|
||||
| `$__timeFilter(dateColumn)` | Will be replaced by a time range filter using the specified column name. For example, _dateColumn BETWEEN FROM_UNIXTIME(1494410783) AND FROM_UNIXTIME(1494410983)_ |
|
||||
| `$__timeFrom()` | Will be replaced by the start of the currently active time selection. For example, _FROM_UNIXTIME(1494410783)_ |
|
||||
| `$__timeTo()` | Will be replaced by the end of the currently active time selection. For example, _FROM_UNIXTIME(1494410983)_ |
|
||||
| `$__timeGroup(dateColumn,'5m')` | Will be replaced by an expression usable in GROUP BY clause. For example, *cast(cast(UNIX_TIMESTAMP(dateColumn)/(300) as signed)*300 as signed),\* |
|
||||
| `$__timeGroup(dateColumn,'5m', 0)` | Same as above but with a fill parameter so missing points in that series will be added by grafana and 0 will be used as value (only works with time series queries). |
|
||||
| `$__timeGroup(dateColumn,'5m', NULL)` | Same as above but NULL will be used as value for missing points (only works with time series queries). |
|
||||
| `$__timeGroup(dateColumn,'5m', previous)` | Same as above but the previous value in that series will be used as fill value if no value has been seen yet NULL will be used (only works with time series queries). |
|
||||
| `$__timeGroupAlias(dateColumn,'5m')` | Will be replaced identical to $\_\_timeGroup but with an added column alias. |
|
||||
| `$__unixEpochFilter(dateColumn)` | Will be replaced by a time range filter using the specified column name with times represented as Unix timestamp. For example, _dateColumn > 1494410783 AND dateColumn < 1494497183_ |
|
||||
| `$__unixEpochFrom()` | Will be replaced by the start of the currently active time selection as Unix timestamp. For example, _1494410783_ |
|
||||
| `$__unixEpochTo()` | Will be replaced by the end of the currently active time selection as Unix timestamp. For example, _1494497183_ |
|
||||
| `$__unixEpochNanoFilter(dateColumn)` | Will be replaced by a time range filter using the specified column name with times represented as nanosecond timestamp. For example, _dateColumn > 1494410783152415214 AND dateColumn < 1494497183142514872_ |
|
||||
| `$__unixEpochNanoFrom()` | Will be replaced by the start of the currently active time selection as nanosecond timestamp. For example, _1494410783152415214_ |
|
||||
| `$__unixEpochNanoTo()` | Will be replaced by the end of the currently active time selection as nanosecond timestamp. For example, _1494497183142514872_ |
|
||||
| `$__unixEpochGroup(dateColumn,'5m', [fillmode])` | Same as $\_\_timeGroup but for times stored as Unix timestamp (`fillMode` only works with time series queries). |
|
||||
| `$__unixEpochGroupAlias(dateColumn,'5m', [fillmode])` | Same as above but also adds a column alias (`fillMode` only works with time series queries). |
|
||||
|
||||
## Table queries
|
||||
|
||||
If the `Format as` query option is set to `Table` then you can basically do any type of SQL query. The table panel will automatically show the results of whatever columns and rows your query returns.
|
||||
|
||||
Query editor with example query:
|
||||
|
||||

|
||||
|
||||
The query:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
title as "Title",
|
||||
"user".login as "Created By",
|
||||
dashboard.created as "Created On"
|
||||
FROM dashboard
|
||||
INNER JOIN "user" on "user".id = dashboard.created_by
|
||||
WHERE $__timeFilter(dashboard.created)
|
||||
```
|
||||
|
||||
You can control the name of the Table panel columns by using regular `as ` SQL column selection syntax.
|
||||
|
||||
The resulting table panel:
|
||||
|
||||

|
||||
|
||||
## Time series queries
|
||||
|
||||
If you set Format as to _Time series_, then the query must have a column named time that returns either a SQL datetime or any numeric datatype representing Unix epoch in seconds. In addition, result sets of time series queries must be sorted by time for panels to properly visualize the result.
|
||||
|
||||
A time series query result is returned in a [wide data frame format](https://grafana.com/developers/plugin-tools/key-concepts/data-frames#wide-format). Any column except time or of type string transforms into value fields in the data frame query result. Any string column transforms into field labels in the data frame query result.
|
||||
|
||||
> For backward compatibility, there's an exception to the above rule for queries that return three columns including a string column named metric. Instead of transforming the metric column into field labels, it becomes the field name, and then the series name is formatted as the value of the metric column. See the example with the metric column below.
|
||||
|
||||
To optionally customize the default series name formatting, refer to [Standard options definitions](ref:configure-standard-options-display-name).
|
||||
|
||||
**Example with `metric` column:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
$__timeGroupAlias("time_date_time",'5m'),
|
||||
min("value_double"),
|
||||
'min' as metric
|
||||
FROM test_data
|
||||
WHERE $__timeFilter("time_date_time")
|
||||
GROUP BY time
|
||||
ORDER BY time
|
||||
```
|
||||
|
||||
Data frame result:
|
||||
|
||||
```text
|
||||
+---------------------+-----------------+
|
||||
| Name: time | Name: min |
|
||||
| Labels: | Labels: |
|
||||
| Type: []time.Time | Type: []float64 |
|
||||
+---------------------+-----------------+
|
||||
| 2020-01-02 03:05:00 | 3 |
|
||||
| 2020-01-02 03:10:00 | 6 |
|
||||
+---------------------+-----------------+
|
||||
```
|
||||
|
||||
**Example using the fill parameter in the $\_\_timeGroupAlias macro to convert null values to be zero instead:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
$__timeGroupAlias("createdAt",'5m',0),
|
||||
sum(value) as value,
|
||||
hostname
|
||||
FROM test_data
|
||||
WHERE
|
||||
$__timeFilter("createdAt")
|
||||
GROUP BY time, hostname
|
||||
ORDER BY time
|
||||
```
|
||||
|
||||
Given the data frame result in the following example and using the graph panel, you will get two series named _value 10.0.1.1_ and _value 10.0.1.2_. To render the series with a name of _10.0.1.1_ and _10.0.1.2_ , use a [Standard options definitions](ref:configure-standard-options-display-name) display value of `${__field.labels.hostname}`.
|
||||
|
||||
Data frame result:
|
||||
|
||||
```text
|
||||
+---------------------+---------------------------+---------------------------+
|
||||
| Name: time | Name: value | Name: value |
|
||||
| Labels: | Labels: hostname=10.0.1.1 | Labels: hostname=10.0.1.2 |
|
||||
| Type: []time.Time | Type: []float64 | Type: []float64 |
|
||||
+---------------------+---------------------------+---------------------------+
|
||||
| 2020-01-02 03:05:00 | 3 | 4 |
|
||||
| 2020-01-02 03:10:00 | 6 | 7 |
|
||||
+---------------------+---------------------------+---------------------------+
|
||||
```
|
||||
|
||||
**Example with multiple columns:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
$__timeGroupAlias("time_date_time",'5m'),
|
||||
min("value_double") as "min_value",
|
||||
max("value_double") as "max_value"
|
||||
FROM test_data
|
||||
WHERE $__timeFilter("time_date_time")
|
||||
GROUP BY time
|
||||
ORDER BY time
|
||||
```
|
||||
|
||||
Data frame result:
|
||||
|
||||
```text
|
||||
+---------------------+-----------------+-----------------+
|
||||
| Name: time | Name: min_value | Name: max_value |
|
||||
| Labels: | Labels: | Labels: |
|
||||
| Type: []time.Time | Type: []float64 | Type: []float64 |
|
||||
+---------------------+-----------------+-----------------+
|
||||
| 2020-01-02 03:04:00 | 3 | 4 |
|
||||
| 2020-01-02 03:05:00 | 6 | 7 |
|
||||
+---------------------+-----------------+-----------------+
|
||||
```
|
||||
|
||||
## Templating
|
||||
|
||||
Instead of hard-coding things like server, application and sensor name in your metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. These dropdowns make it easy to change the data being displayed in your dashboard.
|
||||
|
||||
Refer to [Templates and variables](ref:variables) for an introduction to the templating feature and the different types of template variables.
|
||||
|
||||
### Query variable
|
||||
|
||||
If you add a template variable of the type `Query`, you can write a PostgreSQL query that can
|
||||
return things like measurement names, key names or key values that are shown as a dropdown select box.
|
||||
|
||||
For example, you can have a variable that contains all values for the `hostname` column in a table if you specify a query like this in the templating variable _Query_ setting.
|
||||
|
||||
```sql
|
||||
SELECT hostname FROM host
|
||||
```
|
||||
|
||||
A query can return multiple columns and Grafana will automatically create a list from them. For example, the query below will return a list with values from `hostname` and `hostname2`.
|
||||
|
||||
```sql
|
||||
SELECT host.hostname, other_host.hostname2 FROM host JOIN other_host ON host.city = other_host.city
|
||||
```
|
||||
|
||||
To use time range dependent macros like `$__timeFilter(column)` in your query the refresh mode of the template variable needs to be set to _On Time Range Change_.
|
||||
|
||||
```sql
|
||||
SELECT event_name FROM event_log WHERE $__timeFilter(time_column)
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```sql
|
||||
SELECT hostname AS __text, id AS __value FROM host
|
||||
```
|
||||
|
||||
You can also create nested variables. Using a variable named `region`, you could have
|
||||
the hosts variable only show hosts from the current selected region with a query like this (if `region` is a multi-value variable then use the `IN` comparison operator rather than `=` to match against multiple values):
|
||||
|
||||
```sql
|
||||
SELECT hostname FROM host WHERE region IN($region)
|
||||
```
|
||||
|
||||
#### Using `__searchFilter` to filter results in Query Variable
|
||||
|
||||
Using `__searchFilter` in the query field will filter the query result based on what the user types in the dropdown select box.
|
||||
When nothing has been entered by the user the default value for `__searchFilter` is `%`.
|
||||
|
||||
> Important that you surround the `__searchFilter` expression with quotes as Grafana does not do this for you.
|
||||
|
||||
The example below shows how to use `__searchFilter` as part of the query field to enable searching for `hostname` while the user types in the dropdown select box.
|
||||
|
||||
Query
|
||||
|
||||
```sql
|
||||
SELECT hostname FROM my_host WHERE hostname LIKE '$__searchFilter'
|
||||
```
|
||||
|
||||
### Using Variables in Queries
|
||||
|
||||
Template variable values are only quoted when the template variable is a `multi-value`.
|
||||
|
||||
If the variable is a multi-value variable then use the `IN` comparison operator rather than `=` to match against multiple values.
|
||||
|
||||
There are two syntaxes:
|
||||
|
||||
`$<varname>` Example with a template variable named `hostname`:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
atimestamp as time,
|
||||
aint as value
|
||||
FROM table
|
||||
WHERE $__timeFilter(atimestamp) and hostname in($hostname)
|
||||
ORDER BY atimestamp ASC
|
||||
```
|
||||
|
||||
`[[varname]]` Example with a template variable named `hostname`:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
atimestamp as time,
|
||||
aint as value
|
||||
FROM table
|
||||
WHERE $__timeFilter(atimestamp) and hostname in([[hostname]])
|
||||
ORDER BY atimestamp ASC
|
||||
```
|
||||
|
||||
#### Disabling quoting for multi-value variables
|
||||
|
||||
Grafana automatically creates a quoted, comma-separated string for multi-value variables. For example: if `server01` and `server02` are selected then it will be formatted as: `'server01', 'server02'`. To disable quoting, use the csv formatting option for variables:
|
||||
|
||||
`${servers:csv}`
|
||||
|
||||
Read more about variable formatting options in the [Variables](ref:variable-syntax-advanced-variable-format-options) documentation.
|
||||
|
||||
## Annotations
|
||||
|
||||
[Annotations](ref:annotate-visualizations) allow you to overlay rich event information on top of graphs. You add annotation queries via the Dashboard menu / Annotations view.
|
||||
|
||||
**Example query using time column with epoch values:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
epoch_time as time,
|
||||
metric1 as text,
|
||||
concat_ws(', ', metric1::text, metric2::text) as tags
|
||||
FROM
|
||||
public.test_data
|
||||
WHERE
|
||||
$__unixEpochFilter(epoch_time)
|
||||
```
|
||||
|
||||
**Example region query using time and timeend columns with epoch values:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
epoch_time as time,
|
||||
epoch_time_end as timeend,
|
||||
metric1 as text,
|
||||
concat_ws(', ', metric1::text, metric2::text) as tags
|
||||
FROM
|
||||
public.test_data
|
||||
WHERE
|
||||
$__unixEpochFilter(epoch_time)
|
||||
```
|
||||
|
||||
**Example query using time column of native SQL date/time data type:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
native_date_time as time,
|
||||
metric1 as text,
|
||||
concat_ws(', ', metric1::text, metric2::text) as tags
|
||||
FROM
|
||||
public.test_data
|
||||
WHERE
|
||||
$__timeFilter(native_date_time)
|
||||
```
|
||||
|
||||
| Name | Description |
|
||||
| --------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `time` | The name of the date/time field. Could be a column with a native SQL date/time data type or epoch value. |
|
||||
| `timeend` | Optional name of the end date/time field. Could be a column with a native SQL date/time data type or epoch value. |
|
||||
| `text` | Event description field. |
|
||||
| `tags` | Optional field name to use for event tags as a comma separated string. |
|
||||
|
||||
## Alerting
|
||||
|
||||
Time series queries should work in alerting conditions. Table formatted queries are not yet supported in alert rule
|
||||
conditions.
|
||||
|
194
docs/sources/datasources/postgres/configure/_index.md
Normal file
194
docs/sources/datasources/postgres/configure/_index.md
Normal file
@ -0,0 +1,194 @@
|
||||
---
|
||||
description: This document provides instructions for configuring the PostgreSQL data source.
|
||||
keywords:
|
||||
- grafana
|
||||
- postgresql
|
||||
- guide
|
||||
labels:
|
||||
products:
|
||||
- cloud
|
||||
- enterprise
|
||||
- oss
|
||||
menuTitle: Configure the PostgreSQL data source
|
||||
title: Configure the PostgreSQL data source
|
||||
weight: 10
|
||||
refs:
|
||||
provisioning-data-sources:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/administration/provisioning/#datasources
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/administration/provisioning/#datasources
|
||||
variables:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/
|
||||
add-template-variables-interval-ms:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval_ms
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval_ms
|
||||
add-template-variables-interval:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval
|
||||
data-source-management:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/administration/data-source-management/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/administration/data-source-management/
|
||||
variable-syntax-advanced-variable-format-options:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/variable-syntax/#advanced-variable-format-options
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/variable-syntax/#advanced-variable-format-options
|
||||
---
|
||||
|
||||
# Configure the PostgreSQL data source
|
||||
|
||||
This document provides instructions for configuring the PostgreSQL data source and explains available configuration options. For general information on managing data sources refer to [Data source management](ref:data-source-management).
|
||||
|
||||
## Before you begin
|
||||
|
||||
You must have the `Organization administrator` role to configure the Postgres data source.
|
||||
Organization administrators can also [configure the data source via YAML](#provision-the-data-source) with the Grafana provisioning system.
|
||||
|
||||
Grafana comes with a built-in PostgreSQL data source plugin, eliminating the need to install a plugin.
|
||||
|
||||
{{< admonition type="note" >}}
|
||||
When adding a data source, the database user you specify should have only `SELECT` permissions on the relevant database and tables. Grafana does not validate the safety of queries, which means they can include potentially harmful SQL statements, such as `USE otherdb;` or `DROP TABLE user;`, that could be executed. To mitigate this risk, Grafana strongly recommends creating a dedicated PostgreSQL user with restricted permissions.
|
||||
{{< /admonition >}}
|
||||
|
||||
Example:
|
||||
|
||||
```sql
|
||||
CREATE USER grafanareader WITH PASSWORD 'password';
|
||||
GRANT USAGE ON SCHEMA schema TO grafanareader;
|
||||
GRANT SELECT ON schema.table TO grafanareader;
|
||||
```
|
||||
|
||||
## Add the PostgreSQL data source
|
||||
|
||||
Complete the following steps to set up a new PostgreSQL data source:
|
||||
|
||||
1. Click **Connections** in the left-side menu.
|
||||
1. Click **Add new connection**
|
||||
1. Type `PostgreSQL` in the search bar.
|
||||
1. Select the **PostgreSQL data source**.
|
||||
1. Click **Add new data source** in the upper right.
|
||||
|
||||
You are taken to the **Settings** tab where you will configure the data source.
|
||||
|
||||
## PostgreSQL configuration options
|
||||
|
||||
Following is a list of PostgreSQL configuration options:
|
||||
|
||||
- **Name** - Sets the name you use to refer to the data source in panels and queries. Examples: `PostgreSQL-DB-1`.
|
||||
- **Default** - Toggle to set this specific PostgreSQL data source as the default pre-selected data source in panels and visualizations.
|
||||
|
||||
**Connection section:**
|
||||
|
||||
- **Host URL** - The IP address/hostname and optional port of your PostgreSQL instance.
|
||||
- **Database name** - The name of your PostgreSQL database.
|
||||
|
||||
**Authentication section:**
|
||||
|
||||
- **Username** - Enter the username used to connect to your PostgreSQL database.
|
||||
- **Password** - Enter the password used to connect to the PostgreSQL database.
|
||||
- **TLS/SSL Mode** - Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server. When **TLS/SSL Mode** is disabled, **TLS/SSL Method** and **TLS/SSL Auth Details** aren't visible options.
|
||||
- **TLS/SSL Method** - Determines how TLS/SSL certificates are configured.
|
||||
- **File system path** - This option allows you to configure certificates by specifying paths to existing certificates on the local file system where Grafana is running. Ensure this file is readable by the user executing the Grafana process.
|
||||
- **Certificate content** - This option allows you to configure certificate by specifying their content. The content is stored and encrypted in the Grafana database. When connecting to the database, the certificates are saved as files, on the local filesystem, in the Grafana data path.
|
||||
|
||||
**TLS/SSL Auth Details**
|
||||
|
||||
If you select the TLS/SSL Mode options **require**, **verify-ca** or **verify-full** and **file system path** the following are required:
|
||||
|
||||
- **TLS/SSL Root Certificate** - Specify the path to the root certificate file.
|
||||
- **TLS/SSL Client Certificate** - Specify the path to the client certificate and ensure the file is accessible to the user running the Grafana process.
|
||||
- **TLS/SSL Client Key** - Specify the path to the client key file and ensure the file is accessible to the user running the Grafana process.
|
||||
|
||||
If you select the TLS/SSL Mode option **require** and TLS/SSL Method certificate content the following are required:
|
||||
|
||||
- **TLS/SSL Client Certificate** - Provide the client certificate.
|
||||
- **TLS/SSL Client Key** - Provide the client key.
|
||||
|
||||
If you select the TLS/SSL Mode options **verify-ca** or **verify-full** with the TLS/SSL Method certificate content the following are required:
|
||||
|
||||
- **TLS/SSL Client Certificate** - Provide the client certificate.
|
||||
- **TLS/SSL Root Certificate** - Provide the root certificate.
|
||||
- **TLS/SSL Client Key** - Provide the client key.
|
||||
|
||||
**PostgreSQL Options:**
|
||||
|
||||
- **Version** - Determines which functions are available in the query builder. The default is the current version.
|
||||
- **Min time interval** - Defines a lower limit for the auto group by by time interval. Grafana recommends aligning this setting with the data write frequency. For example, set it to `1m` if your data is written every minute. Refer to [Min time interval](#min-time-interval) for format examples.
|
||||
- **TimescaleDB** - A time-series database built as a PostgreSQL extension. When enabled, Grafana uses `time_bucket` in the `$__timeGroup` macro to display TimescaleDB specific aggregate functions in the query builder. For more information, refer to [TimescaleDB documentation](https://docs.timescale.com/timescaledb/latest/tutorials/grafana/grafana-timescalecloud/#connect-timescaledb-and-grafana).
|
||||
|
||||
**Connection limits:**
|
||||
|
||||
- **Max open** - The maximum number of open connections to the database. The default `100`.
|
||||
- **Auto max idle** - Toggle to set the maximum number of idle connections to the number of maximum open connections. This setting is toggled on by default.
|
||||
- **Max idle** - The maximum number of connections in the idle connection pool. The default `100`.
|
||||
- **Max lifetime** - The maximum amount of time in seconds a connection may be reused. The default is `14400`, or 4 hours.
|
||||
|
||||
**Private data source connect** - _Only for Grafana Cloud users._ Private data source connect, or PDC, allows you to establish a private, secured connection between a Grafana Cloud instance, or stack, and data sources secured within a private network. Click the drop-down to locate the URL for PDC. For more information regarding Grafana PDC refer to [Private data source connect (PDC)](https://grafana.com/docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/).
|
||||
|
||||
Click **Manage private data source connect** to be taken to your PDC connection page, where you’ll find your PDC configuration details.
|
||||
|
||||
After you have added your PostgreSQL connection settings, click **Save & test** to test and save the data source connection.
|
||||
|
||||
### Min time interval
|
||||
|
||||
The **Min time interval** setting defines a lower limit for the [`$__interval`](ref:add-template-variables-interval) and [`$__interval_ms`](ref:add-template-variables-interval-ms) variables.
|
||||
|
||||
This option can also be configured or overridden in the dashboard panel under the data source settings.
|
||||
|
||||
This value must be formatted as a number followed by a valid time identifier:
|
||||
|
||||
| Identifier | Description |
|
||||
| ---------- | ----------- |
|
||||
| `y` | year |
|
||||
| `M` | month |
|
||||
| `w` | week |
|
||||
| `d` | day |
|
||||
| `h` | hour |
|
||||
| `m` | minute |
|
||||
| `s` | second |
|
||||
| `ms` | millisecond |
|
||||
|
||||
## Provision the data source
|
||||
|
||||
You can define and configure the data source in YAML files with [provisioning](/docs/grafana/<GRAFANA_VERSION>/administration/provisioning/#data-sources).
|
||||
For more information about provisioning, and available configuration options, refer to [Provision Grafana](ref:provisioning-data-sources).
|
||||
|
||||
### PostgreSQL provisioning example
|
||||
|
||||
```yaml
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Postgres
|
||||
type: postgres
|
||||
url: localhost:5432
|
||||
user: grafana
|
||||
secureJsonData:
|
||||
password: 'Password!'
|
||||
jsonData:
|
||||
database: grafana
|
||||
sslmode: 'disable' # disable/require/verify-ca/verify-full
|
||||
maxOpenConns: 100
|
||||
maxIdleConns: 100
|
||||
maxIdleConnsAuto: true
|
||||
connMaxLifetime: 14400
|
||||
postgresVersion: 903 # 903=9.3, 904=9.4, 905=9.5, 906=9.6, 1000=10
|
||||
timescaledb: false
|
||||
```
|
||||
|
||||
#### Troubleshoot provisioning issues
|
||||
|
||||
If you encounter metric request errors or other issues:
|
||||
|
||||
- Ensure that the parameters in your data source YAML file precisely match the example provided, including parameter names and the correct use of quotation marks.
|
||||
- Verify that the database name _isn't_ included in the URL.
|
410
docs/sources/datasources/postgres/query-editor/_index.md
Normal file
410
docs/sources/datasources/postgres/query-editor/_index.md
Normal file
@ -0,0 +1,410 @@
|
||||
---
|
||||
description: This document describes the PostgreSQL query editor in Grafana.
|
||||
keywords:
|
||||
- grafana
|
||||
- postgresql
|
||||
- guide
|
||||
labels:
|
||||
products:
|
||||
- cloud
|
||||
- enterprise
|
||||
- oss
|
||||
menuTitle: PostgreSQL query editor
|
||||
title: PostgreSQL query editor
|
||||
weight: 20
|
||||
refs:
|
||||
variables:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/
|
||||
add-template-variables-interval:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/add-template-variables/#__interval
|
||||
explore:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/explore/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/explore/
|
||||
query-transform-data:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/panels-visualizations/query-transform-data/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana-cloud/visualizations/panels-visualizations/query-transform-data/
|
||||
query-editor:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/panels-visualizations/query-transform-data/#query-editors
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana-cloud/visualizations/panels-visualizations/query-transform-data/#query-editors
|
||||
alert-rules:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/alerting/fundamentals/alert-rules/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana-cloud/alerting-and-irm/alerting/alerting-rules/
|
||||
template-annotations-and-labels:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/alerting/alerting-rules/templates/
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana-cloud/alerting-and-irm/alerting/alerting-rules/templates/
|
||||
templates:
|
||||
- pattern: /docs/grafana/
|
||||
destination: /docs/grafana/<GRAFANA_VERSION>/dashboards/variables/#templates
|
||||
- pattern: /docs/grafana-cloud/
|
||||
destination: /docs/grafana-cloud/visualizations/dashboards/variables/#templates
|
||||
---
|
||||
|
||||
# PostgreSQL query editor
|
||||
|
||||
Grafana query editors are unique for each data source.
|
||||
|
||||
For general information on Grafana query editors, refer to [Query editors](ref:query-editor).
|
||||
|
||||
For general information on querying data sources in Grafana, refer to [Query and transform data](ref:query-transform-data).
|
||||
|
||||
The PostgreSQL query editor is located on the [Explore page](ref:explore). You can also access the PostgreSQL query editor from a dashboard panel. Click the ellipsis in the upper right of the panel and select **Edit**.
|
||||
|
||||
{{< figure src="/static/img/docs/screenshot-postgres-query-editor.png" class="docs-image--no-shadow" caption="PostgreSQL query builder" >}}
|
||||
|
||||
## PostgreSQL query editor components
|
||||
|
||||
The PostgreSQL query editor has two modes: **Builder** and **Code**.
|
||||
|
||||
Builder mode helps you build a query using a visual interface. Code mode allows for advanced querying and offers support for complex SQL query writing.
|
||||
|
||||
### PostgreSQL Builder mode
|
||||
|
||||
The following components will help you build a PostgreSQL query:
|
||||
|
||||
- **Format** - Select a format response from the drop-down for the PostgreSQL query. The default is **Table**. If you use the **Time series** format option, one of the columns must be `time`. Refer to [Time series queries](#time-series-queries) for more information.
|
||||
- **Table** - Select a table from the drop-down. Tables correspond to the chosen database.
|
||||
- **Data operations** - _Optional_ Select an aggregation from the drop-down. You can add multiple data operations by clicking the **+ sign**. Click the **garbage can icon** to remove data operations.
|
||||
- **Column** - Select a column on which to run the aggregation.
|
||||
- **Alias** - _Optional_ Add an alias from the drop-down. You can also add your own alias by typing it in the box and clicking **Enter**. Remove an alias by clicking the **X**.
|
||||
- **Filter** - Toggle to add filters.
|
||||
- **Filter by column value** - _Optional_ If you toggle **Filter** you can add a column to filter by from the drop-down. To filter on more columns, click the **+ sign** to the right of the condition drop-down. You can choose a variety of operators from the drop-down next to the condition. When multiple filters are added you can add an `AND` operator to display all true conditions or an `OR` operator to display any true conditions. Use the second drop-down to choose a filter. To remove a filter, click the `X` button next to that filter's drop-down. After selecting a date type column, you can choose **Macros** from the operators list and select `timeFilter` which will add the `$\_\_timeFilter` macro to the query with the selected date column.
|
||||
- **Group** - Toggle to add **Group by column**.
|
||||
- **Group by column** - Select a column to filter by from the drop-down. Click the **+sign** to filter by multiple columns. Click the **X** to remove a filter.
|
||||
- **Order** - Toggle to add an `ORDER BY` statement.
|
||||
- **Order by** - Select a column to order by from the drop-down. Select ascending (`ASC`) or descending (`DESC`) order.
|
||||
- **Limit** - You can add an optional limit on the number of retrieved results. Default is 50.
|
||||
- **Preview** - Toggle for a preview of the SQL query generated by the query builder. Preview is toggled on by default.
|
||||
|
||||
## PostgreSQL Code mode
|
||||
|
||||
To create advanced queries, switch to **Code mode** by clicking **Code** in the upper right of the editor window. Code mode supports the auto-completion of tables, columns, SQL keywords, standard SQL functions, Grafana template variables, and Grafana macros. Columns cannot be completed before a table has been specified.
|
||||
|
||||
{{< figure src="/static/img/docs/v92/sql_code_editor.png" class="docs-image--no-shadow" >}}
|
||||
|
||||
Select **Table** or **Time Series** as the format. Click the **{}** in the bottom right to format the query. Click the **downward caret** to expand the Code mode editor. **CTRL/CMD + Return** serves as a keyboard shortcut to execute the query.
|
||||
|
||||
{{< admonition type="warning" >}}
|
||||
Changes made to a query in Code mode will not transfer to Builder mode and will be discarded. You will be prompted to copy your code to the clipboard to save any changes.
|
||||
{{< /admonition >}}
|
||||
|
||||
## Macros
|
||||
|
||||
You can add macros to your queries to simplify the syntax and enable dynamic elements, such as date range filters.
|
||||
|
||||
| Macro example | Description |
|
||||
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `$__time(dateColumn)` | Replaces the value with an expression to convert to a UNIX timestamp and renames the column to `time_sec`. Example: `UNIX_TIMESTAMP(dateColumn) AS time_sec`. |
|
||||
| `$__timeEpoch(dateColumn)` | Replaces the value with an expression to convert to a UNIX Epoch timestamp and renames the column to `time_sec`. Example: `UNIX_TIMESTAMP(dateColumn) AS time_sec`. |
|
||||
| `$__timeFilter(dateColumn)` | Replaces the value a time range filter using the specified column name. Example: `dateColumn BETWEEN FROM_UNIXTIME(1494410783) AND FROM_UNIXTIME(1494410983)` |
|
||||
| `$__timeFrom()` | Replaces the value with the start of the currently active time selection. Example: `FROM_UNIXTIME(1494410783)` |
|
||||
| `$__timeTo()` | Replaces the value with the end of the currently active time selection. Example: `FROM_UNIXTIME(1494410983)` |
|
||||
| `$__timeGroup(dateColumn,'5m')` | Replaces the value with an expression suitable for use in a `GROUP BY` clause. Example: `cast(cast(UNIX_TIMESTAMP(dateColumn)/(300) AS signed)*300 AS signed)` |
|
||||
| `$__timeGroup(dateColumn,'5m', 0)` | Same as the `$__timeGroup(dateColumn,'5m')` macro, but includes a fill parameter to ensure missing points in the series are added by Grafana, using 0 as the default value. **This applies only to time series queries.** |
|
||||
| `$__timeGroup(dateColumn,'5m', NULL)` | Same as the `$__timeGroup(dateColumn,'5m', 0)` but `NULL` is used as the value for missing points. _This applies only to time series queries._ |
|
||||
| `$__timeGroup(dateColumn,'5m', previous)` | Same as the `$__timeGroup(dateColumn,'5m', previous)` macro, but uses the previous value in the series as the fill value. If no previous value exists, it uses `NULL`. _This applies only to time series queries._ |
|
||||
| `$__timeGroupAlias(dateColumn,'5m')` | Replaces the value identical to `$__timeGroup` but with an added column alias. |
|
||||
| `$__unixEpochFilter(dateColumn)` | Replaces the value by a time range filter using the specified column name with times represented as a UNIX timestamp. Example: `dateColumn > 1494410783 AND dateColumn < 1494497183` |
|
||||
| `$__unixEpochFrom()` | Replaces the value with the start of the currently active time selection as a UNIX timestamp. Example: `1494410783` |
|
||||
| `$__unixEpochTo()` | Replaces the value with the end of the currently active time selection as a UNIX timestamp. Example: `1494497183` |
|
||||
| `$__unixEpochNanoFilter(dateColumn)` | Replaces the value with a time range filter using the specified column name with time represented as a nanosecond timestamp. Example: `dateColumn > 1494410783152415214 AND dateColumn < 1494497183142514872` |
|
||||
| `$__unixEpochNanoFrom()` | Replaces the value with the start of the currently active time selection as a nanosecond timestamp. Example: `1494410783152415214` |
|
||||
| `$__unixEpochNanoTo()` | Replaces the value with the end of the currently active time selection as nanosecond timestamp. Example: `1494497183142514872` |
|
||||
| `$__unixEpochGroup(dateColumn,'5m', [fillmode])` | Same as `$__timeGroup` but for times stored as Unix timestamp. `fillMode` only works with time series queries. |
|
||||
| `$__unixEpochGroupAlias(dateColumn,'5m', [fillmode])` | Same as `$__timeGroup` but also adds a column alias. `fillMode` only works with time series queries. |
|
||||
|
||||
## Table SQL queries
|
||||
|
||||
If the **Format** option is set to **Table**, you can execute virtually any type of SQL query. The Table panel will automatically display the resulting columns and rows from your query.
|
||||
|
||||

|
||||
|
||||
You can change or customize the name of a Table panel column by using the SQL keyword `AS` syntax.
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
title as "Title",
|
||||
"user".login as "Created By",
|
||||
dashboard.created as "Created On"
|
||||
FROM dashboard
|
||||
INNER JOIN "user" on "user".id = dashboard.created_by
|
||||
WHERE $__timeFilter(dashboard.created)
|
||||
```
|
||||
|
||||
## Time series queries
|
||||
|
||||
Set the **Format** option to **Time series** to create and run time series queries.
|
||||
|
||||
{{< admonition type="note" >}}
|
||||
To run a time series query you must include a column named `time` that returns either a SQL `datetime` value or a numeric datatype representing the UNIX epoch time in seconds. Additionally, the query results must be sorted by the `time` column for proper visualization in panels.
|
||||
{{< /admonition >}}
|
||||
|
||||
The examples in this section refer to the data in the following table:
|
||||
|
||||
```text
|
||||
+---------------------+--------------+---------------------+----------+
|
||||
| time_date_time | value_double | CreatedAt | hostname |
|
||||
+---------------------+--------------+---------------------+----------+
|
||||
| 2020-01-02 03:05:00 | 3.0 | 2020-01-02 03:05:00 | 10.0.1.1 |
|
||||
| 2020-01-02 03:06:00 | 4.0 | 2020-01-02 03:06:00 | 10.0.1.2 |
|
||||
| 2020-01-02 03:10:00 | 6.0 | 2020-01-02 03:10:00 | 10.0.1.1 |
|
||||
| 2020-01-02 03:11:00 | 7.0 | 2020-01-02 03:11:00 | 10.0.1.2 |
|
||||
| 2020-01-02 03:20:00 | 5.0 | 2020-01-02 03:20:00 | 10.0.1.2 |
|
||||
+---------------------+--------------+---------------------+----------+
|
||||
```
|
||||
|
||||
Time series query results are returned in [wide data frame format](https://grafana.com/developers/plugin-tools/key-concepts/data-frames#wide-format). In the data frame query result, any column, except for time or string-type columns, transforms into value fields. String columns, on the other hand, become field labels.
|
||||
|
||||
{{< admonition type="note" >}}
|
||||
For backward compatibility, an exception to this rule applies to queries that return three columns, one of which is a string column named `metric`. Instead of converting the metric column into field labels, it is used as the field name, while the series name is set to its value. See the following example for reference.
|
||||
{{< /admonition >}}
|
||||
|
||||
**Example with `metric` column:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
$__timeGroupAlias("time_date_time",'5m'),
|
||||
min("value_double"),
|
||||
'min' as metric
|
||||
FROM test_data
|
||||
WHERE $__timeFilter("time_date_time")
|
||||
GROUP BY time
|
||||
ORDER BY time
|
||||
```
|
||||
|
||||
Data frame result:
|
||||
|
||||
```text
|
||||
+---------------------+-----------------+
|
||||
| Name: time | Name: min |
|
||||
| Labels: | Labels: |
|
||||
| Type: []time.Time | Type: []float64 |
|
||||
+---------------------+-----------------+
|
||||
| 2020-01-02 03:05:00 | 3 |
|
||||
| 2020-01-02 03:10:00 | 6 |
|
||||
+---------------------+-----------------+
|
||||
```
|
||||
|
||||
To customize default series name formatting, refer to [Standard options definitions](ref:configure-standard-options-display-name).
|
||||
|
||||
Following are time series query examples.
|
||||
|
||||
**Example using the fill parameter in the $\_\_timeGroupAlias macro to convert null values to be zero instead:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
$__timeGroupAlias("createdAt",'5m',0),
|
||||
sum(value) as value,
|
||||
hostname
|
||||
FROM test_data
|
||||
WHERE
|
||||
$__timeFilter("createdAt")
|
||||
GROUP BY time, hostname
|
||||
ORDER BY time
|
||||
```
|
||||
|
||||
Based on the data frame result in the following example, the time series panel will generate two series named _value 10.0.1.1_ and _value 10.0.1.2_. To display the series names as _10.0.1.1_ and _10.0.1.2_, use the [Standard options definitions](ref:configure-standard-options-display-name) display value `${__field.labels.hostname}`.
|
||||
|
||||
Data frame result:
|
||||
|
||||
```text
|
||||
+---------------------+---------------------------+---------------------------+
|
||||
| Name: time | Name: value | Name: value |
|
||||
| Labels: | Labels: hostname=10.0.1.1 | Labels: hostname=10.0.1.2 |
|
||||
| Type: []time.Time | Type: []float64 | Type: []float64 |
|
||||
+---------------------+---------------------------+---------------------------+
|
||||
| 2020-01-02 03:05:00 | 3 | 4 |
|
||||
| 2020-01-02 03:10:00 | 6 | 7 |
|
||||
+---------------------+---------------------------+---------------------------+
|
||||
```
|
||||
|
||||
**Example with multiple columns:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
$__timeGroupAlias("time_date_time",'5m'),
|
||||
min("value_double") as "min_value",
|
||||
max("value_double") as "max_value"
|
||||
FROM test_data
|
||||
WHERE $__timeFilter("time_date_time")
|
||||
GROUP BY time
|
||||
ORDER BY time
|
||||
```
|
||||
|
||||
Data frame result:
|
||||
|
||||
```text
|
||||
+---------------------+-----------------+-----------------+
|
||||
| Name: time | Name: min_value | Name: max_value |
|
||||
| Labels: | Labels: | Labels: |
|
||||
| Type: []time.Time | Type: []float64 | Type: []float64 |
|
||||
+---------------------+-----------------+-----------------+
|
||||
| 2020-01-02 03:04:00 | 3 | 4 |
|
||||
| 2020-01-02 03:05:00 | 6 | 7 |
|
||||
+---------------------+-----------------+-----------------+
|
||||
```
|
||||
|
||||
## Templating
|
||||
|
||||
Instead of hard coding values like server, application, or sensor names in your metric queries, you can use variables. Variables appear as drop-down select boxes at the top of the dashboard. These drop-downs make it easy to change the data being displayed in your dashboard.
|
||||
|
||||
Refer to [Templates](ref:templates) for an introduction to creating template variables as well as the different types.
|
||||
|
||||
### Query variable
|
||||
|
||||
If you add a `Query` template variable you can write a PostgreSQL query to retrieve items such as measurement names, key names, or key values, which will be displayed in the drop-down menu.
|
||||
|
||||
For example, you can use a variable to retrieve all the values from the `hostname` column in a table by creating the following query in the templating variable _Query_ setting.
|
||||
|
||||
```sql
|
||||
SELECT hostname FROM host
|
||||
```
|
||||
|
||||
A query can return multiple columns, and Grafana will automatically generate a list based on the query results. For example, the following query returns a list with values from `hostname` and `hostname2`.
|
||||
|
||||
```sql
|
||||
SELECT host.hostname, other_host.hostname2 FROM host JOIN other_host ON host.city = other_host.city
|
||||
```
|
||||
|
||||
To use time range dependent macros like `$__timeFilter(column)` in your query, you must set the template variable's refresh mode to _On Time Range Change_.
|
||||
|
||||
```sql
|
||||
SELECT event_name FROM event_log WHERE $__timeFilter(time_column)
|
||||
```
|
||||
|
||||
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 must contain unique values (if not, only the first value is used). This allows the drop-down options to display a text-friendly name as the text while using an ID as the value. For example, a query could use `hostname` as the text and `id` as the value:
|
||||
|
||||
```sql
|
||||
SELECT hostname AS __text, id AS __value FROM host
|
||||
```
|
||||
|
||||
You can also create nested variables. For example, if you have a variable named `region`, you can configure the `hosts` variable to display only the hosts within the currently selected region as shown in the following example. If `region` is a multi-value variable, use the `IN` operator instead of `=` to match multiple values.
|
||||
|
||||
```sql
|
||||
SELECT hostname FROM host WHERE region IN($region)
|
||||
```
|
||||
|
||||
#### Using `__searchFilter` to filter results in Query Variable
|
||||
|
||||
Using `__searchFilter` in the query field allows the query results to be filtered based on the user’s input in the drop-down selection box. If you do not enter anything, the default value for `__searchFilter` is `%`.
|
||||
|
||||
Note that you must enclose the `__searchFilter` expression in quotes as Grafana does not add them automatically.
|
||||
|
||||
The following example demonstrates how to use `__searchFilter` in the query field to enable real-time searching for `hostname` as the user type in the drop-down selection box.
|
||||
|
||||
```sql
|
||||
SELECT hostname FROM my_host WHERE hostname LIKE '$__searchFilter'
|
||||
```
|
||||
|
||||
### Using Variables in Queries
|
||||
|
||||
Template variable values are only quoted when the template variable is a `multi-value`.
|
||||
|
||||
If the variable is a multi-value variable, use the `IN` comparison operator instead of `=` to match against multiple values.
|
||||
|
||||
You can use two different syntaxes:
|
||||
|
||||
`$<varname>` Example with a template variable named `hostname`:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
atimestamp as time,
|
||||
aint as value
|
||||
FROM table
|
||||
WHERE $__timeFilter(atimestamp) and hostname in($hostname)
|
||||
ORDER BY atimestamp ASC
|
||||
```
|
||||
|
||||
`[[varname]]` Example with a template variable named `hostname`:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
atimestamp as time,
|
||||
aint as value
|
||||
FROM table
|
||||
WHERE $__timeFilter(atimestamp) and hostname in([[hostname]])
|
||||
ORDER BY atimestamp ASC
|
||||
```
|
||||
|
||||
#### Disabling quoting for multi-value variables
|
||||
|
||||
Grafana automatically formats multi-value variables as a quoted, comma-separated string. For example, if `server01` and `server02` are selected, they are formatted as `'server01'`, `'server02'`. To remove the quotes, enable the CSV formatting option for the variables:
|
||||
|
||||
`${servers:csv}`
|
||||
|
||||
Read more about variable formatting options in the [Variables](ref:variable-syntax-advanced-variable-format-options) documentation.
|
||||
|
||||
## Annotations
|
||||
|
||||
[Annotations](ref:annotate-visualizations) allow you to overlay rich event information on top of graphs. Add annotation queries via the **Dashboard settings > Annotations view**.
|
||||
|
||||
**Example query using a `time` column with epoch values:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
epoch_time as time,
|
||||
metric1 as text,
|
||||
concat_ws(', ', metric1::text, metric2::text) as tags
|
||||
FROM
|
||||
public.test_data
|
||||
WHERE
|
||||
$__unixEpochFilter(epoch_time)
|
||||
```
|
||||
|
||||
**Example region query using `time` and `timeend` columns with epoch values:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
epoch_time as time,
|
||||
epoch_time_end as timeend,
|
||||
metric1 as text,
|
||||
concat_ws(', ', metric1::text, metric2::text) as tags
|
||||
FROM
|
||||
public.test_data
|
||||
WHERE
|
||||
$__unixEpochFilter(epoch_time)
|
||||
```
|
||||
|
||||
**Example query using a `time` column with a native SQL date/time data type:**
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
native_date_time as time,
|
||||
metric1 as text,
|
||||
concat_ws(', ', metric1::text, metric2::text) as tags
|
||||
FROM
|
||||
public.test_data
|
||||
WHERE
|
||||
$__timeFilter(native_date_time)
|
||||
```
|
||||
|
||||
| Name | Description |
|
||||
| --------- | --------------------------------------------------------------------------------------------------------------------- |
|
||||
| `time` | The name of the date/time field, which can be a column with a native SQL date/time data type or epoch value. |
|
||||
| `timeend` | Optional name of the end date/time field, which can be a column with a native SQL date/time data type or epoch value. |
|
||||
| `text` | Event description field. |
|
||||
| `tags` | Optional field name to use for event tags as a comma-separated string. |
|
||||
|
||||
## Alerting
|
||||
|
||||
Use time series queries to create alerts. Table formatted queries aren't yet supported in alert rule conditions.
|
||||
|
||||
For more information regarding alerting refer to the following:
|
||||
|
||||
- [Alert rules](ref:alert-rules)
|
||||
- [Template annotations and labels](ref:template-annotations-and-labels)
|
Reference in New Issue
Block a user