Flux - How to Handle Division by Zero

Hi I am trying to do a simple success rate calculation between metrics. By dividing the number of successful requests by the number of attempts. The problem is some intervals are empty where both metrics are 0. When I write the query I get the below “cannot divide by zero” runtime error. In SQL there a NULLIF function to avoid this. Is there something similar in flux or is there an alternate method to avoid division by zero?

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

My Sample Query:

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 Paging_SR: r.RequestSuccess_E/r.RequestAttempt }))

Thanks in advance.

@mbasith You could use some simple conditional logic to check the values of ReqeustSuccess_E and RequestAttempt. You can check if they’re null or 0. You do need to provide a default value for when the operands or null or zero because you can’t map a null value.

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
      Paging_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 
  }))
3 Likes

@scott, that worked great. This is some cool added flexibility. Thanks for the help.

1 Like