Skip to content

Query methods

Vladimir Dementyev edited this page Oct 11, 2015 · 5 revisions

Influxer provides an ActiveRecord-style way to work with InfluxDB.

Basic functions

class Metrics < Influxer::Metrics
  set_series :data
end

# by default metrics return all points
Metrics.all #=> select * from data

# you can specify fields to select (or aggregations)
# 'select' method accepts array of columns or string 
Metrics.select(:time, :user_id) #=> select time, user_id from data
Metrics.select("mean(cpu_load), count(cpu_load)") #=> select mean(cpu_load), count(cpu_load) from data

# filter data using 'where' or 'where.not' (or simply 'not')
Metrics.where(user_id: 1) #=> select * from data where user_id=1
Metrics.where.not(user_id: 1) #=> select * from data where user_id<>1

# 'where' supports regexp values
Metrics.where(page_id: /^home\/.*/) #=> select * from data where page_id=~/^home\/.*/.

# range values (including Date ranges)
Metrics.where(time: Time.zone.yesterday..Time.zone.today) #=> select * from data where time > ... and time < ...

# array values
Metrics.where(user_id: [1,2]) #=> select * from data where (user_id=1 or user_id=2)

# and of course string values
Metrics.where("user_id > 1") #=> select * from data where user_id>1

# other usual SQL functions
Metrics.group(:user_id).limit(10) #=> select * from data group by user_id limit 10

# and calculations methods
Metrics.time(:h).count("distinct(user_id)").mean(:req_time)
#=> select count(distinct(user_id)), mean(req_time) from data group by time(1h)

# with aliases
Metrics.past(:h).percentile(:val, 80, 'p1').percentile(:val, 90, 'p90')
#=> select percentile(val,80) as p80, percentile(val,90) as p90 from data where time > now() - 1h

# order
Metrics.order(cpu: :desc) #=> select * from data order by cpu desc

# or with raw string
Metrics.order('cpu desc, memory high') #=> select * from data order by cpu desc, memory high

Special functions

Since we working with time series data it would be great to have some special query functions.

# 'time' is a shorthand to group by time
# it supports predefined symbol values as long as custom string values
Metrics.time(:hour) #=> select * from data group by time(1h)
Metrics.time("3d") #=> select * from data group by time(3d)
   
# use 'fill' to fill the gaps
Metrics.time(:w).fill(0) #=> select * from data group by time(1w) fill(0)

# use 'past' to load points relative to current time 
Metrics.past(:hour) #=> select * from data where time > now() - 1h

# use 'since' to load data since specified date
Metrics.since(Time.utc(2014,12,31)) => # select * ... where time > 1419984000s

If you do not need denormalized result use normalized method:

Metrics.time(:h).limit(10).normalized #=> [{ "name" => "data", "columns" => [...], "values" => [...] }]
Clone this wiki locally