Module: Redis::Commands::SortedSets

Included in:
Redis::Commands
Defined in:
lib/redis/commands/sorted_sets.rb

Instance Method Summary collapse

Instance Method Details

#bzmove(source, destination, timeout: 0, modifier: "MIN", count: nil) ⇒ nil, Array<Array<String, Float>>

Atomically move the lowest- or highest-scoring members from one sorted set to another, preserving their scores; or block until a member is available or the timeout expires.

Examples:

With timeout

redis.bzmove('src', 'dst', timeout: 1)
#=> [['a', 1.0]], or nil on timeout

Move up to 3 of the highest-scoring members as soon as any is available

redis.bzmove('src', 'dst', modifier: 'MAX', count: 3)

Parameters:

  • source (String) —

    source key

  • destination (String) —

    destination key

  • timeout (Float, Integer) (defaults to: 0) —

    seconds to block, 0 blocks indefinitely

  • modifier (String) (defaults to: "MIN") —

    which members to move, "MIN" (default) or "MAX"

  • count (Integer) (defaults to: nil) —

    move at most count members once at least one is available

Returns:

  • (nil, Array<Array<String, Float>>) —

    the moved [member, score] pairs, or nil when the timeout expired and nothing was moved

Raises:

  • (ArgumentError)

See Also:



297
298
299
300
301
302
303
304
# File 'lib/redis/commands/sorted_sets.rb', line 297

def bzmove(source, destination, timeout: 0, modifier: "MIN", count: nil)
  raise ArgumentError, "Pick either MIN or MAX" unless modifier == "MIN" || modifier == "MAX"

  args = [:bzmove, source, destination, modifier, timeout]
  args << "COUNT" << Integer(count) if count

  send_blocking_command(args, timeout, &FloatifyPairs)
end

#bzmpop(timeout, *keys, modifier: "MIN", count: nil) ⇒ Array<String, Array<String, Float>>

Removes and returns up to count members with scores in the sorted set stored at key.

Examples:

Popping a member

redis.bzmpop('zset')
#=> ['zset', ['a', 1.0]]

With count option

redis.bzmpop('zset', count: 2)
#=> ['zset', [['a', 1.0], ['b', 2.0]]

Returns:

  • (Array<String, Array<String, Float>>) —

    list of popped elements and scores

Raises:

  • (ArgumentError)


188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/redis/commands/sorted_sets.rb', line 188

def bzmpop(timeout, *keys, modifier: "MIN", count: nil)
  raise ArgumentError, "Pick either MIN or MAX" unless modifier == "MIN" || modifier == "MAX"

  args = [:bzmpop, timeout, keys.size, *keys, modifier]
  args << "COUNT" << Integer(count) if count

  send_blocking_command(args, timeout) do |response|
    response&.map do |entry|
      case entry
      when String then entry
      when Array then entry.map { |pair| FloatifyPairs.call(pair) }.flatten(1)
      end
    end
  end
end

#bzpopmax(*args) ⇒ Array<String, String, Float>?

Removes and returns up to count members with the highest scores in the sorted set stored at keys, or block until one is available.

Examples:

Popping a member from a sorted set

redis.bzpopmax('zset', 1)
#=> ['zset', 'b', 2.0]

Popping a member from multiple sorted sets

redis.bzpopmax('zset1', 'zset2', 1)
#=> ['zset1', 'b', 2.0]

Returns:

  • (Array<String, String, Float>) —

    a touple of key, member and score

  • (nil) —

    when no element could be popped and the timeout expired



352
353
354
355
356
# File 'lib/redis/commands/sorted_sets.rb', line 352

def bzpopmax(*args)
  _bpop(:bzpopmax, args) do |reply|
    reply.is_a?(Array) ? [reply[0], reply[1], Floatify.call(reply[2])] : reply
  end
end

#bzpopmin(*args) ⇒ Array<String, String, Float>?

Removes and returns up to count members with the lowest scores in the sorted set stored at keys, or block until one is available.

Examples:

Popping a member from a sorted set

redis.bzpopmin('zset', 1)
#=> ['zset', 'a', 1.0]

Popping a member from multiple sorted sets

redis.bzpopmin('zset1', 'zset2', 1)
#=> ['zset1', 'a', 1.0]

Returns:

  • (Array<String, String, Float>) —

    a touple of key, member and score

  • (nil) —

    when no element could be popped and the timeout expired



373
374
375
376
377
# File 'lib/redis/commands/sorted_sets.rb', line 373

def bzpopmin(*args)
  _bpop(:bzpopmin, args) do |reply|
    reply.is_a?(Array) ? [reply[0], reply[1], Floatify.call(reply[2])] : reply
  end
end

#zadd(key, *args, nx: nil, xx: nil, lt: nil, gt: nil, ch: nil, incr: nil) ⇒ Boolean, ...

Add one or more members to a sorted set, or update the score for members that already exist.

Examples:

Add a single [score, member] pair to a sorted set

redis.zadd("zset", 32.0, "member")

Add an array of [score, member] pairs to a sorted set

redis.zadd("zset", [[32.0, "a"], [64.0, "b"]])

Parameters:

  • key (String)
  • args ([Float, String], Array<[Float, String]>) —
    • a single [score, member] pair
    • an array of [score, member] pairs
  • options (Hash) —
    • :xx => true: Only update elements that already exist (never add elements)
    • :nx => true: Don't update already existing elements (always add new elements)
    • :lt => true: Only update existing elements if the new score is less than the current score
    • :gt => true: Only update existing elements if the new score is greater than the current score
    • :ch => true: Modify the return value from the number of new elements added, to the total number of elements changed (CH is an abbreviation of changed); changed elements are new elements added and elements already existing for which the score was updated
    • :incr => true: When this option is specified ZADD acts like ZINCRBY; only one score-element pair can be specified in this mode

Returns:

  • (Boolean, Integer, Float) —
    • Boolean when a single pair is specified, holding whether or not it was added to the sorted set.
    • Integer when an array of pairs is specified, holding the number of pairs that were added to the sorted set.
    • Float when option :incr is specified, holding the score of the member after incrementing it.


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/redis/commands/sorted_sets.rb', line 53

def zadd(key, *args, nx: nil, xx: nil, lt: nil, gt: nil, ch: nil, incr: nil)
  command = [:zadd, key]
  command << "NX" if nx
  command << "XX" if xx
  command << "LT" if lt
  command << "GT" if gt
  command << "CH" if ch
  command << "INCR" if incr

  if args.size == 1 && args[0].is_a?(Array)
    members_to_add = args[0]
    return 0 if members_to_add.empty?

    # Variadic: return float if INCR, integer if !INCR
    send_command(command + members_to_add, &(incr ? Floatify : nil))
  elsif args.size == 2
    # Single pair: return float if INCR, boolean if !INCR
    send_command(command + args, &(incr ? Floatify : Boolify))
  else
    raise ArgumentError, "wrong number of arguments"
  end
end

#zcard(key) ⇒ Integer

Get the number of members in a sorted set.

Examples:

redis.zcard("zset")
  # => 4

Parameters:

  • key (String)

Returns:

  • (Integer)


14
15
16
# File 'lib/redis/commands/sorted_sets.rb', line 14

def zcard(key)
  send_command([:zcard, key])
end

#zcount(key, min, max) ⇒ Integer

Count the members in a sorted set with scores within the given values.

Examples:

Count members with score >= 5 and < 100

redis.zcount("zset", "5", "(100")
  # => 2

Count members with scores > 5

redis.zcount("zset", "(5", "+inf")
  # => 2

Parameters:

  • key (String)
  • min (String) —
    • inclusive minimum score is specified verbatim
    • exclusive minimum score is specified by prefixing (
  • max (String) —
    • inclusive maximum score is specified verbatim
    • exclusive maximum score is specified by prefixing (

Returns:

  • (Integer) —

    number of members in within the specified range



814
815
816
# File 'lib/redis/commands/sorted_sets.rb', line 814

def zcount(key, min, max)
  send_command([:zcount, key, min, max])
end

#zdiff(*keys, with_scores: false) ⇒ Array<String>, Array<[String, Float]>

Return the difference between the first and all successive input sorted sets

Examples:

redis.zadd("zsetA", [[1.0, "v1"], [2.0, "v2"]])
redis.zadd("zsetB", [[3.0, "v2"], [2.0, "v3"]])
redis.zdiff("zsetA", "zsetB")
  => ["v1"]

With scores

redis.zadd("zsetA", [[1.0, "v1"], [2.0, "v2"]])
redis.zadd("zsetB", [[3.0, "v2"], [2.0, "v3"]])
redis.zdiff("zsetA", "zsetB", :with_scores => true)
  => [["v1", 1.0]]

Parameters:

  • keys (String, Array<String>) —

    one or more keys to compute the difference

  • options (Hash) —
    • :with_scores => true: include scores in output

Returns:

  • (Array<String>, Array<[String, Float]>) —
    • when :with_scores is not specified, an array of members
    • when :with_scores is specified, an array with [member, score] pairs


945
946
947
# File 'lib/redis/commands/sorted_sets.rb', line 945

def zdiff(*keys, with_scores: false)
  _zsets_operation(:zdiff, *keys, with_scores: with_scores)
end

#zdiffstore(*args) ⇒ Integer

Compute the difference between the first and all successive input sorted sets and store the resulting sorted set in a new key

Examples:

redis.zadd("zsetA", [[1.0, "v1"], [2.0, "v2"]])
redis.zadd("zsetB", [[3.0, "v2"], [2.0, "v3"]])
redis.zdiffstore("zsetA", "zsetB")
  # => 1

Parameters:

  • destination (String) —

    destination key

  • keys (Array<String>) —

    source keys

Returns:

  • (Integer) —

    number of elements in the resulting sorted set



961
962
963
# File 'lib/redis/commands/sorted_sets.rb', line 961

def zdiffstore(*args)
  _zsets_operation_store(:zdiffstore, *args)
end

#zincrby(key, increment, member) ⇒ Float

Increment the score of a member in a sorted set.

Examples:

redis.zincrby("zset", 32.0, "a")
  # => 64.0

Parameters:

  • key (String)
  • increment (Float)
  • member (String)

Returns:

  • (Float) —

    score of the member after incrementing it



86
87
88
# File 'lib/redis/commands/sorted_sets.rb', line 86

def zincrby(key, increment, member)
  send_command([:zincrby, key, increment, member], &Floatify)
end

#zinter(*args) ⇒ Array<String>, Array<[String, Float]>

Return the intersection of multiple sorted sets

Examples:

Retrieve the intersection of 2*zsetA and 1*zsetB

redis.zinter("zsetA", "zsetB", :weights => [2.0, 1.0])
  # => ["v1", "v2"]

Retrieve the intersection of 2*zsetA and 1*zsetB, and their scores

redis.zinter("zsetA", "zsetB", :weights => [2.0, 1.0], :with_scores => true)
  # => [["v1", 3.0], ["v2", 6.0]]

Parameters:

  • keys (String, Array<String>) —

    one or more keys to intersect

  • options (Hash) —
    • :weights => [Float, Float, ...]: weights to associate with source sorted sets
    • :aggregate => String: aggregate function to use (sum, min, max; count since Redis 8.8)
    • :with_scores => true: include scores in output

Returns:

  • (Array<String>, Array<[String, Float]>) —
    • when :with_scores is not specified, an array of members
    • when :with_scores is specified, an array with [member, score] pairs


837
838
839
# File 'lib/redis/commands/sorted_sets.rb', line 837

def zinter(*args)
  _zsets_operation(:zinter, *args)
end

#zintercard(*keys, limit: nil) ⇒ Integer

Get the number of members in the intersection of multiple sorted sets.

Examples:

redis.zadd("zsetA", [[1, "v1"], [2, "v2"], [3, "v3"]])
redis.zadd("zsetB", [[1, "v2"], [2, "v3"], [3, "v4"]])
redis.zintercard("zsetA", "zsetB")
  # => 2

Stop counting once the intersection reaches 1 member

redis.zintercard("zsetA", "zsetB", limit: 1)
  # => 1

Parameters:

  • keys (String, Array<String>) —

    one or more keys to intersect

  • limit (Integer) (defaults to: nil) —

    stop counting once the intersection reaches limit members (0 means unlimited)

Returns:

  • (Integer) —

    number of members in the intersection



857
858
859
860
861
862
# File 'lib/redis/commands/sorted_sets.rb', line 857

def zintercard(*keys, limit: nil)
  keys.flatten!(1)
  args = [:zintercard, keys.size].concat(keys)
  args << "LIMIT" << Integer(limit) if limit
  send_command(args)
end

#zinterstore(*args) ⇒ Integer

Intersect multiple sorted sets and store the resulting sorted set in a new key.

Examples:

Compute the intersection of 2*zsetA with 1*zsetB, summing their scores

redis.zinterstore("zsetC", ["zsetA", "zsetB"], :weights => [2.0, 1.0], :aggregate => "sum")
  # => 4

Parameters:

  • destination (String) —

    destination key

  • keys (Array<String>) —

    source keys

  • options (Hash) —
    • :weights => [Array<Float>]: weights to associate with source sorted sets
    • :aggregate => String: aggregate function to use (sum, min, max; count since Redis 8.8)

Returns:

  • (Integer) —

    number of elements in the resulting sorted set



878
879
880
# File 'lib/redis/commands/sorted_sets.rb', line 878

def zinterstore(*args)
  _zsets_operation_store(:zinterstore, *args)
end

#zlexcount(key, min, max) ⇒ Integer

Count the members, with the same score in a sorted set, within the given lexicographical range.

Examples:

Count members matching a

redis.zlexcount("zset", "[a", "[a\xff")
  # => 1

Count members matching a-z

redis.zlexcount("zset", "[a", "[z\xff")
  # => 26

Parameters:

  • key (String)
  • min (String) —
    • inclusive minimum is specified by prefixing (
    • exclusive minimum is specified by prefixing [
  • max (String) —
    • inclusive maximum is specified by prefixing (
    • exclusive maximum is specified by prefixing [

Returns:

  • (Integer) —

    number of members within the specified lexicographical range



645
646
647
# File 'lib/redis/commands/sorted_sets.rb', line 645

def zlexcount(key, min, max)
  send_command([:zlexcount, key, min, max])
end

#zmove(source, destination, modifier: nil, byscore: nil, count: nil) ⇒ nil, Array<Array<String, Float>>

Atomically move members from one sorted set to another, preserving their scores.

Examples:

Move the lowest-scoring member

redis.zmove('src', 'dst')
#=> [['a', 1.0]]

Move the two highest-scoring members

redis.zmove('src', 'dst', modifier: 'MAX', count: 2)
#=> [['d', 4.0], ['c', 3.0]]

Move every member with a score in (1, 3]

redis.zmove('src', 'dst', byscore: ['(1', 3])
#=> [['b', 2.0], ['c', 3.0]]

Parameters:

  • source (String) —

    source key

  • destination (String) —

    destination key

  • modifier (String) (defaults to: nil) —

    which members to move, "MIN" (default) or "MAX"; not allowed together with byscore

  • byscore (Array<String, Numeric>) (defaults to: nil) —

    [min, max] score range to move, lowest score first; bounds are inclusive unless prefixed with (, and -inf/+inf are accepted

  • count (Integer) (defaults to: nil) —

    move at most count members; without it MIN/MAX move one member and byscore moves the whole range

Returns:

  • (nil, Array<Array<String, Float>>) —

    the moved [member, score] pairs, or nil when nothing was moved (missing source, empty range, same source and destination)

Raises:

  • (ArgumentError)


259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/redis/commands/sorted_sets.rb', line 259

def zmove(source, destination, modifier: nil, byscore: nil, count: nil)
  raise ArgumentError, "Pick either modifier or byscore" if modifier && byscore

  args = [:zmove, source, destination]
  if byscore
    min, max = byscore
    args << "BYSCORE" << min << max
  else
    modifier ||= "MIN"
    raise ArgumentError, "Pick either MIN or MAX" unless modifier == "MIN" || modifier == "MAX"

    args << modifier
  end
  args << "COUNT" << Integer(count) if count

  send_command(args, &FloatifyPairs)
end

#zmovemember(source, destination, members, nx: nil, xx: nil) ⇒ nil, Array<Array<String, Float>>

Atomically move the given members from one sorted set to another, preserving their scores.

Examples:

Move two members

redis.zmovemember('src', 'dst', %w[a b])
#=> [['a', 1.0], ['b', 2.0]]

Move a member only when the destination does not have it yet

redis.zmovemember('src', 'dst', 'a', nx: true)

Parameters:

  • source (String) —

    source key

  • destination (String) —

    destination key

  • members (String, Array<String>) —

    one or more members, processed in the given order; members missing from the source are skipped, duplicates are moved once

  • nx (Boolean) (defaults to: nil) —

    only move members the destination does not have

  • xx (Boolean) (defaults to: nil) —

    only move members the destination already has (their score is overwritten)

Returns:

  • (nil, Array<Array<String, Float>>) —

    the moved [member, score] pairs in the given order, or nil when nothing was moved

Raises:

  • (ArgumentError)


324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/redis/commands/sorted_sets.rb', line 324

def zmovemember(source, destination, members, nx: nil, xx: nil)
  raise ArgumentError, "Pick either NX or XX" if nx && xx

  members = Array(members)
  args = [:zmovemember, source, destination]
  args << "NX" if nx
  args << "XX" if xx
  args << "MEMBERS" << members.size
  args.concat(members)

  send_command(args, &FloatifyPairs)
end

#zmpop(*keys, modifier: "MIN", count: nil) ⇒ Array<String, Array<String, Float>>

Removes and returns up to count members with scores in the sorted set stored at key.

Examples:

Popping a member

redis.zmpop('zset')
#=> ['zset', ['a', 1.0]]

With count option

redis.zmpop('zset', count: 2)
#=> ['zset', [['a', 1.0], ['b', 2.0]]

Returns:

  • (Array<String, Array<String, Float>>) —

    list of popped elements and scores

Raises:

  • (ArgumentError)


220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/redis/commands/sorted_sets.rb', line 220

def zmpop(*keys, modifier: "MIN", count: nil)
  raise ArgumentError, "Pick either MIN or MAX" unless modifier == "MIN" || modifier == "MAX"

  args = [:zmpop, keys.size, *keys, modifier]
  args << "COUNT" << Integer(count) if count

  send_command(args) do |response|
    response&.map do |entry|
      case entry
      when String then entry
      when Array then entry.map { |pair| FloatifyPairs.call(pair) }.flatten(1)
      end
    end
  end
end

#zmscore(key, *members) ⇒ Array<Float>

Get the scores associated with the given members in a sorted set.

Examples:

Get the scores for members "a" and "b"

redis.zmscore("zset", "a", "b")
  # => [32.0, 48.0]

Parameters:

  • key (String)
  • members (String, Array<String>)

Returns:

  • (Array<Float>) —

    scores of the members



401
402
403
404
405
# File 'lib/redis/commands/sorted_sets.rb', line 401

def zmscore(key, *members)
  send_command([:zmscore, key, *members]) do |reply|
    reply.map(&Floatify)
  end
end

#zpopmax(key, count = nil) ⇒ Array<String, Float>+

Removes and returns up to count members with the highest scores in the sorted set stored at key.

Examples:

Popping a member

redis.zpopmax('zset')
#=> ['b', 2.0]

With count option

redis.zpopmax('zset', 2)
#=> [['b', 2.0], ['a', 1.0]]

Returns:

  • (Array<String, Float>) —

    element and score pair if count is not specified

  • (Array<Array<String, Float>>) —

    list of popped elements and scores



138
139
140
141
142
143
144
145
# File 'lib/redis/commands/sorted_sets.rb', line 138

def zpopmax(key, count = nil)
  command = [:zpopmax, key]
  command << Integer(count) if count
  send_command(command) do |members|
    members = FloatifyPairs.call(members)
    count.to_i > 1 ? members : members.first
  end
end

#zpopmin(key, count = nil) ⇒ Array<String, Float>+

Removes and returns up to count members with the lowest scores in the sorted set stored at key.

Examples:

Popping a member

redis.zpopmin('zset')
#=> ['a', 1.0]

With count option

redis.zpopmin('zset', 2)
#=> [['a', 1.0], ['b', 2.0]]

Returns:

  • (Array<String, Float>) —

    element and score pair if count is not specified

  • (Array<Array<String, Float>>) —

    list of popped elements and scores



161
162
163
164
165
166
167
168
# File 'lib/redis/commands/sorted_sets.rb', line 161

def zpopmin(key, count = nil)
  command = [:zpopmin, key]
  command << Integer(count) if count
  send_command(command) do |members|
    members = FloatifyPairs.call(members)
    count.to_i > 1 ? members : members.first
  end
end

#zrandmember(key, count = nil, withscores: false, with_scores: withscores) ⇒ nil, ...

Get one or more random members from a sorted set.

Examples:

Get one random member

redis.zrandmember("zset")
  # => "a"

Get multiple random members

redis.zrandmember("zset", 2)
  # => ["a", "b"]

Get multiple random members with scores

redis.zrandmember("zset", 2, with_scores: true)
  # => [["a", 2.0], ["b", 3.0]]

Parameters:

  • key (String)
  • count (Integer) (defaults to: nil)
  • options (Hash) —
    • :with_scores => true: include scores in output

Returns:

  • (nil, String, Array<String>, Array<[String, Float]>) —
    • when key does not exist or set is empty, nil
    • when count is not specified, a member
    • when count is specified and :with_scores is not specified, an array of members
    • when :with_scores is specified, an array with [member, score] pairs


429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/redis/commands/sorted_sets.rb', line 429

def zrandmember(key, count = nil, withscores: false, with_scores: withscores)
  if with_scores && count.nil?
    raise ArgumentError, "count argument must be specified"
  end

  args = [:zrandmember, key]
  args << Integer(count) if count

  if with_scores
    args << "WITHSCORES"
    block = FloatifyPairs
  end

  send_command(args, &block)
end

#zrange(key, start, stop, byscore: false, by_score: byscore, bylex: false, by_lex: bylex, rev: false, limit: nil, withscores: false, with_scores: withscores) ⇒ Array<String>, Array<[String, Float]>

Return a range of members in a sorted set, by index, score or lexicographical ordering.

Examples:

Retrieve all members from a sorted set, by index

redis.zrange("zset", 0, -1)
  # => ["a", "b"]

Retrieve all members and their scores from a sorted set

redis.zrange("zset", 0, -1, :with_scores => true)
  # => [["a", 32.0], ["b", 64.0]]

Parameters:

  • key (String)
  • start (Integer) —

    start index

  • stop (Integer) —

    stop index

  • options (Hash) —
    • :by_score => false: return members by score
    • :by_lex => false: return members by lexicographical ordering
    • :rev => false: reverse the ordering, from highest to lowest
    • :limit => [offset, count]: skip offset members, return a maximum of count members
    • :with_scores => true: include scores in output

Returns:

  • (Array<String>, Array<[String, Float]>) —
    • when :with_scores is not specified, an array of members
    • when :with_scores is specified, an array with [member, score] pairs


468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/redis/commands/sorted_sets.rb', line 468

def zrange(key, start, stop, byscore: false, by_score: byscore, bylex: false, by_lex: bylex,
           rev: false, limit: nil, withscores: false, with_scores: withscores)
  if by_score && by_lex
    raise ArgumentError, "only one of :by_score or :by_lex can be specified"
  end

  args = [:zrange, key, start, stop]

  if by_score
    args << "BYSCORE"
  elsif by_lex
    args << "BYLEX"
  end

  args << "REV" if rev

  if limit
    args << "LIMIT"
    args.concat(limit.map { |l| Integer(l) })
  end

  if with_scores
    args << "WITHSCORES"
    block = FloatifyPairs
  end

  send_command(args, &block)
end

#zrangebylex(key, min, max, limit: nil) ⇒ Array<String>, Array<[String, Float]>

Return a range of members with the same score in a sorted set, by lexicographical ordering

Examples:

Retrieve members matching a

redis.zrangebylex("zset", "[a", "[a\xff")
  # => ["aaren", "aarika", "abagael", "abby"]

Retrieve the first 2 members matching a

redis.zrangebylex("zset", "[a", "[a\xff", :limit => [0, 2])
  # => ["aaren", "aarika"]

Parameters:

  • key (String)
  • min (String) —
    • inclusive minimum is specified by prefixing (
    • exclusive minimum is specified by prefixing [
  • max (String) —
    • inclusive maximum is specified by prefixing (
    • exclusive maximum is specified by prefixing [
  • options (Hash) —
    • :limit => [offset, count]: skip offset members, return a maximum of count members

Returns:

  • (Array<String>, Array<[String, Float]>)


670
671
672
673
674
675
676
677
678
679
# File 'lib/redis/commands/sorted_sets.rb', line 670

def zrangebylex(key, min, max, limit: nil)
  args = [:zrangebylex, key, min, max]

  if limit
    args << "LIMIT"
    args.concat(limit.map { |l| Integer(l) })
  end

  send_command(args)
end

#zrangebyscore(key, min, max, withscores: false, with_scores: withscores, limit: nil) ⇒ Array<String>, Array<[String, Float]>

Return a range of members in a sorted set, by score.

Examples:

Retrieve members with score >= 5 and < 100

redis.zrangebyscore("zset", "5", "(100")
  # => ["a", "b"]

Retrieve the first 2 members with score >= 0

redis.zrangebyscore("zset", "0", "+inf", :limit => [0, 2])
  # => ["a", "b"]

Retrieve members and their scores with scores > 5

redis.zrangebyscore("zset", "(5", "+inf", :with_scores => true)
  # => [["a", 32.0], ["b", 64.0]]

Parameters:

  • key (String)
  • min (String) —
    • inclusive minimum score is specified verbatim
    • exclusive minimum score is specified by prefixing (
  • max (String) —
    • inclusive maximum score is specified verbatim
    • exclusive maximum score is specified by prefixing (
  • options (Hash) —
    • :with_scores => true: include scores in output
    • :limit => [offset, count]: skip offset members, return a maximum of count members

Returns:

  • (Array<String>, Array<[String, Float]>) —
    • when :with_scores is not specified, an array of members
    • when :with_scores is specified, an array with [member, score] pairs


730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/redis/commands/sorted_sets.rb', line 730

def zrangebyscore(key, min, max, withscores: false, with_scores: withscores, limit: nil)
  args = [:zrangebyscore, key, min, max]

  if with_scores
    args << "WITHSCORES"
    block = FloatifyPairs
  end

  if limit
    args << "LIMIT"
    args.concat(limit.map { |l| Integer(l) })
  end

  send_command(args, &block)
end

#zrangestore(dest_key, src_key, start, stop, byscore: false, by_score: byscore, bylex: false, by_lex: bylex, rev: false, limit: nil) ⇒ Integer

Select a range of members in a sorted set, by index, score or lexicographical ordering and store the resulting sorted set in a new key.

Examples:

redis.zadd("foo", [[1.0, "s1"], [2.0, "s2"], [3.0, "s3"]])
redis.zrangestore("bar", "foo", 0, 1)
  # => 2
redis.zrange("bar", 0, -1)
  # => ["s1", "s2"]

Returns:

  • (Integer) —

    the number of elements in the resulting sorted set

See Also:



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/redis/commands/sorted_sets.rb', line 509

def zrangestore(dest_key, src_key, start, stop, byscore: false, by_score: byscore,
                bylex: false, by_lex: bylex, rev: false, limit: nil)
  if by_score && by_lex
    raise ArgumentError, "only one of :by_score or :by_lex can be specified"
  end

  args = [:zrangestore, dest_key, src_key, start, stop]

  if by_score
    args << "BYSCORE"
  elsif by_lex
    args << "BYLEX"
  end

  args << "REV" if rev

  if limit
    args << "LIMIT"
    args.concat(limit.map { |l| Integer(l) })
  end

  send_command(args)
end

#zrank(key, member, withscore: false, with_score: withscore) ⇒ Integer, ...

Determine the index of a member in a sorted set.

Examples:

Retrieve member rank

redis.zrank("zset", "a")
  # => 3

Retrieve member rank with their score

redis.zrank("zset", "a", :with_score => true)
  # => [3, 32.0]

Parameters:

  • key (String)
  • member (String)

Returns:

  • (Integer, [Integer, Float], nil) —
    • when :with_score is not specified, an Integer
    • when :with_score is specified, a [rank, score] pair
    • nil when the key or the member does not exist


571
572
573
574
575
576
577
578
579
580
# File 'lib/redis/commands/sorted_sets.rb', line 571

def zrank(key, member, withscore: false, with_score: withscore)
  args = [:zrank, key, member]

  if with_score
    args << "WITHSCORE"
    block = FloatifyPair
  end

  send_command(args, &block)
end

#zrem(key, member) ⇒ Boolean, Integer

Remove one or more members from a sorted set.

Examples:

Remove a single member from a sorted set

redis.zrem("zset", "a")

Remove an array of members from a sorted set

redis.zrem("zset", ["a", "b"])

Parameters:

  • key (String)
  • member (String, Array<String>) —
    • a single member
    • an array of members

Returns:

  • (Boolean, Integer) —
    • Boolean when a single member is specified, holding whether or not it was removed from the sorted set
    • Integer when an array of pairs is specified, holding the number of members that were removed to the sorted set


107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/redis/commands/sorted_sets.rb', line 107

def zrem(key, member)
  if member.is_a?(Array)
    members_to_remove = member
    return 0 if members_to_remove.empty?
  end

  send_command([:zrem, key, member]) do |reply|
    if member.is_a? Array
      # Variadic: return integer
      reply
    else
      # Single argument: return boolean
      Boolify.call(reply)
    end
  end
end

#zremrangebyrank(key, start, stop) ⇒ Integer

Remove all members in a sorted set within the given indexes.

Examples:

Remove first 5 members

redis.zremrangebyrank("zset", 0, 4)
  # => 5

Remove last 5 members

redis.zremrangebyrank("zset", -5, -1)
  # => 5

Parameters:

  • key (String)
  • start (Integer) —

    start index

  • stop (Integer) —

    stop index

Returns:

  • (Integer) —

    number of members that were removed



623
624
625
# File 'lib/redis/commands/sorted_sets.rb', line 623

def zremrangebyrank(key, start, stop)
  send_command([:zremrangebyrank, key, start, stop])
end

#zremrangebyscore(key, min, max) ⇒ Integer

Remove all members in a sorted set within the given scores.

Examples:

Remove members with score >= 5 and < 100

redis.zremrangebyscore("zset", "5", "(100")
  # => 2

Remove members with scores > 5

redis.zremrangebyscore("zset", "(5", "+inf")
  # => 2

Parameters:

  • key (String)
  • min (String) —
    • inclusive minimum score is specified verbatim
    • exclusive minimum score is specified by prefixing (
  • max (String) —
    • inclusive maximum score is specified verbatim
    • exclusive maximum score is specified by prefixing (

Returns:

  • (Integer) —

    number of members that were removed



793
794
795
# File 'lib/redis/commands/sorted_sets.rb', line 793

def zremrangebyscore(key, min, max)
  send_command([:zremrangebyscore, key, min, max])
end

#zrevrange(key, start, stop, withscores: false, with_scores: withscores) ⇒ Object

Return a range of members in a sorted set, by index, with scores ordered from high to low.

Examples:

Retrieve all members from a sorted set

redis.zrevrange("zset", 0, -1)
  # => ["b", "a"]

Retrieve all members and their scores from a sorted set

redis.zrevrange("zset", 0, -1, :with_scores => true)
  # => [["b", 64.0], ["a", 32.0]]

See Also:



544
545
546
547
548
549
550
551
552
553
# File 'lib/redis/commands/sorted_sets.rb', line 544

def zrevrange(key, start, stop, withscores: false, with_scores: withscores)
  args = [:zrevrange, key, Integer(start), Integer(stop)]

  if with_scores
    args << "WITHSCORES"
    block = FloatifyPairs
  end

  send_command(args, &block)
end

#zrevrangebylex(key, max, min, limit: nil) ⇒ Object

Return a range of members with the same score in a sorted set, by reversed lexicographical ordering. Apart from the reversed ordering, #zrevrangebylex is similar to #zrangebylex.

Examples:

Retrieve members matching a

redis.zrevrangebylex("zset", "[a", "[a\xff")
  # => ["abbygail", "abby", "abagael", "aaren"]

Retrieve the last 2 members matching a

redis.zrevrangebylex("zset", "[a", "[a\xff", :limit => [0, 2])
  # => ["abbygail", "abby"]

See Also:



692
693
694
695
696
697
698
699
700
701
# File 'lib/redis/commands/sorted_sets.rb', line 692

def zrevrangebylex(key, max, min, limit: nil)
  args = [:zrevrangebylex, key, max, min]

  if limit
    args << "LIMIT"
    args.concat(limit.map { |l| Integer(l) })
  end

  send_command(args)
end

#zrevrangebyscore(key, max, min, withscores: false, with_scores: withscores, limit: nil) ⇒ Object

Return a range of members in a sorted set, by score, with scores ordered from high to low.

Examples:

Retrieve members with score < 100 and >= 5

redis.zrevrangebyscore("zset", "(100", "5")
  # => ["b", "a"]

Retrieve the first 2 members with score <= 0

redis.zrevrangebyscore("zset", "0", "-inf", :limit => [0, 2])
  # => ["b", "a"]

Retrieve members and their scores with scores > 5

redis.zrevrangebyscore("zset", "+inf", "(5", :with_scores => true)
  # => [["b", 64.0], ["a", 32.0]]

See Also:



760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
# File 'lib/redis/commands/sorted_sets.rb', line 760

def zrevrangebyscore(key, max, min, withscores: false, with_scores: withscores, limit: nil)
  args = [:zrevrangebyscore, key, max, min]

  if with_scores
    args << "WITHSCORES"
    block = FloatifyPairs
  end

  if limit
    args << "LIMIT"
    args.concat(limit.map { |l| Integer(l) })
  end

  send_command(args, &block)
end

#zrevrank(key, member, withscore: false, with_score: withscore) ⇒ Integer, ...

Determine the index of a member in a sorted set, with scores ordered from high to low.

Examples:

Retrieve member rank

redis.zrevrank("zset", "a")
  # => 3

Retrieve member rank with their score

redis.zrevrank("zset", "a", :with_score => true)
  # => [3, 32.0]

Parameters:

  • key (String)
  • member (String)

Returns:

  • (Integer, [Integer, Float], nil) —
    • when :with_score is not specified, an Integer
    • when :with_score is specified, a [rank, score] pair
    • nil when the key or the member does not exist


599
600
601
602
603
604
605
606
607
608
# File 'lib/redis/commands/sorted_sets.rb', line 599

def zrevrank(key, member, withscore: false, with_score: withscore)
  args = [:zrevrank, key, member]

  if with_score
    args << "WITHSCORE"
    block = FloatifyPair
  end

  send_command(args, &block)
end

#zscan(key, cursor, **options) ⇒ String, Array<[String, Float]>

Scan a sorted set

See the Redis Server ZSCAN documentation for further details

Examples:

Retrieve the first batch of key/value pairs in a hash

redis.zscan("zset", 0)

Parameters:

  • cursor (String, Integer) —

    the cursor of the iteration

  • options (Hash) —
    • :match => String: only return keys matching the pattern
    • :count => Integer: return count keys at most per iteration

Returns:

  • (String, Array<[String, Float]>) —

    the next cursor and all found members and scores



980
981
982
983
984
# File 'lib/redis/commands/sorted_sets.rb', line 980

def zscan(key, cursor, **options)
  _scan(:zscan, cursor, [key], **options) do |reply|
    [reply[0], FloatifyPairs.call(reply[1])]
  end
end

#zscan_each(key, **options, &block) ⇒ Enumerator

Scan a sorted set

See the Redis Server ZSCAN documentation for further details

Examples:

Retrieve all of the members/scores in a sorted set

redis.zscan_each("zset").to_a
# => [["key70", "70"], ["key80", "80"]]

Parameters:

  • options (Hash) —
    • :match => String: only return keys matching the pattern
    • :count => Integer: return count keys at most per iteration

Returns:

  • (Enumerator) —

    an enumerator for all found scores and members



999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/redis/commands/sorted_sets.rb', line 999

def zscan_each(key, **options, &block)
  return to_enum(:zscan_each, key, **options) unless block_given?

  cursor = 0
  loop do
    cursor, values = zscan(key, cursor, **options)
    values.each(&block)
    break if cursor == "0"
  end
end

#zscore(key, member) ⇒ Float

Get the score associated with the given member in a sorted set.

Examples:

Get the score for member "a"

redis.zscore("zset", "a")
  # => 32.0

Parameters:

  • key (String)
  • member (String)

Returns:

  • (Float) —

    score of the member



388
389
390
# File 'lib/redis/commands/sorted_sets.rb', line 388

def zscore(key, member)
  send_command([:zscore, key, member], &Floatify)
end

#zunion(*args) ⇒ Array<String>, Array<[String, Float]>

Return the union of multiple sorted sets

Examples:

Retrieve the union of 2*zsetA and 1*zsetB

redis.zunion("zsetA", "zsetB", :weights => [2.0, 1.0])
  # => ["v1", "v2"]

Retrieve the union of 2*zsetA and 1*zsetB, and their scores

redis.zunion("zsetA", "zsetB", :weights => [2.0, 1.0], :with_scores => true)
  # => [["v1", 3.0], ["v2", 6.0]]

Parameters:

  • keys (String, Array<String>) —

    one or more keys to union

  • options (Hash) —
    • :weights => [Array<Float>]: weights to associate with source sorted sets
    • :aggregate => String: aggregate function to use (sum, min, max; count since Redis 8.8)
    • :with_scores => true: include scores in output

Returns:

  • (Array<String>, Array<[String, Float]>) —
    • when :with_scores is not specified, an array of members
    • when :with_scores is specified, an array with [member, score] pairs


902
903
904
# File 'lib/redis/commands/sorted_sets.rb', line 902

def zunion(*args)
  _zsets_operation(:zunion, *args)
end

#zunionstore(*args) ⇒ Integer

Add multiple sorted sets and store the resulting sorted set in a new key.

Examples:

Compute the union of 2*zsetA with 1*zsetB, summing their scores

redis.zunionstore("zsetC", ["zsetA", "zsetB"], :weights => [2.0, 1.0], :aggregate => "sum")
  # => 8

Parameters:

  • destination (String) —

    destination key

  • keys (Array<String>) —

    source keys

  • options (Hash) —
    • :weights => [Float, Float, ...]: weights to associate with source sorted sets
    • :aggregate => String: aggregate function to use (sum, min, max; count since Redis 8.8)

Returns:

  • (Integer) —

    number of elements in the resulting sorted set



920
921
922
# File 'lib/redis/commands/sorted_sets.rb', line 920

def zunionstore(*args)
  _zsets_operation_store(:zunionstore, *args)
end