InfluxDB 2.0 Flux - 如何处理被零除

InfluxDB 2.0 Flux - How to Handle Division by Zero

您好,我正在尝试计算指标之间的简单成功率。通过将成功请求的次数除以尝试次数。问题是一些间隔是空的,其中两个指标都是 0。当我编写查询时,我得到下面的“不能被零除”运行时错误。在 SQL 中有一个 NULLIF 函数可以避免这种情况。是否有类似的通量或者是否有替代方法来避免被零除?

错误:runtime error @7:6-7:90: map: failed to evaluate map function: cannot divide by zero

我的示例查询:

from(bucket: "my_db")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "HTTPRequests")
  |> filter(fn: (r) => r["_field"] == "RequestAttempt" or r["_field"] == "RequestSuccess_E")
  |> filter(fn: (r) => r["host"] == "host-a")
  |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
  |> map(fn: (r) => ({ r with Request_SR: r.RequestSuccess_E/r.RequestAttempt }))

提前致谢。

Influx 团队回答了我的问题。这对我的情况有效。

您可以使用一些简单的条件逻辑来检查 ReqeustSuccess 和 RequestAttempt 的值。您可以检查它们是否为空或 0。您确实需要为操作数为空或零时提供默认值,因为您无法映射空值。

from(bucket: "my_db")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "HTTPRequests")
  |> filter(fn: (r) => r["_field"] == "RequestAttempt" or r["_field"] == "RequestSuccess_E")
  |> filter(fn: (r) => r["host"] == "host-a")
  |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
  |> map(fn: (r) => ({ r with
      Request_SR:
        if not exists r.RequestSuccess_E or r.RequestSuccess_E == 0.0 then 0.0
        else if not exists r.RequestAttempt or r.RequestAttempt == 0.0 then 0.0
        else r.RequestSuccess_E / r.RequestAttempt 
  }))