Skip to content

Sorted-Set based implementation #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions redis-timeseries-sorted-set.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
require 'base64'

class RedisTimeSeries
def initialize(prefix,timestep,redis)
@prefix = prefix
@timestep = timestep
@redis = redis
end

def normalize_time(t)
t = t.to_i
t - (t % @timestep)
end

def getkey(t)
"ts:#{@prefix}:#{normalize_time t}"
end

def add(data,timestamp=nil,marshal=true)
timestamp ||= Time.now.to_f
data = marshal ? Marshal.dump(data) : data
@redis.zadd(getkey(timestamp), timestamp, data)
end

def fetch_range(begin_time,end_time,marshal=true)
begin_time = begin_time.to_f
end_time = end_time.to_f
result = (0..((end_time - begin_time) / @timestep)).collect do |i|
key = getkey(begin_time + (i*@timestep))

r = @redis.zrangebyscore(key, begin_time.to_f,end_time.to_f)
marshal ? r.collect{|elem| Marshal.load(elem) } : r
end
result.flatten
end

def fetch_timestep(time, marshal=true)
t = time.to_f
r = @redis.zrangebyscore(getkey(time), t, t)
marshal ? r.collect{|elem| Marshal.load(elem) } : r
end
end
33 changes: 33 additions & 0 deletions sorted-set-example.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
require 'rubygems'
require 'redis'
require './redis-timeseries-sorted-set'

# To show the lib implementation here we use a timestep of just one second.
# Then we sample every 0.1 seconds, producing on average 10 samples per key.
# This way we should how multi-key range queries are working.
ts = RedisTimeSeries.new("test",1,Redis.new)

now = Time.now.to_f
puts "Adding data points: "
(0..300).each{|i|
print "#{i} "
STDOUT.flush
time = (now+(i/10.0))
ts.add({:time => time, :data => i.to_s}, time)
}
puts ""

# Get the second in the middle of our sampling.
begin_time = now+1
end_time = now+2
puts "\nGet range from #{begin_time} to #{end_time}"

ts.fetch_range(begin_time,end_time).each{|record|
puts "Record time #{record[:time]}, data #{record[:data]}"
}

# Show API to get a single timestep
puts "\nGet a single timestep near #{begin_time}"
ts.fetch_timestep(begin_time).each{|record|
puts "Record time #{record[:time]}, data #{record[:data]}"
}