Module: Redis::Commands::Keys

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

Instance Method Summary collapse

Instance Method Details

#copy(source, destination, db: nil, replace: false) ⇒ Boolean

Copy a value from one key to another.

Examples:

Copy a value to another key

redis.set "foo", "value"
  # => "OK"
redis.copy "foo", "bar"
  # => true
redis.get "bar"
  # => "value"

Copy a value to a key in another database

redis.set "foo", "value"
  # => "OK"
redis.copy "foo", "bar", db: 2
  # => true
redis.select 2
  # => "OK"
redis.get "bar"
  # => "value"


349
350
351
352
353
354
355
# File 'lib/redis/commands/keys.rb', line 349

def copy(source, destination, db: nil, replace: false)
  command = [:copy, source, destination]
  command << "DB" << db if db
  command << "REPLACE" if replace

  send_command(command, &Boolify)
end

#del(*keys) ⇒ Integer

Delete one or more keys.



252
253
254
255
256
257
# File 'lib/redis/commands/keys.rb', line 252

def del(*keys)
  keys.flatten!(1)
  return 0 if keys.empty?

  send_command([:del] + keys)
end

#dump(key) ⇒ String

Return a serialized version of the value stored at a key.



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

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

#exists(*keys) ⇒ Integer

Determine how many of the keys exists.



271
272
273
# File 'lib/redis/commands/keys.rb', line 271

def exists(*keys)
  send_command([:exists, *keys])
end

#exists?(*keys) ⇒ Boolean

Determine if any of the keys exists.



279
280
281
282
283
# File 'lib/redis/commands/keys.rb', line 279

def exists?(*keys)
  send_command([:exists, *keys]) do |value|
    value > 0
  end
end

#expire(key, seconds, nx: nil, xx: nil, gt: nil, lt: nil) ⇒ Boolean

Set a key’s time to live in seconds.



82
83
84
85
86
87
88
89
90
# File 'lib/redis/commands/keys.rb', line 82

def expire(key, seconds, nx: nil, xx: nil, gt: nil, lt: nil)
  args = [:expire, key, Integer(seconds)]
  args << "NX" if nx
  args << "XX" if xx
  args << "GT" if gt
  args << "LT" if lt

  send_command(args, &Boolify)
end

#expireat(key, unix_time, nx: nil, xx: nil, gt: nil, lt: nil) ⇒ Boolean

Set the expiration for a key as a UNIX timestamp.



102
103
104
105
106
107
108
109
110
# File 'lib/redis/commands/keys.rb', line 102

def expireat(key, unix_time, nx: nil, xx: nil, gt: nil, lt: nil)
  args = [:expireat, key, Integer(unix_time)]
  args << "NX" if nx
  args << "XX" if xx
  args << "GT" if gt
  args << "LT" if lt

  send_command(args, &Boolify)
end

#expiretime(key) ⇒ Integer

Get a key’s expiry time specified as number of seconds from UNIX Epoch



116
117
118
# File 'lib/redis/commands/keys.rb', line 116

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

#keys(pattern = "*") ⇒ Array<String>

Find all keys matching the given pattern.

See the [Redis Server KEYS documentation](redis.io/docs/latest/commands/keys/) for further details



291
292
293
294
295
296
297
298
299
# File 'lib/redis/commands/keys.rb', line 291

def keys(pattern = "*")
  send_command([:keys, pattern]) do |reply|
    if reply.is_a?(String)
      reply.split(" ")
    else
      reply
    end
  end
end

#migrate(key, options) ⇒ String

Transfer a key from the connected instance to another instance.



234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/redis/commands/keys.rb', line 234

def migrate(key, options)
  args = [:migrate]
  args << (options[:host] || raise(':host not specified'))
  args << (options[:port] || raise(':port not specified'))
  args << (key.is_a?(String) ? key : '')
  args << (options[:db] || @client.db).to_i
  args << (options[:timeout] || @client.timeout).to_i
  args << 'COPY' if options[:copy]
  args << 'REPLACE' if options[:replace]
  args += ['KEYS', *key] if key.is_a?(Array)

  send_command(args)
end

#move(key, db) ⇒ Boolean

Move a key to another database.

Examples:

Move a key to another database

redis.set "foo", "bar"
  # => "OK"
redis.move "foo", 2
  # => true
redis.exists "foo"
  # => false
redis.select 2
  # => "OK"
redis.exists "foo"
  # => true
redis.get "foo"
  # => "bar"


320
321
322
# File 'lib/redis/commands/keys.rb', line 320

def move(key, db)
  send_command([:move, key, db], &Boolify)
end

#object(*args) ⇒ Object



357
358
359
# File 'lib/redis/commands/keys.rb', line 357

def object(*args)
  send_command([:object] + args)
end

#persist(key) ⇒ Boolean

Remove the expiration from a key.



68
69
70
# File 'lib/redis/commands/keys.rb', line 68

def persist(key)
  send_command([:persist, key], &Boolify)
end

#pexpire(key, milliseconds, nx: nil, xx: nil, gt: nil, lt: nil) ⇒ Boolean

Set a key’s time to live in milliseconds.



146
147
148
149
150
151
152
153
154
# File 'lib/redis/commands/keys.rb', line 146

def pexpire(key, milliseconds, nx: nil, xx: nil, gt: nil, lt: nil)
  args = [:pexpire, key, Integer(milliseconds)]
  args << "NX" if nx
  args << "XX" if xx
  args << "GT" if gt
  args << "LT" if lt

  send_command(args, &Boolify)
end

#pexpireat(key, ms_unix_time, nx: nil, xx: nil, gt: nil, lt: nil) ⇒ Boolean

Set the expiration for a key as number of milliseconds from UNIX Epoch.



166
167
168
169
170
171
172
173
174
# File 'lib/redis/commands/keys.rb', line 166

def pexpireat(key, ms_unix_time, nx: nil, xx: nil, gt: nil, lt: nil)
  args = [:pexpireat, key, Integer(ms_unix_time)]
  args << "NX" if nx
  args << "XX" if xx
  args << "GT" if gt
  args << "LT" if lt

  send_command(args, &Boolify)
end

#pexpiretime(key) ⇒ Integer

Get a key’s expiry time specified as number of milliseconds from UNIX Epoch



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

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

#pttl(key) ⇒ Integer

Get the time to live (in milliseconds) for a key.

In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire.

Starting with Redis 2.8 the return value in case of error changed:

- The command returns -2 if the key does not exist.
- The command returns -1 if the key exists but has no associated expire.


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

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

#randomkeyString

Return a random key from the keyspace.



364
365
366
# File 'lib/redis/commands/keys.rb', line 364

def randomkey
  send_command([:randomkey])
end

#rename(old_name, new_name) ⇒ String

Rename a key. If the new key already exists it is overwritten.



373
374
375
# File 'lib/redis/commands/keys.rb', line 373

def rename(old_name, new_name)
  send_command([:rename, old_name, new_name])
end

#renamenx(old_name, new_name) ⇒ Boolean

Rename a key, only if the new key does not exist.



382
383
384
# File 'lib/redis/commands/keys.rb', line 382

def renamenx(old_name, new_name)
  send_command([:renamenx, old_name, new_name], &Boolify)
end

#restore(key, ttl, serialized_value, replace: nil) ⇒ String

Create a key using the serialized value, previously obtained using DUMP.



216
217
218
219
220
221
# File 'lib/redis/commands/keys.rb', line 216

def restore(key, ttl, serialized_value, replace: nil)
  args = [:restore, key, ttl, serialized_value]
  args << 'REPLACE' if replace

  send_command(args)
end

#scan(cursor, **options) ⇒ String+

Scan the keyspace

See the [Redis Server SCAN documentation](redis.io/docs/latest/commands/scan/) for further details

Examples:

Retrieve the first batch of keys

redis.scan(0)
  # => ["4", ["key:21", "key:47", "key:42"]]

Retrieve a batch of keys matching a pattern

redis.scan(4, :match => "key:1?")
  # => ["92", ["key:13", "key:18"]]

Retrieve a batch of keys of a certain type

redis.scan(92, :type => "zset")
  # => ["173", ["sortedset:14", "sortedset:78"]]


27
28
29
# File 'lib/redis/commands/keys.rb', line 27

def scan(cursor, **options)
  _scan(:scan, cursor, [], **options)
end

#scan_each(**options, &block) ⇒ Enumerator

Scan the keyspace

See the [Redis Server SCAN documentation](redis.io/docs/latest/commands/scan/) for further details

Examples:

Retrieve all of the keys (with possible duplicates)

redis.scan_each.to_a
  # => ["key:21", "key:47", "key:42"]

Execute block for each key matching a pattern

redis.scan_each(:match => "key:1?") {|key| puts key}
  # => key:13
  # => key:18

Execute block for each key of a type

redis.scan_each(:type => "hash") {|key| puts redis.type(key)}
  # => "hash"
  # => "hash"


53
54
55
56
57
58
59
60
61
62
# File 'lib/redis/commands/keys.rb', line 53

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

  cursor = 0
  loop do
    cursor, keys = scan(cursor, **options)
    keys.each(&block)
    break if cursor == "0"
  end
end

#sort(key, by: nil, limit: nil, get: nil, order: nil, store: nil) ⇒ Array<String>, ...

Sort the elements in a list, set or sorted set.

Examples:

Retrieve the first 2 elements from an alphabetically sorted “list”

redis.sort("list", :order => "alpha", :limit => [0, 2])
  # => ["a", "b"]

Store an alphabetically descending list in “target”

redis.sort("list", :order => "desc alpha", :store => "target")
  # => 26


411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/redis/commands/keys.rb', line 411

def sort(key, by: nil, limit: nil, get: nil, order: nil, store: nil)
  args = [:sort, key]
  args << "BY" << by if by

  if limit
    args << "LIMIT"
    args.concat(limit)
  end

  get = Array(get)
  get.each do |item|
    args << "GET" << item
  end

  args.concat(order.split(" ")) if order
  args << "STORE" << store if store

  send_command(args) do |reply|
    if get.size > 1 && !store
      reply.each_slice(get.size).to_a if reply
    else
      reply
    end
  end
end

#ttl(key) ⇒ Integer

Get the time to live (in seconds) for a key.

In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire.

Starting with Redis 2.8 the return value in case of error changed:

- The command returns -2 if the key does not exist.
- The command returns -1 if the key exists but has no associated expire.


132
133
134
# File 'lib/redis/commands/keys.rb', line 132

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

#type(key) ⇒ String

Determine the type stored at key.



441
442
443
# File 'lib/redis/commands/keys.rb', line 441

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

Unlink one or more keys.



263
264
265
# File 'lib/redis/commands/keys.rb', line 263

def unlink(*keys)
  send_command([:unlink] + keys)
end