Module: Valkey::Commands::SortedSetCommands

Included in:
Valkey::Commands
Defined in:
lib/valkey/commands/sorted_set_commands.rb

Instance Method Summary collapse

Instance Method Details

#bzmpop(timeout, *keys, modifier: "MIN", count: 1) ⇒ Array?

Remove and return members with scores from one or more sorted sets, blocking until available.

Examples:

Pop from multiple keys

valkey.bzmpop(1.0, "key1", "key2", modifier: "MAX", count: 2)
  # => ["key1", [["member1", 3.0], ["member2", 2.0]]]

Parameters:

  • timeout (Float)

    timeout in seconds

  • keys (Array<String>)

    sorted set keys

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

    “MIN” or “MAX”

  • count (Integer) (defaults to: 1)

    number of elements to pop

Returns:

  • (Array, nil)

    key and array of [member, score] pairs, or nil if timeout

See Also:



574
575
576
577
578
579
# File 'lib/valkey/commands/sorted_set_commands.rb', line 574

def bzmpop(timeout, *keys, modifier: "MIN", count: 1)
  args = [timeout, keys.size] + keys + [modifier, "COUNT", count]
  send_command(RequestType::BZ_MPOP, args) do |reply|
    reply && [reply[0], Utils::FloatifyPairs.call(reply[1])]
  end
end

#bzpopmax(*keys, timeout:) ⇒ Array?

Remove and return the member with the highest score from a sorted set, blocking until available.

Examples:

Pop from single key

valkey.bzpopmax("key1", timeout: 1.0)
  # => ["key1", "member", 3.0]

Pop from multiple keys

valkey.bzpopmax("key1", "key2", timeout: 1.0)
  # => ["key2", "member", 2.0]

Parameters:

  • keys (Array<String>)

    sorted set keys

  • timeout (Float)

    timeout in seconds

Returns:

  • (Array, nil)

    key, member, and score, or nil if timeout

See Also:



595
596
597
598
599
600
# File 'lib/valkey/commands/sorted_set_commands.rb', line 595

def bzpopmax(*keys, timeout:)
  args = keys + [timeout]
  send_command(RequestType::BZ_POP_MAX, args) do |reply|
    reply && [reply[0], reply[1], Utils::Floatify.call(reply[2])]
  end
end

#bzpopmin(*keys, timeout:) ⇒ Array?

Remove and return the member with the lowest score from a sorted set, blocking until available.

Examples:

Pop from single key

valkey.bzpopmin("key1", timeout: 1.0)
  # => ["key1", "member", 1.0]

Pop from multiple keys

valkey.bzpopmin("key1", "key2", timeout: 1.0)
  # => ["key2", "member", 0.5]

Parameters:

  • keys (Array<String>)

    sorted set keys

  • timeout (Float)

    timeout in seconds

Returns:

  • (Array, nil)

    key, member, and score, or nil if timeout

See Also:



616
617
618
619
620
621
# File 'lib/valkey/commands/sorted_set_commands.rb', line 616

def bzpopmin(*keys, timeout:)
  args = keys + [timeout]
  send_command(RequestType::BZ_POP_MIN, args) do |reply|
    reply && [reply[0], reply[1], Utils::Floatify.call(reply[2])]
  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

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

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

valkey.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/valkey/commands/sorted_set_commands.rb', line 53

def zadd(key, *args, nx: nil, xx: nil, lt: nil, gt: nil, ch: nil, incr: nil)
  command_args = [key]
  command_args << "NX" if nx
  command_args << "XX" if xx
  command_args << "LT" if lt
  command_args << "GT" if gt
  command_args << "CH" if ch
  command_args << "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(RequestType::Z_ADD, command_args + members_to_add.flatten, &(incr ? Utils::Floatify : nil))
  elsif args.size == 2
    # Single pair: return float if INCR, boolean if !INCR
    send_command(RequestType::Z_ADD, command_args + args.flatten.flatten, &(incr ? Utils::Floatify : Utils::Boolify))
  else
    raise ArgumentError, "wrong number of arguments"
  end
end

#zcard(key) ⇒ Integer

Get the number of members in a sorted set.

Examples:

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

Parameters:

  • key (String)

Returns:

  • (Integer)


14
15
16
# File 'lib/valkey/commands/sorted_set_commands.rb', line 14

def zcard(key)
  send_command(RequestType::Z_CARD, [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`

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

Count members with scores ‘> 5`

valkey.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



411
412
413
# File 'lib/valkey/commands/sorted_set_commands.rb', line 411

def zcount(key, min, max)
  send_command(RequestType::Z_COUNT, [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:

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

With scores

valkey.zadd("zsetA", [[1.0, "v1"], [2.0, "v2"]])
valkey.zadd("zsetB", [[3.0, "v2"], [2.0, "v3"]])
valkey.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



520
521
522
# File 'lib/valkey/commands/sorted_set_commands.rb', line 520

def zdiff(*keys, with_scores: false)
  _zsets_operation(RequestType::Z_DIFF, *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:

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

Parameters:

  • destination (String)

    destination key

  • keys (Array<String>)

    source keys

Returns:

  • (Integer)

    number of elements in the resulting sorted set



536
537
538
# File 'lib/valkey/commands/sorted_set_commands.rb', line 536

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

#zincrby(key, increment, member) ⇒ Float

Increment the score of a member in a sorted set.

Examples:

valkey.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/valkey/commands/sorted_set_commands.rb', line 86

def zincrby(key, increment, member)
  send_command(RequestType::Z_INCR_BY, [key, increment, member], &Utils::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`

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

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

valkey.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, …)

    • ‘: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



434
435
436
# File 'lib/valkey/commands/sorted_set_commands.rb', line 434

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

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

Return the number of elements in the intersection of sorted sets.

Examples:

Get intersection cardinality

valkey.zintercard("key1", "key2")
  # => 3

With limit

valkey.zintercard("key1", "key2", limit: 10)
  # => 3

Parameters:

  • keys (Array<String>)

    sorted set keys

  • limit (Integer) (defaults to: nil)

    maximum number to count (optional)

Returns:

  • (Integer)

    number of elements in intersection

See Also:



637
638
639
640
641
# File 'lib/valkey/commands/sorted_set_commands.rb', line 637

def zintercard(*keys, limit: nil)
  args = [keys.size] + keys
  args += ["LIMIT", limit] if limit
  send_command(RequestType::Z_INTER_CARD, 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

valkey.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)

Returns:

  • (Integer)

    number of elements in the resulting sorted set



453
454
455
# File 'lib/valkey/commands/sorted_set_commands.rb', line 453

def zinterstore(*args)
  _zsets_operation_store(RequestType::Z_INTER_STORE, *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

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

Count members matching a-z

valkey.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



369
370
371
# File 'lib/valkey/commands/sorted_set_commands.rb', line 369

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

#zmpop(*keys, modifier: "MIN", count: 1) ⇒ Array?

Remove and return members with scores from one or more sorted sets.

Examples:

Pop from multiple keys

valkey.zmpop("key1", "key2", modifier: "MAX", count: 2)
  # => ["key1", [["member1", 3.0], ["member2", 2.0]]]

Parameters:

  • keys (Array<String>)

    sorted set keys

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

    “MIN” or “MAX”

  • count (Integer) (defaults to: 1)

    number of elements to pop

Returns:

  • (Array, nil)

    key and array of [member, score] pairs, or nil if no elements

See Also:



655
656
657
658
659
660
# File 'lib/valkey/commands/sorted_set_commands.rb', line 655

def zmpop(*keys, modifier: "MIN", count: 1)
  args = [keys.size] + keys + [modifier, "COUNT", count]
  send_command(RequestType::Z_MPOP, args) do |reply|
    reply && [reply[0], Utils::FloatifyPairs.call(reply[1])]
  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”

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

Parameters:

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

Returns:

  • (Array<Float>)

    scores of the members



191
192
193
194
195
# File 'lib/valkey/commands/sorted_set_commands.rb', line 191

def zmscore(key, *members)
  send_command(RequestType::Z_MSCORE, [key, *members]) do |reply|
    reply.map(&Utils::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

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

With count option

valkey.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



137
138
139
140
141
142
143
144
# File 'lib/valkey/commands/sorted_set_commands.rb', line 137

def zpopmax(key, count = nil)
  command_args = [key]
  command_args << Integer(count) if count
  send_command(RequestType::Z_POP_MAX, command_args) do |members|
    members = Utils::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

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

With count option

valkey.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



160
161
162
163
164
165
166
167
# File 'lib/valkey/commands/sorted_set_commands.rb', line 160

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

#zrandmember(key, count = nil, with_scores: false) ⇒ String, Array

Return random members from a sorted set.

Examples:

Get single random member

valkey.zrandmember("key")
  # => "member"

Get multiple random members

valkey.zrandmember("key", 3)
  # => ["member1", "member2", "member3"]

Get random members with scores

valkey.zrandmember("key", 2, with_scores: true)
  # => [["member1", 1.0], ["member2", 2.0]]

Parameters:

  • key (String)

    sorted set key

  • count (Integer) (defaults to: nil)

    number of members to return (optional)

  • with_scores (Boolean) (defaults to: false)

    return scores with members

Returns:

  • (String, Array)

    random member(s), optionally with scores

See Also:



680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# File 'lib/valkey/commands/sorted_set_commands.rb', line 680

def zrandmember(key, count = nil, with_scores: false)
  args = [key]
  if count
    args << count
    args << "WITHSCORES" if with_scores
  end

  send_command(RequestType::Z_RAND_MEMBER, args) do |reply|
    if with_scores
      # The reply is already in pairs format from the server
      # Just need to convert scores to floats
      reply.map { |pair| [pair[0], Utils::Floatify.call(pair[1])] }
    else
      reply
    end
  end
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

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

Retrieve all members and their scores from a sorted set

valkey.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

Raises:

  • (ArgumentError)


220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/valkey/commands/sorted_set_commands.rb', line 220

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

  args = [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 = Utils::FloatifyPairs
  end

  send_command(RequestType::Z_RANGE, args, &block)
end

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

Note:

This command is deprecated since Redis 6.2.0. Use #zrange with the ‘:by_lex` option instead.

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

Examples:

Retrieve members within a lexicographical range

valkey.zrangebylex("zset", "[aaa", "[g")
  # => ["aaa", "b", "c", "d", "e", "foo", "g"]

With exclusive ranges

valkey.zrangebylex("zset", "(aaa", "[g")
  # => ["b", "c", "d", "e", "foo", "g"]

With limit

valkey.zrangebylex("zset", "[aaa", "[g", :limit => [0, 3])
  # => ["aaa", "b", "c"]

Parameters:

  • key (String)
  • min (String)

    minimum lexicographical value

    • inclusive minimum is specified by prefixing ‘[`

    • exclusive minimum is specified by prefixing ‘(`

    • ‘-` represents negative infinity

  • max (String)

    maximum lexicographical value

    • inclusive maximum is specified by prefixing ‘[`

    • exclusive maximum is specified by prefixing ‘(`

    • ‘+` represents positive infinity

  • options (Hash)
    • ‘:limit => [offset, count]`: skip `offset` members, return a maximum of `count` members

Returns:

  • (Array<String>)

    array of members

See Also:



833
834
835
836
837
838
839
840
841
842
# File 'lib/valkey/commands/sorted_set_commands.rb', line 833

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

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

  send_command(RequestType::Z_RANGE_BY_LEX, args)
end

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

Note:

This command is deprecated since Redis 6.2.0. Use #zrange with the ‘:by_score` option instead.

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

Examples:

Retrieve members with scores between 1 and 3

valkey.zrangebyscore("zset", 1, 3)
  # => ["s1", "s2", "s3"]

Retrieve members with scores between 1 and 3, with scores

valkey.zrangebyscore("zset", 1, 3, :with_scores => true)
  # => [["s1", 1.0], ["s2", 2.0], ["s3", 3.0]]

With exclusive ranges

valkey.zrangebyscore("zset", "(1", "(3")
  # => ["s2"]

With limit

valkey.zrangebyscore("zset", 1, 3, :limit => [0, 2])
  # => ["s1", "s2"]

Parameters:

  • key (String)
  • min (String, Numeric)

    minimum score

    • inclusive minimum is specified verbatim

    • exclusive minimum is specified by prefixing ‘(`

    • ‘-inf` represents negative infinity

  • max (String, Numeric)

    maximum score

    • inclusive maximum is specified verbatim

    • exclusive maximum is specified by prefixing ‘(`

    • ‘+inf` represents positive infinity

  • 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

See Also:



788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
# File 'lib/valkey/commands/sorted_set_commands.rb', line 788

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

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

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

  send_command(RequestType::Z_RANGE_BY_SCORE, 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:

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

Returns:

  • (Integer)

    the number of elements in the resulting sorted set

Raises:

  • (ArgumentError)

See Also:



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/valkey/commands/sorted_set_commands.rb', line 259

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

  args = [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(RequestType::Z_RANGE_STORE, args)
end

#zrank(key, member, withscore: false, with_score: withscore) ⇒ Integer, [Integer, Float]

Determine the index of a member in a sorted set.

Examples:

Retrieve member rank

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

Retrieve member rank with their score

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

Parameters:

  • key (String)
  • member (String)

Returns:

  • (Integer, [Integer, Float])
    • when ‘:with_score` is not specified, an Integer

    • when ‘:with_score` is specified, a `[rank, score]` pair



296
297
298
299
300
301
302
303
304
305
# File 'lib/valkey/commands/sorted_set_commands.rb', line 296

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

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

  send_command(RequestType::Z_RANK, 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

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

Remove an array of members from a sorted set

valkey.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
# File 'lib/valkey/commands/sorted_set_commands.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(RequestType::Z_REM, [key, member].flatten) do |reply|
    if member.is_a? Array
      # Variadic: return integer
      reply
    else
      # Single argument: return boolean
      Utils::Boolify.call(reply)
    end
  end
end

#zremrangebylex(key, min, max) ⇒ Integer

Remove members from a sorted set within a lexicographical range.

Examples:

Remove by lexicographical range

valkey.zremrangebylex("key", "[a", "[c")
  # => 2

Parameters:

  • key (String)

    sorted set key

  • min (String)

    minimum lexicographical value

    • inclusive minimum is specified by prefixing ‘[`

    • exclusive minimum is specified by prefixing ‘(`

    • ‘-` represents negative infinity

  • max (String)

    maximum lexicographical value

    • inclusive maximum is specified by prefixing ‘[`

    • exclusive maximum is specified by prefixing ‘(`

    • ‘+` represents positive infinity

Returns:

  • (Integer)

    number of members that were removed

See Also:



716
717
718
# File 'lib/valkey/commands/sorted_set_commands.rb', line 716

def zremrangebylex(key, min, max)
  send_command(RequestType::Z_REM_RANGE_BY_LEX, [key, min, max])
end

#zremrangebyrank(key, start, stop) ⇒ Integer

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

Examples:

Remove first 5 members

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

Remove last 5 members

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

Parameters:

  • key (String)
  • start (Integer)

    start index

  • stop (Integer)

    stop index

Returns:

  • (Integer)

    number of members that were removed



347
348
349
# File 'lib/valkey/commands/sorted_set_commands.rb', line 347

def zremrangebyrank(key, start, stop)
  send_command(RequestType::Z_REM_RANGE_BY_RANK, [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`

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

Remove members with scores ‘> 5`

valkey.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



390
391
392
# File 'lib/valkey/commands/sorted_set_commands.rb', line 390

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

#zrevrange(key, start, stop, withscores: false, with_scores: withscores) ⇒ Array<String>, Array<[String, Float]>

Note:

This command is deprecated since Redis 6.2.0. Use #zrange with the ‘:rev` option instead.

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

Examples:

Retrieve members from a sorted set in reverse order

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

Retrieve members and their scores from a sorted set in reverse order

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

Parameters:

  • key (String)
  • start (Integer)

    start index

  • stop (Integer)

    stop index

  • 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

See Also:



742
743
744
745
746
747
748
749
750
751
# File 'lib/valkey/commands/sorted_set_commands.rb', line 742

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

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

  send_command(RequestType::Z_REV_RANGE, args, &block)
end

#zrevrangebylex(key, max, min, limit: nil) ⇒ Array<String>

Note:

This command is deprecated since Redis 6.2.0. Use #zrange with the ‘:by_lex` and `:rev` options instead.

Return a range of members in a sorted set, by lexicographical ordering, ordered from high to low.

Examples:

Retrieve members within a lexicographical range (reversed)

valkey.zrevrangebylex("zset", "[g", "[aaa")
  # => ["g", "foo", "e", "d", "c", "b", "aaa"]

With exclusive ranges

valkey.zrevrangebylex("zset", "[g", "(aaa")
  # => ["g", "foo", "e", "d", "c", "b"]

With limit

valkey.zrevrangebylex("zset", "[g", "[aaa", :limit => [0, 3])
  # => ["g", "foo", "e"]

Parameters:

  • key (String)
  • max (String)

    maximum lexicographical value

    • inclusive maximum is specified by prefixing ‘[`

    • exclusive maximum is specified by prefixing ‘(`

    • ‘+` represents positive infinity

  • min (String)

    minimum lexicographical value

    • inclusive minimum is specified by prefixing ‘[`

    • exclusive minimum is specified by prefixing ‘(`

    • ‘-` represents negative infinity

  • options (Hash)
    • ‘:limit => [offset, count]`: skip `offset` members, return a maximum of `count` members

Returns:

  • (Array<String>)

    array of members

See Also:



924
925
926
927
928
929
930
931
932
933
# File 'lib/valkey/commands/sorted_set_commands.rb', line 924

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

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

  send_command(RequestType::Z_REV_RANGE_BY_LEX, args)
end

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

Note:

This command is deprecated since Redis 6.2.0. Use #zrange with ‘:by_score` and `:rev` instead.

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

Examples:

Retrieve members with scores between 3 and 1 (reversed)

valkey.zrevrangebyscore("zset", 3, 1)
  # => ["s3", "s2", "s1"]

Retrieve members with scores between 3 and 1, with scores

valkey.zrevrangebyscore("zset", 3, 1, :with_scores => true)
  # => [["s3", 3.0], ["s2", 2.0], ["s1", 1.0]]

With exclusive ranges

valkey.zrevrangebyscore("zset", "(3", "(1")
  # => ["s2"]

With limit

valkey.zrevrangebyscore("zset", 3, 1, :limit => [0, 2])
  # => ["s3", "s2"]

Parameters:

  • key (String)
  • max (String, Numeric)

    maximum score

    • inclusive maximum is specified verbatim

    • exclusive maximum is specified by prefixing ‘(`

    • ‘+inf` represents positive infinity

  • min (String, Numeric)

    minimum score

    • inclusive minimum is specified verbatim

    • exclusive minimum is specified by prefixing ‘(`

    • ‘-inf` represents negative infinity

  • 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

See Also:



879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
# File 'lib/valkey/commands/sorted_set_commands.rb', line 879

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

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

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

  send_command(RequestType::Z_REV_RANGE_BY_SCORE, args, &block)
end

#zrevrank(key, member, withscore: false, with_score: withscore) ⇒ Integer, [Integer, Float]

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

Examples:

Retrieve member rank

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

Retrieve member rank with their score

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

Parameters:

  • key (String)
  • member (String)

Returns:

  • (Integer, [Integer, Float])
    • when ‘:with_score` is not specified, an Integer

    • when ‘:with_score` is specified, a `[rank, score]` pair



323
324
325
326
327
328
329
330
331
332
# File 'lib/valkey/commands/sorted_set_commands.rb', line 323

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

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

  send_command(RequestType::Z_REV_RANK, args, &block)
end

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

Scan a sorted set

See the [Valkey Server ZSCAN documentation](valkey.io/docs/latest/commands/zscan/) for further details

Examples:

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

valkey.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



555
556
557
558
559
# File 'lib/valkey/commands/sorted_set_commands.rb', line 555

def zscan(key, cursor, **options)
  _scan(RequestType::Z_SCAN, cursor, [key], **options) do |reply|
    [reply[0], Utils::FloatifyPairs.call(reply[1])]
  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”

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

Parameters:

  • key (String)
  • member (String)

Returns:

  • (Float)

    score of the member



178
179
180
# File 'lib/valkey/commands/sorted_set_commands.rb', line 178

def zscore(key, member)
  send_command(RequestType::Z_SCORE, [key, member], &Utils::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`

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

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

valkey.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)

    • ‘: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



477
478
479
# File 'lib/valkey/commands/sorted_set_commands.rb', line 477

def zunion(*args)
  _zsets_operation(RequestType::Z_UNION, *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

valkey.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, …)

Returns:

  • (Integer)

    number of elements in the resulting sorted set



495
496
497
# File 'lib/valkey/commands/sorted_set_commands.rb', line 495

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