Flux query: Get number of fields

I have a measurement with dynamic field names. So my measurement is called “deviceStatus” and my fields are “device1”, “device23” and so on. The device ids are not in ascending order, but can randomly appear and disappear.

I would like to do a simple query that gives me the number of devices for which the deviceStatus measurement is available within the time range.

I can do a query that basically combines last() and count() so I get the number if there is any field available. The problem is, if there is none, I get no result. I would need to have the result 0 instead.

Is it possible?

In other words, what I am asking for is a row count.

Hello @ypnos,
You should be aware of the schema package:

import "influxdata/influxdb/schema"

schema.fieldKeys(
  bucket: "airsensor",
  predicate: (r) => true,
  start: -1d
)
|> count() 

Here’s a full function that can give you your field values count or return a table with 0:

import "array"
import "influxdata/influxdb/schema"

my_start = -1d 
existFieldsRecord = 
schema.fieldKeys(
  bucket: "airsensor",
  predicate: (r) => true,
  start: my_start
)
|> count() 
|> findRecord(fn: (key) => true, idx: 0)

x = (existFieldsValue, myStart) => { 

fieldCountTable = from(bucket: "airsensor")
|> range(start: myStart)
|> filter(fn: (r) => r._field == "temperature") 
|> last() 
|> count()

noneTable = array.from(rows: [{_time: 2020-01-01T00:00:00Z, _value: "no fields"}])

out = if existFieldsValue > 0.0 then fieldCountTable 
          else noneTable

return out 
} 

x(existFieldsValue:existFieldsRecord._value, myStart: my_start)

Please let me know if that helps.