@@ -236,13 +236,27 @@ def query_flux(unit, unique_id,
236236
237237 if group_sec :
238238 # Bug in influxdb/Flux v1.8.10 due to mean, but 1.x is EOL so won't be fixed
239- # Workaround is to query all measurements, then simulate aggregateWindow with mean for 1.x
239+ # Original workaround was to query all measurements, then simulate aggregateWindow with mean for 1.x
240240 # Error: panic: runtime error: invalid memory address or nil pointer dereference
241241 # https://github.com/influxdata/influxdb/issues/21649
242242 # https://github.com/influxdata/influxdb/pull/23520
243243 if settings .measurement_db_version == '2' :
244+ # Safe to use aggregateWindow with mean on InfluxDB 2.x
244245 query += f' |> aggregateWindow(every: { group_sec } s, fn: mean)'
245-
246+ elif settings .measurement_db_version == '1' and not value :
247+ # For InfluxDB 1.x, avoid aggregateWindow(mean) and perform windowing via window() + reduce().
248+ # This computes a per-window mean server-side to avoid transferring all raw points.
249+ query += (
250+ f' |> window(every: { group_sec } s)'
251+ ' |> reduce('
252+ 'identity: {sum: 0.0, count: 0}, '
253+ 'fn: (r, accumulator) => ({'
254+ 'sum: accumulator.sum + r._value, '
255+ 'count: accumulator.count + 1'
256+ '})'
257+ ')'
258+ ' |> map(fn: (r) => ({ _time: r._stop, _value: r.sum / float(v: r.count) }))'
259+ )
246260 if limit :
247261 query += f' |> limit(n:{ limit } )'
248262
0 commit comments