redis 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +114 -0
  3. data/README.md +172 -5
  4. data/lib/redis/client.rb +5 -1
  5. data/lib/redis/commands/arrays.rb +358 -0
  6. data/lib/redis/commands/bitmaps.rb +24 -0
  7. data/lib/redis/commands/bless.rb +115 -0
  8. data/lib/redis/commands/cluster.rb +9 -2
  9. data/lib/redis/commands/hashes.rb +250 -7
  10. data/lib/redis/commands/keys.rb +48 -11
  11. data/lib/redis/commands/modules/json.rb +27 -2
  12. data/lib/redis/commands/modules/search/aggregation.rb +2 -1
  13. data/lib/redis/commands/modules/search/field.rb +11 -2
  14. data/lib/redis/commands/modules/search/hybrid.rb +3 -0
  15. data/lib/redis/commands/modules/search/index.rb +2 -1
  16. data/lib/redis/commands/modules/search/miscellaneous.rb +2 -1
  17. data/lib/redis/commands/modules/search/query.rb +2 -2
  18. data/lib/redis/commands/modules/search/schema.rb +4 -0
  19. data/lib/redis/commands/scripting.rb +109 -0
  20. data/lib/redis/commands/server.rb +158 -7
  21. data/lib/redis/commands/sets.rb +270 -0
  22. data/lib/redis/commands/sorted_sets.rb +131 -6
  23. data/lib/redis/commands/streams.rb +284 -33
  24. data/lib/redis/commands/strings.rb +232 -6
  25. data/lib/redis/commands/transactions.rb +6 -1
  26. data/lib/redis/commands/vector_sets.rb +407 -0
  27. data/lib/redis/commands.rb +169 -6
  28. data/lib/redis/distributed.rb +539 -22
  29. data/lib/redis/hash_ring.rb +2 -1
  30. data/lib/redis/keyspace_notifications/channels.rb +121 -0
  31. data/lib/redis/keyspace_notifications/manager.rb +1121 -0
  32. data/lib/redis/keyspace_notifications/notification.rb +95 -0
  33. data/lib/redis/keyspace_notifications/parser.rb +170 -0
  34. data/lib/redis/keyspace_notifications.rb +59 -0
  35. data/lib/redis/pipeline.rb +17 -5
  36. data/lib/redis/ractorize.rb +6 -0
  37. data/lib/redis/subscribe.rb +80 -2
  38. data/lib/redis/version.rb +1 -1
  39. data/lib/redis/xxh3.rb +354 -0
  40. data/lib/redis.rb +29 -8
  41. metadata +16 -6
@@ -84,14 +84,26 @@ class Redis
84
84
 
85
85
  # Get information and statistics about the server.
86
86
  #
87
- # @param [String, Symbol] cmd e.g. "commandstats"
88
- # @return [Hash<String, String>]
89
- def info(cmd = nil)
90
- send_command([:info, cmd].compact) do |reply|
87
+ # @example Default sections
88
+ # redis.info
89
+ # @example One section
90
+ # redis.info(:commandstats)
91
+ # # => { "get" => { "calls" => "2", ... }, ... }
92
+ # @example Several sections at once (Redis 7.0)
93
+ # redis.info(:server, :clients)
94
+ #
95
+ # @param [Array<String, Symbol>] sections zero or more sections, e.g. `server`, `clients`,
96
+ # `commandstats`, `all`, `everything`. Passing more than one section requires Redis 7.0.
97
+ # @return [Hash<String, String>] the parsed `INFO` output. When `commandstats` is the only
98
+ # section, the reply is nested per command instead: `{ "get" => { "calls" => "2", ... } }`.
99
+ def info(*sections)
100
+ sections.flatten!(1)
101
+ sections.compact!
102
+ send_command([:info].concat(sections)) do |reply|
91
103
  if reply.is_a?(String)
92
104
  reply = HashifyInfo.call(reply)
93
105
 
94
- if cmd && cmd.to_s == "commandstats"
106
+ if sections.size == 1 && sections.first.to_s == "commandstats"
95
107
  # Extract nested hashes for INFO COMMANDSTATS
96
108
  reply = Hash[reply.map do |k, v|
97
109
  v = v.split(",").map { |e| e.split("=") }
@@ -134,11 +146,150 @@ class Redis
134
146
  send_command([:save])
135
147
  end
136
148
 
149
+ # Block until the write commands previously sent on this connection have been fsynced to
150
+ # the append-only file of the local server and/or of the given number of replicas.
151
+ #
152
+ # The reply always reports how many local servers and replicas had fsynced the writes when
153
+ # the command returned, whether or not the requested levels were reached, so compare it
154
+ # against what you asked for. Inside `multi` the command does not block.
155
+ #
156
+ # On `Redis::Cluster` the command is sent to every primary and each count is the minimum
157
+ # across them (the server's `agg_min` policy): `local` is `1` only if every primary
158
+ # fsynced, and `replicas` is the fewest acks any shard received. This per-connection
159
+ # guarantee does not hold inside `pipelined`/`multi` on cluster: `WAITAOF` carries no
160
+ # `write` flag, so the driver routes it to an arbitrary node (a random primary, or a
161
+ # replica when `replica: true`) rather than the node(s) that carried the pipeline's
162
+ # writes, so the reply is shape-correct but unrelated to those writes.
163
+ #
164
+ # @example Wait for the local AOF fsync
165
+ # redis.set("foo", "bar")
166
+ # redis.waitaof(1, 0, 0)
167
+ # # => [1, 0]
168
+ # @example Wait at most one second for one replica
169
+ # redis.waitaof(0, 1, 1000)
170
+ # # => [1, 0]
171
+ #
172
+ # @param [Integer] numlocal `1` to wait for the local AOF fsync, `0` to skip it. Requires
173
+ # `appendonly yes` on the server when set.
174
+ # @param [Integer] numreplicas number of replicas that must acknowledge the fsync
175
+ # @param [Integer] timeout maximum time to wait in milliseconds, `0` blocks indefinitely
176
+ #
177
+ # @return [Array<Integer>] `[local, replicas]`: the number of local servers (`0` or `1`) and
178
+ # replicas that had fsynced the writes
179
+ def waitaof(numlocal, numreplicas, timeout)
180
+ timeout = Integer(timeout)
181
+ command = [:waitaof, Integer(numlocal), Integer(numreplicas), timeout]
182
+ send_blocking_command(command, timeout / 1000.0)
183
+ end
184
+
185
+ # Start a hot-key tracking session (Redis 8.6).
186
+ #
187
+ # Keys are ranked by the share of CPU time and/or network bytes they consume while the
188
+ # session runs. The session is server-wide state shared by every connection, and only one
189
+ # can run at a time, so the command family is only available on a single-node client:
190
+ # `Redis::Cluster` and `Redis::Distributed` raise `NotImplementedError`.
191
+ #
192
+ # @example Track the top 10 keys by CPU time and network bytes
193
+ # redis.hotkeys_start(metrics: [:cpu, :net], count: 10)
194
+ # # => "OK"
195
+ # @example Track CPU time for one minute, sampling one command in five
196
+ # redis.hotkeys_start(metrics: :cpu, duration: 60, sample: 5)
197
+ # # => "OK"
198
+ #
199
+ # @param [Symbol, String, Array<Symbol, String>] metrics one or both of `:cpu` and `:net`
200
+ # @param [Integer, nil] count keys to report per metric, `1` to `64` (server default `10`)
201
+ # @param [Integer, nil] duration stop the session after this many seconds, `1` to `1_000_000`;
202
+ # without it the session runs until #hotkeys_stop
203
+ # @param [Integer, nil] sample track one command in `sample` (server default `1`: every command)
204
+ # @param [Array<Integer>, nil] slots cluster mode only: hash slots to track, all of them owned
205
+ # by the receiving node; the server rejects the option outside cluster mode
206
+ # @return [String] `"OK"`
207
+ # @raise [Redis::CommandError] when a session is already in progress or a value is out of range
208
+ def hotkeys_start(metrics:, count: nil, duration: nil, sample: nil, slots: nil)
209
+ metrics = Array(metrics).map { |metric| metric.to_s.upcase }
210
+ raise ArgumentError, "metrics must not be empty" if metrics.empty?
211
+
212
+ args = [:hotkeys, "START", "METRICS", metrics.size].concat(metrics)
213
+ args << "COUNT" << Integer(count) if count
214
+ args << "DURATION" << Integer(duration) if duration
215
+ args << "SAMPLE" << Integer(sample) if sample
216
+ slots = Array(slots)
217
+ args.push("SLOTS", slots.size, *slots.map { |slot| Integer(slot) }) unless slots.empty?
218
+ send_command(args)
219
+ end
220
+
221
+ # Return the results of the running or most recent hot-key tracking session (Redis 8.6).
222
+ #
223
+ # @example
224
+ # redis.hotkeys_get
225
+ # # => { "tracking-active" => 1, "sample-ratio" => 1, "selected-slots" => [[0, 16383]],
226
+ # # "all-commands-all-slots-us" => 73, "net-bytes-all-commands-all-slots" => 311,
227
+ # # "collection-start-time-unix-ms" => 1793782936885, "collection-duration-ms" => 4,
228
+ # # "total-cpu-time-user-ms" => 0, "total-cpu-time-sys-ms" => 0, "total-net-bytes" => 311,
229
+ # # "by-cpu-time-us" => [["product:1", 69], ["product:2", 4]],
230
+ # # "by-net-bytes" => [["product:1", 285], ["product:2", 26]] }
231
+ #
232
+ # @return [Hash{String => Object}] the reply fields, keyed by the server's names. Always
233
+ # present: `tracking-active` (`1` or `0`), `sample-ratio`, `selected-slots` (`[first, last]`
234
+ # slot ranges), `all-commands-all-slots-us`, `net-bytes-all-commands-all-slots`,
235
+ # `collection-start-time-unix-ms` and `collection-duration-ms`. With the `:cpu` metric:
236
+ # `total-cpu-time-user-ms`, `total-cpu-time-sys-ms` and `by-cpu-time-us`; with `:net`:
237
+ # `total-net-bytes` and `by-net-bytes`. The `by-*` lists are `[key, Integer]` pairs,
238
+ # hottest first, with at most `count` entries (possibly none). When `slots:` was given to
239
+ # #hotkeys_start the per-slot counters `all-commands-selected-slots-us`,
240
+ # `net-bytes-all-commands-selected-slots` and, with sampling,
241
+ # `sampled-commands-selected-slots-us`, `net-bytes-sampled-commands-selected-slots` are added.
242
+ # @return [nil] when no session was started, or after #hotkeys_reset
243
+ def hotkeys_get
244
+ send_command([:hotkeys, "GET"], &HashifyHotkeys)
245
+ end
246
+
247
+ # Stop the running hot-key tracking session, keeping its results for #hotkeys_get (Redis 8.6).
248
+ #
249
+ # @return [String] `"OK"`
250
+ # @return [nil] when no session is active
251
+ def hotkeys_stop
252
+ send_command([:hotkeys, "STOP"])
253
+ end
254
+
255
+ # Release the resources of a stopped hot-key tracking session (Redis 8.6).
256
+ #
257
+ # @return [String] `"OK"`
258
+ # @raise [Redis::CommandError] while a session is active; call #hotkeys_stop first
259
+ def hotkeys_reset
260
+ send_command([:hotkeys, "RESET"])
261
+ end
262
+
137
263
  # Synchronously save the dataset to disk and then shut down the server.
138
- def shutdown
264
+ #
265
+ # @example Default: save if a save point is configured, then exit
266
+ # redis.shutdown
267
+ # # => nil
268
+ # @example Skip the RDB save and don't wait for lagging replicas (Redis 7.0)
269
+ # redis.shutdown(save: false, now: true)
270
+ # @example Cancel an in-progress shutdown (Redis 7.0)
271
+ # redis.shutdown(abort: true)
272
+ # # => "OK"
273
+ #
274
+ # @param [Boolean, nil] save `true` forces an RDB save (`SAVE`), `false` skips it
275
+ # (`NOSAVE`); `nil` leaves the decision to the server's save points
276
+ # @param [Boolean] now skip waiting for lagging replicas (Redis 7.0)
277
+ # @param [Boolean] force ignore errors that would normally prevent the shutdown, such as a
278
+ # failed RDB or AOF write (Redis 7.0)
279
+ # @param [Boolean] abort cancel a shutdown that is waiting for replicas (Redis 7.0)
280
+ #
281
+ # @return [nil] when the server shut down (the connection is closed without a reply)
282
+ # @return [String] `OK` when `abort:` cancelled a pending shutdown
283
+ def shutdown(save: nil, now: false, force: false, abort: false)
284
+ args = [:shutdown]
285
+ args << (save ? "SAVE" : "NOSAVE") unless save.nil?
286
+ args << "NOW" if now
287
+ args << "FORCE" if force
288
+ args << "ABORT" if abort
289
+
139
290
  synchronize do |client|
140
291
  client.disable_reconnection do
141
- client.call_v([:shutdown])
292
+ client.call_v(args)
142
293
  rescue ConnectionError
143
294
  # This means Redis has probably exited.
144
295
  nil
@@ -164,6 +164,28 @@ class Redis
164
164
  send_command([:sinter].concat(keys))
165
165
  end
166
166
 
167
+ # Get the number of members in the intersection of multiple sets.
168
+ #
169
+ # @example
170
+ # redis.sadd("foo", ["s1", "s2", "s3"])
171
+ # redis.sadd("bar", ["s2", "s3", "s4"])
172
+ # redis.sintercard("foo", "bar")
173
+ # # => 2
174
+ # @example Stop counting once the intersection reaches 1 member
175
+ # redis.sintercard("foo", "bar", limit: 1)
176
+ # # => 1
177
+ #
178
+ # @param [String, Array<String>] keys keys pointing to sets to intersect
179
+ # @param [Integer] limit stop counting once the intersection reaches `limit`
180
+ # members (`0` means unlimited)
181
+ # @return [Integer] number of members in the intersection
182
+ def sintercard(*keys, limit: nil)
183
+ keys.flatten!(1)
184
+ args = [:sintercard, keys.size].concat(keys)
185
+ args << "LIMIT" << Integer(limit) if limit
186
+ send_command(args)
187
+ end
188
+
167
189
  # Intersect multiple sets and store the resulting set in a key.
168
190
  #
169
191
  # @param [String] destination destination key
@@ -254,6 +276,254 @@ class Redis
254
276
  break if cursor == "0"
255
277
  end
256
278
  end
279
+
280
+ # Sets the time to live in seconds for one or more set members. An
281
+ # expired member is removed from the set; a TTL of `0` removes it
282
+ # immediately.
283
+ #
284
+ # @example
285
+ # redis.sadd("set", "m1")
286
+ # redis.sexpire("set", 10, "m1", "m2") # => [1, -2]
287
+ # redis.sexpire("set", 10, "m1", "m2", nx: true) # => [0, -2]
288
+ #
289
+ # @param [String] key
290
+ # @param [Integer] ttl
291
+ # @param [Hash] options
292
+ # - `:nx => true`: Set expiry only when the member has no expiry.
293
+ # - `:xx => true`: Set expiry only when the member has an existing expiry.
294
+ # - `:gt => true`: Set expiry only when the new expiry is greater than current one.
295
+ # - `:lt => true`: Set expiry only when the new expiry is less than current one.
296
+ # @param [Array<String>] members
297
+ # @return [Array<Integer>] per member: `1` set, `0` condition not met,
298
+ # `2` deleted (TTL `0`), `-2` no such member or key.
299
+ # @raise [ArgumentError] when more than one of `:nx`, `:xx`, `:gt`, `:lt` is given
300
+ def sexpire(key, ttl, *members, nx: nil, xx: nil, gt: nil, lt: nil)
301
+ members.flatten!(1)
302
+ args = [:sexpire, key, Integer(ttl)]
303
+ args.concat(hash_field_expiration_condition(nx, xx, gt, lt))
304
+ args.concat(['MEMBERS', members.length, *members])
305
+
306
+ send_command(args)
307
+ end
308
+
309
+ # Sets the time to live in milliseconds for one or more set members. An
310
+ # expired member is removed from the set; a TTL of `0` removes it
311
+ # immediately.
312
+ #
313
+ # @example
314
+ # redis.sadd("set", "m1")
315
+ # redis.spexpire("set", 500, "m1", "m2") # => [1, -2]
316
+ # redis.spexpire("set", 500, "m1", "m2", nx: true) # => [0, -2]
317
+ #
318
+ # @param [String] key
319
+ # @param [Integer] ttl
320
+ # @param [Hash] options
321
+ # - `:nx => true`: Set expiry only when the member has no expiry.
322
+ # - `:xx => true`: Set expiry only when the member has an existing expiry.
323
+ # - `:gt => true`: Set expiry only when the new expiry is greater than current one.
324
+ # - `:lt => true`: Set expiry only when the new expiry is less than current one.
325
+ # @param [Array<String>] members
326
+ # @return [Array<Integer>] per member: `1` set, `0` condition not met,
327
+ # `2` deleted (TTL `0`), `-2` no such member or key.
328
+ # @raise [ArgumentError] when more than one of `:nx`, `:xx`, `:gt`, `:lt` is given
329
+ def spexpire(key, ttl, *members, nx: nil, xx: nil, gt: nil, lt: nil)
330
+ members.flatten!(1)
331
+ args = [:spexpire, key, Integer(ttl)]
332
+ args.concat(hash_field_expiration_condition(nx, xx, gt, lt))
333
+ args.concat(['MEMBERS', members.length, *members])
334
+
335
+ send_command(args)
336
+ end
337
+
338
+ # Sets the expiration for one or more set members as an absolute Unix
339
+ # timestamp in seconds. A timestamp in the past removes the member
340
+ # immediately.
341
+ #
342
+ # @example
343
+ # redis.sadd("set", "m1")
344
+ # redis.sexpireat("set", Time.now.to_i + 10, "m1", "m2") # => [1, -2]
345
+ # redis.sexpireat("set", Time.now.to_i - 10, "m1") # => [2]
346
+ #
347
+ # @param [String] key
348
+ # @param [Integer] unix_time_seconds absolute expiration timestamp in seconds since epoch
349
+ # @param [Hash] options
350
+ # - `:nx => true`: Set expiry only when the member has no expiry.
351
+ # - `:xx => true`: Set expiry only when the member has an existing expiry.
352
+ # - `:gt => true`: Set expiry only when the new expiry is greater than current one.
353
+ # - `:lt => true`: Set expiry only when the new expiry is less than current one.
354
+ # @param [Array<String>] members
355
+ # @return [Array<Integer>] per member: `1` set, `0` condition not met,
356
+ # `2` deleted (past timestamp), `-2` no such member or key.
357
+ # @raise [ArgumentError] when more than one of `:nx`, `:xx`, `:gt`, `:lt` is given
358
+ def sexpireat(key, unix_time_seconds, *members, nx: nil, xx: nil, gt: nil, lt: nil)
359
+ members.flatten!(1)
360
+ args = [:sexpireat, key, Integer(unix_time_seconds)]
361
+ args.concat(hash_field_expiration_condition(nx, xx, gt, lt))
362
+ args.concat(['MEMBERS', members.length, *members])
363
+
364
+ send_command(args)
365
+ end
366
+
367
+ # Sets the expiration for one or more set members as an absolute Unix
368
+ # timestamp in milliseconds. A timestamp in the past removes the member
369
+ # immediately.
370
+ #
371
+ # @example
372
+ # redis.sadd("set", "m1")
373
+ # redis.spexpireat("set", (Time.now.to_f * 1000).to_i + 500, "m1", "m2") # => [1, -2]
374
+ # redis.spexpireat("set", (Time.now.to_f * 1000).to_i - 500, "m1") # => [2]
375
+ #
376
+ # @param [String] key
377
+ # @param [Integer] unix_time_milliseconds absolute expiration timestamp in milliseconds since epoch
378
+ # @param [Hash] options
379
+ # - `:nx => true`: Set expiry only when the member has no expiry.
380
+ # - `:xx => true`: Set expiry only when the member has an existing expiry.
381
+ # - `:gt => true`: Set expiry only when the new expiry is greater than current one.
382
+ # - `:lt => true`: Set expiry only when the new expiry is less than current one.
383
+ # @param [Array<String>] members
384
+ # @return [Array<Integer>] per member: `1` set, `0` condition not met,
385
+ # `2` deleted (past timestamp), `-2` no such member or key.
386
+ # @raise [ArgumentError] when more than one of `:nx`, `:xx`, `:gt`, `:lt` is given
387
+ def spexpireat(key, unix_time_milliseconds, *members, nx: nil, xx: nil, gt: nil, lt: nil)
388
+ members.flatten!(1)
389
+ args = [:spexpireat, key, Integer(unix_time_milliseconds)]
390
+ args.concat(hash_field_expiration_condition(nx, xx, gt, lt))
391
+ args.concat(['MEMBERS', members.length, *members])
392
+
393
+ send_command(args)
394
+ end
395
+
396
+ # Returns the time to live in seconds for one or more set members.
397
+ #
398
+ # @example
399
+ # redis.sadd("set", "m1", "m2")
400
+ # redis.sexpire("set", 10, "m1") # => [1]
401
+ # redis.sttl("set", "m1", "m2", "m3") # => [10, -1, -2]
402
+ #
403
+ # @param [String] key
404
+ # @param [Array<String>] members
405
+ # @return [Array<Integer>] per member: the TTL in seconds, `-1` when the
406
+ # member has no expiry, `-2` when the member or key does not exist.
407
+ def sttl(key, *members)
408
+ members.flatten!(1)
409
+ send_command([:sttl, key, 'MEMBERS', members.length, *members])
410
+ end
411
+
412
+ # Returns the time to live in milliseconds for one or more set members.
413
+ #
414
+ # @example
415
+ # redis.sadd("set", "m1", "m2")
416
+ # redis.spexpire("set", 500, "m1") # => [1]
417
+ # redis.spttl("set", "m1", "m2", "m3") # => [500, -1, -2]
418
+ #
419
+ # @param [String] key
420
+ # @param [Array<String>] members
421
+ # @return [Array<Integer>] per member: the TTL in milliseconds, `-1` when
422
+ # the member has no expiry, `-2` when the member or key does not exist.
423
+ def spttl(key, *members)
424
+ members.flatten!(1)
425
+ send_command([:spttl, key, 'MEMBERS', members.length, *members])
426
+ end
427
+
428
+ # Returns the expiration time of one or more set members as an absolute
429
+ # Unix timestamp in seconds.
430
+ #
431
+ # @example
432
+ # redis.sadd("set", "m1", "m2")
433
+ # redis.sexpireat("set", Time.now.to_i + 100, "m1")
434
+ # redis.sexpiretime("set", "m1", "m2", "m3") # => [<unix timestamp in seconds>, -1, -2]
435
+ #
436
+ # @param [String] key
437
+ # @param [Array<String>] members
438
+ # @return [Array<Integer>] per member: the expiration Unix timestamp in
439
+ # seconds, `-1` when the member has no expiry, `-2` when the member or
440
+ # key does not exist.
441
+ def sexpiretime(key, *members)
442
+ members.flatten!(1)
443
+ send_command([:sexpiretime, key, 'MEMBERS', members.length, *members])
444
+ end
445
+
446
+ # Returns the expiration time of one or more set members as an absolute
447
+ # Unix timestamp in milliseconds.
448
+ #
449
+ # @example
450
+ # redis.sadd("set", "m1", "m2")
451
+ # redis.spexpireat("set", (Time.now.to_f * 1000).to_i + 100_000, "m1")
452
+ # redis.spexpiretime("set", "m1", "m2", "m3") # => [<unix timestamp in milliseconds>, -1, -2]
453
+ #
454
+ # @param [String] key
455
+ # @param [Array<String>] members
456
+ # @return [Array<Integer>] per member: the expiration Unix timestamp in
457
+ # milliseconds, `-1` when the member has no expiry, `-2` when the member
458
+ # or key does not exist.
459
+ def spexpiretime(key, *members)
460
+ members.flatten!(1)
461
+ send_command([:spexpiretime, key, 'MEMBERS', members.length, *members])
462
+ end
463
+
464
+ # Removes the expiration from one or more set members, making them
465
+ # persistent.
466
+ #
467
+ # @example
468
+ # redis.sadd("set", "m1", "m2")
469
+ # redis.sexpire("set", 100, "m1")
470
+ # redis.spersist("set", "m1", "m2", "m3") # => [1, -1, -2]
471
+ #
472
+ # @param [String] key
473
+ # @param [Array<String>] members
474
+ # @return [Array<Integer>] per member: `1` when the expiration was
475
+ # removed, `-1` when the member has no expiry, `-2` when the member or
476
+ # key does not exist.
477
+ def spersist(key, *members)
478
+ members.flatten!(1)
479
+ send_command([:spersist, key, 'MEMBERS', members.length, *members])
480
+ end
481
+
482
+ # Adds one or more members to a set and optionally sets their expiration.
483
+ # Without an expiration option, an existing member's TTL is cleared
484
+ # unless `:keepttl` is given.
485
+ #
486
+ # @example
487
+ # redis.saddex("set", "m1", "m2", ex: 60) # => 1
488
+ # redis.saddex("set", ["m1", "m3"], mnx: true, ex: 60) # => 0
489
+ #
490
+ # @param [String] key
491
+ # @param [Array<String>] members
492
+ # @param [Hash] options
493
+ # - `:mnx => true`: Only apply if none of the members already exist. Mutually
494
+ # exclusive with `:mxx`.
495
+ # - `:mxx => true`: Only apply if all of the members already exist. Mutually
496
+ # exclusive with `:mnx`.
497
+ # - `:ex => Integer`: Set the specified expire time on the members, in seconds.
498
+ # - `:px => Integer`: Set the specified expire time on the members, in milliseconds.
499
+ # - `:exat => Integer`: Set the specified Unix time at which the members will expire, in
500
+ # seconds.
501
+ # - `:pxat => Integer`: Set the specified Unix time at which the members will expire, in
502
+ # milliseconds.
503
+ # - `:keepttl => true`: Retain the time to live already associated with the members.
504
+ # @return [Integer] `1` if the members were added/updated, `0` if the `:mnx`/`:mxx`
505
+ # condition was not met
506
+ # @raise [ArgumentError] when mutually exclusive options are combined
507
+ def saddex(key, *members, mnx: nil, mxx: nil, ex: nil, px: nil, exat: nil, pxat: nil, keepttl: false)
508
+ raise ArgumentError, "mnx and mxx are mutually exclusive" if mnx && mxx
509
+ if [ex, px, exat, pxat, keepttl].count { |option| option } > 1
510
+ raise ArgumentError, "ex, px, exat, pxat, and keepttl are mutually exclusive"
511
+ end
512
+
513
+ members.flatten!(1)
514
+
515
+ args = [:saddex, key]
516
+ args << "MNX" if mnx
517
+ args << "MXX" if mxx
518
+ args << "EX" << Integer(ex) if ex
519
+ args << "PX" << Integer(px) if px
520
+ args << "EXAT" << Integer(exat) if exat
521
+ args << "PXAT" << Integer(pxat) if pxat
522
+ args << "KEEPTTL" if keepttl
523
+ args.concat(['MEMBERS', members.length, *members])
524
+
525
+ send_command(args)
526
+ end
257
527
  end
258
528
  end
259
529
  end
@@ -233,6 +233,107 @@ class Redis
233
233
  end
234
234
  end
235
235
 
236
+ # Atomically move members from one sorted set to another, preserving their scores.
237
+ #
238
+ # @example Move the lowest-scoring member
239
+ # redis.zmove('src', 'dst')
240
+ # #=> [['a', 1.0]]
241
+ # @example Move the two highest-scoring members
242
+ # redis.zmove('src', 'dst', modifier: 'MAX', count: 2)
243
+ # #=> [['d', 4.0], ['c', 3.0]]
244
+ # @example Move every member with a score in (1, 3]
245
+ # redis.zmove('src', 'dst', byscore: ['(1', 3])
246
+ # #=> [['b', 2.0], ['c', 3.0]]
247
+ #
248
+ # @param [String] source source key
249
+ # @param [String] destination destination key
250
+ # @param [String] modifier which members to move, `"MIN"` (default) or `"MAX"`;
251
+ # not allowed together with `byscore`
252
+ # @param [Array<String, Numeric>] byscore `[min, max]` score range to move, lowest score first;
253
+ # bounds are inclusive unless prefixed with `(`, and `-inf`/`+inf` are accepted
254
+ # @param [Integer] count move at most `count` members; without it `MIN`/`MAX` move one
255
+ # member and `byscore` moves the whole range
256
+ #
257
+ # @return [nil, Array<Array<String, Float>>] the moved `[member, score]` pairs, or nil
258
+ # when nothing was moved (missing source, empty range, same source and destination)
259
+ def zmove(source, destination, modifier: nil, byscore: nil, count: nil)
260
+ raise ArgumentError, "Pick either modifier or byscore" if modifier && byscore
261
+
262
+ args = [:zmove, source, destination]
263
+ if byscore
264
+ min, max = byscore
265
+ args << "BYSCORE" << min << max
266
+ else
267
+ modifier ||= "MIN"
268
+ raise ArgumentError, "Pick either MIN or MAX" unless modifier == "MIN" || modifier == "MAX"
269
+
270
+ args << modifier
271
+ end
272
+ args << "COUNT" << Integer(count) if count
273
+
274
+ send_command(args, &FloatifyPairs)
275
+ end
276
+
277
+ # Atomically move the lowest- or highest-scoring members from one sorted set to
278
+ # another, preserving their scores; or block until a member is available or the
279
+ # timeout expires.
280
+ #
281
+ # @example With timeout
282
+ # redis.bzmove('src', 'dst', timeout: 1)
283
+ # #=> [['a', 1.0]], or nil on timeout
284
+ # @example Move up to 3 of the highest-scoring members as soon as any is available
285
+ # redis.bzmove('src', 'dst', modifier: 'MAX', count: 3)
286
+ #
287
+ # @param [String] source source key
288
+ # @param [String] destination destination key
289
+ # @param [Float, Integer] timeout seconds to block, 0 blocks indefinitely
290
+ # @param [String] modifier which members to move, `"MIN"` (default) or `"MAX"`
291
+ # @param [Integer] count move at most `count` members once at least one is available
292
+ #
293
+ # @return [nil, Array<Array<String, Float>>] the moved `[member, score]` pairs, or nil
294
+ # when the timeout expired and nothing was moved
295
+ #
296
+ # @see #zmove
297
+ def bzmove(source, destination, timeout: 0, modifier: "MIN", count: nil)
298
+ raise ArgumentError, "Pick either MIN or MAX" unless modifier == "MIN" || modifier == "MAX"
299
+
300
+ args = [:bzmove, source, destination, modifier, timeout]
301
+ args << "COUNT" << Integer(count) if count
302
+
303
+ send_blocking_command(args, timeout, &FloatifyPairs)
304
+ end
305
+
306
+ # Atomically move the given members from one sorted set to another, preserving
307
+ # their scores.
308
+ #
309
+ # @example Move two members
310
+ # redis.zmovemember('src', 'dst', %w[a b])
311
+ # #=> [['a', 1.0], ['b', 2.0]]
312
+ # @example Move a member only when the destination does not have it yet
313
+ # redis.zmovemember('src', 'dst', 'a', nx: true)
314
+ #
315
+ # @param [String] source source key
316
+ # @param [String] destination destination key
317
+ # @param [String, Array<String>] members one or more members, processed in the given order;
318
+ # members missing from the source are skipped, duplicates are moved once
319
+ # @param [Boolean] nx only move members the destination does not have
320
+ # @param [Boolean] xx only move members the destination already has (their score is overwritten)
321
+ #
322
+ # @return [nil, Array<Array<String, Float>>] the moved `[member, score]` pairs in the given
323
+ # order, or nil when nothing was moved
324
+ def zmovemember(source, destination, members, nx: nil, xx: nil)
325
+ raise ArgumentError, "Pick either NX or XX" if nx && xx
326
+
327
+ members = Array(members)
328
+ args = [:zmovemember, source, destination]
329
+ args << "NX" if nx
330
+ args << "XX" if xx
331
+ args << "MEMBERS" << members.size
332
+ args.concat(members)
333
+
334
+ send_command(args, &FloatifyPairs)
335
+ end
336
+
236
337
  # Removes and returns up to count members with the highest scores in the sorted set stored at keys,
237
338
  # or block until one is available.
238
339
  #
@@ -463,9 +564,10 @@ class Redis
463
564
  # @param [String] key
464
565
  # @param [String] member
465
566
  #
466
- # @return [Integer, [Integer, Float]]
567
+ # @return [Integer, [Integer, Float], nil]
467
568
  # - when `:with_score` is not specified, an Integer
468
569
  # - when `:with_score` is specified, a `[rank, score]` pair
570
+ # - `nil` when the key or the member does not exist
469
571
  def zrank(key, member, withscore: false, with_score: withscore)
470
572
  args = [:zrank, key, member]
471
573
 
@@ -490,9 +592,10 @@ class Redis
490
592
  # @param [String] key
491
593
  # @param [String] member
492
594
  #
493
- # @return [Integer, [Integer, Float]]
595
+ # @return [Integer, [Integer, Float], nil]
494
596
  # - when `:with_score` is not specified, an Integer
495
597
  # - when `:with_score` is specified, a `[rank, score]` pair
598
+ # - `nil` when the key or the member does not exist
496
599
  def zrevrank(key, member, withscore: false, with_score: withscore)
497
600
  args = [:zrevrank, key, member]
498
601
 
@@ -725,7 +828,7 @@ class Redis
725
828
  # @param [Hash] options
726
829
  # - `:weights => [Float, Float, ...]`: weights to associate with source
727
830
  # sorted sets
728
- # - `:aggregate => String`: aggregate function to use (sum, min, max, ...)
831
+ # - `:aggregate => String`: aggregate function to use (sum, min, max; count since Redis 8.8)
729
832
  # - `:with_scores => true`: include scores in output
730
833
  #
731
834
  # @return [Array<String>, Array<[String, Float]>]
@@ -736,6 +839,28 @@ class Redis
736
839
  end
737
840
  ruby2_keywords(:zinter) if respond_to?(:ruby2_keywords, true)
738
841
 
842
+ # Get the number of members in the intersection of multiple sorted sets.
843
+ #
844
+ # @example
845
+ # redis.zadd("zsetA", [[1, "v1"], [2, "v2"], [3, "v3"]])
846
+ # redis.zadd("zsetB", [[1, "v2"], [2, "v3"], [3, "v4"]])
847
+ # redis.zintercard("zsetA", "zsetB")
848
+ # # => 2
849
+ # @example Stop counting once the intersection reaches 1 member
850
+ # redis.zintercard("zsetA", "zsetB", limit: 1)
851
+ # # => 1
852
+ #
853
+ # @param [String, Array<String>] keys one or more keys to intersect
854
+ # @param [Integer] limit stop counting once the intersection reaches `limit`
855
+ # members (`0` means unlimited)
856
+ # @return [Integer] number of members in the intersection
857
+ def zintercard(*keys, limit: nil)
858
+ keys.flatten!(1)
859
+ args = [:zintercard, keys.size].concat(keys)
860
+ args << "LIMIT" << Integer(limit) if limit
861
+ send_command(args)
862
+ end
863
+
739
864
  # Intersect multiple sorted sets and store the resulting sorted set in a new
740
865
  # key.
741
866
  #
@@ -748,7 +873,7 @@ class Redis
748
873
  # @param [Hash] options
749
874
  # - `:weights => [Array<Float>]`: weights to associate with source
750
875
  # sorted sets
751
- # - `:aggregate => String`: aggregate function to use (sum, min, max)
876
+ # - `:aggregate => String`: aggregate function to use (sum, min, max; count since Redis 8.8)
752
877
  # @return [Integer] number of elements in the resulting sorted set
753
878
  def zinterstore(*args)
754
879
  _zsets_operation_store(:zinterstore, *args)
@@ -768,7 +893,7 @@ class Redis
768
893
  # @param [Hash] options
769
894
  # - `:weights => [Array<Float>]`: weights to associate with source
770
895
  # sorted sets
771
- # - `:aggregate => String`: aggregate function to use (sum, min, max)
896
+ # - `:aggregate => String`: aggregate function to use (sum, min, max; count since Redis 8.8)
772
897
  # - `:with_scores => true`: include scores in output
773
898
  #
774
899
  # @return [Array<String>, Array<[String, Float]>]
@@ -790,7 +915,7 @@ class Redis
790
915
  # @param [Hash] options
791
916
  # - `:weights => [Float, Float, ...]`: weights to associate with source
792
917
  # sorted sets
793
- # - `:aggregate => String`: aggregate function to use (sum, min, max, ...)
918
+ # - `:aggregate => String`: aggregate function to use (sum, min, max; count since Redis 8.8)
794
919
  # @return [Integer] number of elements in the resulting sorted set
795
920
  def zunionstore(*args)
796
921
  _zsets_operation_store(:zunionstore, *args)