Class: Redis::SortedSet

Inherits:
Object
  • Object
show all
Includes:
Helpers::CoreCommands, Helpers::Serialize
Defined in:
lib/redis/sorted_set.rb

Overview

Class representing a sorted set.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers::Serialize

#from_redis, #to_redis

Methods included from Helpers::CoreCommands

#exists?, #expire, #expireat, #move, #rename, #renamenx, #type

Constructor Details

#initialize(key, *args) ⇒ SortedSet

Create a new SortedSet.



16
17
18
19
20
# File 'lib/redis/sorted_set.rb', line 16

def initialize(key, *args)
  @key = key.is_a?(Array) ? key.flatten.join(':') : key
  @options = args.last.is_a?(Hash) ? args.pop : {}
  @redis = args.first || $redis
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



13
14
15
# File 'lib/redis/sorted_set.rb', line 13

def key
  @key
end

#optionsObject (readonly)

Returns the value of attribute options.



13
14
15
# File 'lib/redis/sorted_set.rb', line 13

def options
  @options
end

#redisObject (readonly)

Returns the value of attribute redis.



13
14
15
# File 'lib/redis/sorted_set.rb', line 13

def redis
  @redis
end

Instance Method Details

#==(x) ⇒ Object



237
238
239
# File 'lib/redis/sorted_set.rb', line 237

def ==(x)
  members == x
end

#[](index, length = nil) ⇒ Object

Same functionality as Ruby arrays. If a single number is given, return just the element at that index using Redis: ZRANGE. Otherwise, return a range of values using Redis: ZRANGE.



39
40
41
42
43
44
45
46
47
# File 'lib/redis/sorted_set.rb', line 39

def [](index, length=nil)
  if index.is_a? Range
    range(index.first, index.last)
  elsif length
    range(index, length)
  else
    score(index)
  end
end

#[]=(member, score) ⇒ Object

How to add values using a sorted set. The key is the member, eg, “Peter”, and the value is the score, eg, 163. So:

num_posts['Peter'] = 163


25
26
27
# File 'lib/redis/sorted_set.rb', line 25

def []=(member, score)
  add(member, score)
end

#add(member, score) ⇒ Object

Add a member and its corresponding value to Redis. Note that the arguments to this are flipped; the member comes first rather than the score, since the member is the unique item (not the score).



32
33
34
# File 'lib/redis/sorted_set.rb', line 32

def add(member, score)
  redis.zadd(key, score, to_redis(member))
end

#at(index) ⇒ Object

Return the value at the given index. Can also use familiar list syntax. Redis: ZRANGE



247
248
249
# File 'lib/redis/sorted_set.rb', line 247

def at(index)
  range(index, index).first
end

#decrement(by = 1) ⇒ Object Also known as: decr, decrby

Convenience to calling increment() with a negative number.



154
155
156
# File 'lib/redis/sorted_set.rb', line 154

def decrement(by=1)
  redis.zincrby(key, -by).to_i
end

#delete(value) ⇒ Object

Delete the value from the set. Redis: ZREM



141
142
143
# File 'lib/redis/sorted_set.rb', line 141

def delete(value)
  redis.zrem(key, value)
end

#difference(*sets) ⇒ Object Also known as: diff, ^, -

Return the difference vs another set. Can pass it either another set object or set name. Also available as ^ or - which is a bit cleaner:

members_difference = set1 ^ set2
members_difference = set1 - set2

If you want to specify multiple sets, you must use difference:

members_difference = set1.difference(set2, set3, set4)
members_difference = set1.diff(set2, set3, set4)

Redis: SDIFF



219
220
221
# File 'lib/redis/sorted_set.rb', line 219

def difference(*sets)
  from_redis redis.zdiff(key, *keys_from_objects(sets))
end

#diffstore(name, *sets) ⇒ Object

Calculate the diff and store it in Redis as name. Returns the number of elements in the stored union. Redis: SDIFFSTORE



228
229
230
# File 'lib/redis/sorted_set.rb', line 228

def diffstore(name, *sets)
  redis.zdiffstore(name, key, *keys_from_objects(sets))
end

#empty?Boolean

Returns true if the set has no members. Redis: SCARD == 0

Returns:

  • (Boolean)


233
234
235
# File 'lib/redis/sorted_set.rb', line 233

def empty?
  length == 0
end

#firstObject

Return the first element in the list. Redis: ZRANGE(0)



252
253
254
# File 'lib/redis/sorted_set.rb', line 252

def first
  at(0)
end

#increment(member, by = 1) ⇒ Object Also known as: incr, incrby

Increment the rank of that member atomically and return the new value. This method is aliased as incr() for brevity. Redis: ZINCRBY



147
148
149
# File 'lib/redis/sorted_set.rb', line 147

def increment(member, by=1)
  redis.zincrby(key, by, member).to_i
end

#intersection(*sets) ⇒ Object Also known as: intersect, inter, &

Return the intersection with another set. Can pass it either another set object or set name. Also available as & which is a bit cleaner:

members_in_both = set1 & set2

If you want to specify multiple sets, you must use intersection:

members_in_all = set1.intersection(set2, set3, set4)
members_in_all = set1.inter(set2, set3, set4)  # alias

Redis: SINTER



171
172
173
# File 'lib/redis/sorted_set.rb', line 171

def intersection(*sets)
  from_redis redis.zinter(key, *keys_from_objects(sets))
end

#interstore(name, *sets) ⇒ Object

Calculate the intersection and store it in Redis as name. Returns the number of elements in the stored intersection. Redis: SUNIONSTORE



180
181
182
# File 'lib/redis/sorted_set.rb', line 180

def interstore(name, *sets)
  redis.zinterstore(name, key, *keys_from_objects(sets))
end

#lastObject

Return the last element in the list. Redis: ZRANGE(-1)



257
258
259
# File 'lib/redis/sorted_set.rb', line 257

def last
  at(-1)
end

#lengthObject Also known as: size

The number of members in the set. Aliased as size. Redis: ZCARD



262
263
264
# File 'lib/redis/sorted_set.rb', line 262

def length
  redis.zcard(key)
end

#members(options = {}) ⇒ Object

Return all members of the sorted set with their scores. Extremely CPU-intensive. Better to use a range instead.



70
71
72
# File 'lib/redis/sorted_set.rb', line 70

def members(options={})
  range(0, -1, options)
end

#range(start_index, end_index, options = {}) ⇒ Object

Return a range of values from start_index to end_index. Can also use the familiar list Ruby syntax. Redis: ZRANGE



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/redis/sorted_set.rb', line 76

def range(start_index, end_index, options={})
  if options[:withscores]
    val = from_redis redis.zrange(key, start_index, end_index, 'withscores')
    ret = []
    while k = val.shift and v = val.shift
      ret << [k, v.to_f]
    end
    ret
  else
    from_redis redis.zrange(key, start_index, end_index)
  end
end

#rangebyscore(min, max, options = {}) ⇒ Object

Return the all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max). Options:

:count, :offset - passed to LIMIT
:withscores     - if true, scores are returned as well

Redis: ZRANGEBYSCORE



108
109
110
111
112
113
114
# File 'lib/redis/sorted_set.rb', line 108

def rangebyscore(min, max, options={})
  args = []
  args += ['limit', options[:offset] || 0, options[:limit] || options[:count]] if
            options[:offset] || options[:limit] || options[:count]
  args += ['withscores'] if options[:withscores]
  from_redis redis.zrangebyscore(key, min, max, *args)
end

#rank(member) ⇒ Object

Return the rank of the member in the sorted set, with scores ordered from low to high. revrank returns the rank with scores ordered from high to low. When the given member does not exist in the sorted set, nil is returned. The returned rank (or index) of the member is 0-based for both commands



60
61
62
# File 'lib/redis/sorted_set.rb', line 60

def rank(member)
  redis.zrank(key, to_redis(member)).to_i
end

#remrangebyrank(min, max) ⇒ Object

Remove all elements in the sorted set at key with rank between start and end. Start and end are 0-based with rank 0 being the element with the lowest score. Both start and end can be negative numbers, where they indicate offsets starting at the element with the highest rank. For example: -1 is the element with the highest score, -2 the element with the second highest score and so forth. Redis: ZREMRANGEBYRANK



130
131
132
# File 'lib/redis/sorted_set.rb', line 130

def remrangebyrank(min, max)
  redis.zremrangebyrank(key, min, max)
end

#remrangebyscore(min, max) ⇒ Object

Remove all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max). Redis: ZREMRANGEBYSCORE



136
137
138
# File 'lib/redis/sorted_set.rb', line 136

def remrangebyscore(min, max)
  redis.zremrangebyscore(key, min, max)
end

#revrange(start_index, end_index, options = {}) ⇒ Object

Return a range of values from start_index to end_index in reverse order. Redis: ZREVRANGE



90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/redis/sorted_set.rb', line 90

def revrange(start_index, end_index, options={})
  if options[:withscores]
    val = from_redis redis.zrevrange(key, start_index, end_index, 'withscores')
    ret = []
    while k = val.shift and v = val.shift
      ret << [k, v.to_f]
    end
    ret
  else
    from_redis redis.zrevrange(key, start_index, end_index)
  end
end

#revrangebyscore(min, max, options = {}) ⇒ Object

Forwards compat (not yet implemented in Redis)



117
118
119
120
121
122
123
# File 'lib/redis/sorted_set.rb', line 117

def revrangebyscore(min, max, options={})
  args = []
  args += ['limit', options[:offset] || 0, options[:limit] || options[:count]] if
            options[:offset] || options[:limit] || options[:count]
  args += ['withscores'] if options[:withscores]
  from_redis redis.zrevrangebyscore(key, min, max, *args)
end

#revrank(member) ⇒ Object



64
65
66
# File 'lib/redis/sorted_set.rb', line 64

def revrank(member)
  redis.zrevrank(key, to_redis(member)).to_i
end

#score(member) ⇒ Object

Return the score of the specified element of the sorted set at key. If the specified element does not exist in the sorted set, or the key does not exist at all, nil is returned. Redis: ZSCORE.



52
53
54
# File 'lib/redis/sorted_set.rb', line 52

def score(member)
  redis.zscore(key, to_redis(member)).to_f
end

#to_sObject



241
242
243
# File 'lib/redis/sorted_set.rb', line 241

def to_s
  members.join(', ')
end

#union(*sets) ⇒ Object Also known as: |, +

Return the union with another set. Can pass it either another set object or set name. Also available as | and + which are a bit cleaner:

members_in_either = set1 | set2
members_in_either = set1 + set2

If you want to specify multiple sets, you must use union:

members_in_all = set1.union(set2, set3, set4)

Redis: SUNION



195
196
197
# File 'lib/redis/sorted_set.rb', line 195

def union(*sets)
  from_redis redis.zunion(key, *keys_from_objects(sets))
end

#unionstore(name, *sets) ⇒ Object

Calculate the union and store it in Redis as name. Returns the number of elements in the stored union. Redis: SUNIONSTORE



203
204
205
# File 'lib/redis/sorted_set.rb', line 203

def unionstore(name, *sets)
  redis.zunionstore(name, key, *keys_from_objects(sets))
end