You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flux查询中按小时统计布尔值真假数量且保留其他字段

完整实现代码

from(bucket: "xxx")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> window(every: 1h)
  |> filter(fn: (r) => r["_measurement"] == "xxx")
  |> filter(fn: (r) => r["_field"] == "myBoolField")
  // 分组时加入需要保留的其他字段,作为分组键聚合后自动保留
  |> group(columns: ["_stop", "otherfield1", "otherfield2"])
  // 转换布尔值为可统计的数值
  |> map(fn: (r) => ({ r with
    nbTrue: if r._value == true then 1 else 0,
    nbFalse: if r._value == false then 1 else 0
  }))
  // 按分组聚合统计
  |> reduce(
    fn: (r, accumulator) => ({
      _stop: r._stop,
      otherfield1: r.otherfield1,
      otherfield2: r.otherfield2,
      total: accumulator.total + 1,
      nbTrue: accumulator.nbTrue + r.nbTrue,
      nbFalse: accumulator.nbFalse + r.nbFalse
    }),
    identity: {total: 0, nbTrue: 0, nbFalse: 0, _stop: "", otherfield1: "", otherfield2: ""}
  )
  // 重命名总条数列匹配你期望的_value字段名
  |> rename(columns: {total: "_value"})
  // 调整列顺序符合输出要求
  |> keep(columns: ["_stop", "_value", "nbFalse", "nbTrue", "otherfield1", "otherfield2"])

可选简化写法(不用reduce)

如果觉得reduce写法繁琐,也可以用sum+count组合实现相同效果,前面的group、map步骤保持不变,替换reduce部分即可:

|> count(column: "_value")
|> sum(columns: ["nbTrue", "nbFalse"])
|> rename(columns: {_value: "_value"})

注意事项

如果同一小时窗口内otherfield1、otherfield2存在多个不同值,可以根据实际需求调整聚合逻辑,比如取窗口最后一条的值、去重拼接等。


内容的提问来源于stack exchange,提问作者Christophe Blin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 06:06:03