Documentation

使用Flux查询InfluxDB

本指南将介绍如何使用Flux从InfluxDB查询数据的基础知识。每个Flux查询都需要以下内容:

  1. 数据源
  2. 时间范围
  3. 数据过滤器

1. 定义您的数据源

Flux的 from() 函数定义了一个InfluxDB数据源。 需要一个 bucket 参数。 以下示例使用 example-bucket 作为桶名称。

from(bucket:"example-bucket")

2. 指定时间范围

Flux 查询时间序列数据时需要一个时间范围。“无界”查询非常消耗资源,作为一种保护措施,Flux 不会在没有指定范围的情况下查询数据库。

使用管道转发操作符(|>)将数据从数据源传输到range(),它指定查询的时间范围。它接受两个参数:startstop。开始和结束值可以使用负持续时间相对值或使用时间戳绝对值。

示例相对时间范围
// Relative time range with start only. Stop defaults to now.
from(bucket:"example-bucket")
    |> range(start: -1h)

// Relative time range with start and stop
from(bucket:"example-bucket")
    |> range(start: -1h, stop: -10m)

相对范围是相对于“现在”。

示例绝对时间范围
from(bucket:"example-bucket")
    |> range(start: 2021-01-01T00:00:00Z, stop: 2021-01-01T12:00:00Z)

使用以下内容:

对于本指南,使用相对时间范围 -15m 来限制查询结果为过去 15 分钟的数据:

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

3. 过滤你的数据

将您的范围数据传递到 filter() 中,以根据数据属性或列缩小结果。 filter() 有一个参数, fn,它期望一个 谓词函数 根据列值评估行。

filter() 在每一行输入上进行迭代,并将行数据结构化为一个 Flux record。 该记录作为 r 传递给谓词函数,在那里使用 predicate expressions 进行评估。

评估为 false 的行将从输出数据中删除。
评估为 true 的行将保留在输出数据中。

// Pattern
(r) => (r.recordProperty comparisonOperator comparisonExpression)

// Example with single filter
(r) => (r._measurement == "cpu")

// Example with multiple filters
(r) => (r._measurement == "cpu" and r._field != "usage_system")

使用以下内容:

对于这个例子,按 cpu 测量、 usage_system 字段和 cpu-total 标签值过滤:

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

4. 提交您查询的数据

yield() 输出查询的结果。

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

Flux 自动假定在每个脚本的末尾有一个 yield() 函数来输出和可视化数据。 仅在同一个 Flux 查询中包含多个查询时,显式调用 yield() 是必要的。 每组返回的数据需要使用 yield() 函数命名。

恭喜!

您现在已使用 Flux 从 InfluxDB 查询数据。

这里显示的查询是一个基本示例。Flux 查询可以通过多种方式扩展,以形成强大的脚本。



Flux的未来

Flux 正在进入维护模式。您可以像现在一样继续使用它,而无需对您的代码进行任何更改。

阅读更多

InfluxDB 3 开源版本现已公开Alpha测试

InfluxDB 3 Open Source is now available for alpha testing, licensed under MIT or Apache 2 licensing.

我们将发布两个产品作为测试版的一部分。

InfluxDB 3 核心,是我们新的开源产品。 它是一个用于时间序列和事件数据的实时数据引擎。 InfluxDB 3 企业版是建立在核心基础之上的商业版本,增加了历史查询能力、读取副本、高可用性、可扩展性和细粒度安全性。

有关如何开始的更多信息,请查看:

由TSM驱动的InfluxDB Cloud