使用Flux查询InfluxDB
本指南将介绍如何使用Flux从InfluxDB查询数据的基础知识。每个Flux查询都需要以下内容:
1. 定义您的数据源
Flux的 from() 函数定义了一个InfluxDB数据源。 需要一个 bucket 参数。 以下示例使用 example-bucket 作为桶名称。
from(bucket:"example-bucket")
2. 指定时间范围
Flux 查询时间序列数据时需要一个时间范围。“无界”查询非常消耗资源,作为一种保护措施,Flux 不会在没有指定范围的情况下查询数据库。
使用管道转发操作符(|>)将数据从数据源传输到range(),它指定查询的时间范围。它接受两个参数:start和stop。开始和结束值可以使用负持续时间的相对值或使用时间戳的绝对值。
示例相对时间范围
// 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 查询可以通过多种方式扩展,以形成强大的脚本。