Query InfluxDB with Flux

  1. A time range

Flux’s from() function defines an InfluxDB data source. It requires a parameter. The following examples use as the bucket name.

Flux requires a time range when querying time series data. “Unbounded” queries are very resource-intensive and as a protective measure, Flux will not query the database without a specified range.

Use the pipe-forward operator (|>) to pipe data from your data source into , which specifies a time range for your query. It accepts two parameters: start and stop. Start and stop values can be relative using negative durations or absolute using .

Example relative time ranges
  1. // Relative time range with start only. Stop defaults to now.
  2. from(bucket:"example-bucket")
  3. |> range(start: -1h)
  4. // Relative time range with start and stop
  5. from(bucket:"example-bucket")

Relative ranges are relative to “now.”

Example absolute time range

Use the following:

  1. from(bucket:"example-bucket")
  2. |> range(start: -15m)

Pass your ranged data into filter() to narrow results based on data attributes or columns. filter() has one parameter, fn, which expects a evaluates rows by column values.

filter() iterates over every input row and structures row data as a Flux record. The record is passed into the predicate function as r where it is evaluated using .

Rows that evaluate to false are dropped from the output data. Rows that evaluate to persist in the output data.

Use the following:

For this example, filter by the cpu measurement, usage_system field, and cpu-total tag value:

  1. from(bucket: "example-bucket")
  2. |> range(start: -15m)
  3. |> filter(fn: (r) => r._measurement == "cpu" and r._field == "usage_system" and r.cpu == "cpu-total")

Flux automatically assumes a yield() function at the end of each script to output and visualize the data. Explicitly calling yield() is only necessary when including multiple queries in the same Flux query. Each set of returned data needs to be named using the yield() function.

You have now queried data from InfluxDB using Flux.

The query shown here is a basic example. Flux queries can be extended in many ways to form powerful scripts.

Transform data with Flux