使用 Flux 查询 InfluxDB
本指南将引导您了解使用 Flux 从 InfluxDB 查询数据的基本知识。每个 Flux 查询都需要以下内容
1. 定义您的数据源
Flux 的 from()
函数定义了一个 InfluxDB 数据源。它需要一个 bucket
参数。以下示例使用 example-bucket
作为 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 记录。该记录作为 r
传递到谓词函数中,并在其中使用 谓词表达式 进行评估。
评估结果为 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 查询可以通过多种方式扩展以形成强大的脚本。
此页是否对您有帮助?
感谢您的反馈!
支持与反馈
感谢您成为我们社区的一份子!我们欢迎并鼓励您提供关于 InfluxDB 和本文档的反馈和错误报告。如需寻求支持,请使用以下资源
拥有年度合同或支持合同的客户可以联系 InfluxData 支持。