InfluxDB 2.0 查询结果,pivot 使一个 table 包含多个 field

发布时间: 2021-06-17 18:38:43 作者: 大象笔记

我的需求

在 Antd Pro 后台 table 列表,每行数据对应 InfluxDB 一个 measurement tag 一个时间点所有 field 数据。

例如:

一行数据为,一个网站指定网页在某一分钟的 UV,PV。下一行数据为下一分钟的相应数据。

InfluxDB 2.0 默认的返回 table 是怎样的

先写入测试数据,假设 org 为 sunzhongwei.com,bucket 也是 sunzhongwei.com。

里面的:

influx write \
  -b sunzhongwei.com \
  -o sunzhongwei.com \
  'sunzhongwei.com,page=home uv=2,pv=10'

influx write \
  -b sunzhongwei.com \
  -o sunzhongwei.com \
  'sunzhongwei.com,page=tool uv=20,pv=110'

influx write \
  -b sunzhongwei.com \
  -o sunzhongwei.com \
  'google.com,page=home uv=200,pv=10000'

直接查询的话

from(bucket: "sunzhongwei.com")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)

会发现查询结果被分割成了6个 table, 如图 (InfluxDB UI 后台):

可以看出,查询结果会根据不同的 measurement 和 tag, field 组合,每一个组合对应一个新的 table。

每个 table 中是:

pivot 使 table 包含多个 field

from(bucket: "sunzhongwei.com")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> pivot(
    rowKey:["_time"],
    columnKey: ["_field"],
    valueColumn: "_value"
  )

此时会看到查询结果由6个 table 变成了 3 个:

pv, uv 变成了 table 中的 field name。

正是我想要的效果。

pivot

pivot 中文翻译为:旋转运动 ... 😭

The pivot() function collects values stored vertically (column-wise) in a table and aligns them horizontally (row-wise) into logical sets.

总结

InfluxDB 2.0 的资料还是非常少,英文的都很难查到,更不要说中文的。

还是需要把官方文档粗略地翻一遍。

参考

我是一名山东烟台的开发者,联系作者