Module: Valkey::Commands::SortedSetCommands

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

Instance Method Summary collapse

Instance Method Details

#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

#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

#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

#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

#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

#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

#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