Module: Redis::Commands::Keys

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

Instance Method Summary collapse

Instance Method Details

#_exists(*keys) ⇒ Object



225
226
227
# File 'lib/redis/commands/keys.rb', line 225

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

#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"

Parameters:

  • source (String)
  • destination (String)
  • db (Integer) (defaults to: nil)
  • replace (Boolean) (defaults to: false)

    removes the ‘destination` key before copying value to it

Returns:

  • (Boolean)

    whether the key was copied or not



301
302
303
304
305
306
307
# File 'lib/redis/commands/keys.rb', line 301

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.

Parameters:

  • keys (String, Array<String>)

Returns:

  • (Integer)

    number of keys that were deleted



188
189
190
191
192
193
# File 'lib/redis/commands/keys.rb', line 188

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.

Parameters:

  • key (String)

Returns:

  • (String)

    serialized_value



139
140
141
# File 'lib/redis/commands/keys.rb', line 139

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

#exists(*keys) ⇒ Integer

Determine how many of the keys exists.

Parameters:

  • keys (String, Array<String>)

Returns:

  • (Integer)


207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/redis/commands/keys.rb', line 207

def exists(*keys)
  if !Redis.exists_returns_integer && keys.size == 1
    if Redis.exists_returns_integer.nil?
      message = "`Redis#exists(key)` will return an Integer in redis-rb 4.3. `exists?` returns a boolean, you " \
        "should use it instead. To opt-in to the new behavior now you can set Redis.exists_returns_integer =  " \
        "true. To disable this message and keep the current (boolean) behaviour of 'exists' you can set " \
        "`Redis.exists_returns_integer = false`, but this option will be removed in 5.0.0. " \
        "(#{::Kernel.caller(1, 1).first})\n"

      ::Redis.deprecate!(message)
    end

    exists?(*keys)
  else
    _exists(*keys)
  end
end

#exists?(*keys) ⇒ Boolean

Determine if any of the keys exists.

Parameters:

  • keys (String, Array<String>)

Returns:

  • (Boolean)


233
234
235
236
237
# File 'lib/redis/commands/keys.rb', line 233

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

#expire(key, seconds) ⇒ Boolean

Set a key’s time to live in seconds.

Parameters:

  • key (String)
  • seconds (Integer)

    time to live

Returns:

  • (Boolean)

    whether the timeout was set or not



73
74
75
# File 'lib/redis/commands/keys.rb', line 73

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

#expireat(key, unix_time) ⇒ Boolean

Set the expiration for a key as a UNIX timestamp.

Parameters:

  • key (String)
  • unix_time (Integer)

    expiry time specified as a UNIX timestamp

Returns:

  • (Boolean)

    whether the timeout was set or not



82
83
84
# File 'lib/redis/commands/keys.rb', line 82

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

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

Find all keys matching the given pattern.

Parameters:

  • pattern (String) (defaults to: "*")

Returns:

  • (Array<String>)


243
244
245
246
247
248
249
250
251
# File 'lib/redis/commands/keys.rb', line 243

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.

Parameters:

  • key (String, Array<String>)
  • options (Hash)
    • ‘:host => String`: host of instance to migrate to

    • ‘:port => Integer`: port of instance to migrate to

    • ‘:db => Integer`: database to migrate to (default: same as source)

    • ‘:timeout => Integer`: timeout (default: same as connection timeout)

    • ‘:copy => Boolean`: Do not remove the key from the local instance.

    • ‘:replace => Boolean`: Replace existing key on the remote instance.

Returns:

  • (String)

    ‘“OK”`



170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/redis/commands/keys.rb', line 170

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"

Parameters:

  • key (String)
  • db (Integer)

Returns:

  • (Boolean)

    whether the key was moved or not



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

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

#object(*args) ⇒ Object



309
310
311
# File 'lib/redis/commands/keys.rb', line 309

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

#persist(key) ⇒ Boolean

Remove the expiration from a key.

Parameters:

  • key (String)

Returns:

  • (Boolean)

    whether the timeout was removed or not



64
65
66
# File 'lib/redis/commands/keys.rb', line 64

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

#pexpire(key, milliseconds) ⇒ Boolean

Set a key’s time to live in milliseconds.

Parameters:

  • key (String)
  • milliseconds (Integer)

    time to live

Returns:

  • (Boolean)

    whether the timeout was set or not



107
108
109
# File 'lib/redis/commands/keys.rb', line 107

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

#pexpireat(key, ms_unix_time) ⇒ Boolean

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

Parameters:

  • key (String)
  • ms_unix_time (Integer)

    expiry time specified as number of milliseconds from UNIX Epoch.

Returns:

  • (Boolean)

    whether the timeout was set or not



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

def pexpireat(key, ms_unix_time)
  send_command([:pexpireat, key, ms_unix_time], &Boolify)
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.

Parameters:

  • key (String)

Returns:

  • (Integer)

    remaining time to live in milliseconds



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

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

#randomkeyString

Return a random key from the keyspace.

Returns:

  • (String)


316
317
318
# File 'lib/redis/commands/keys.rb', line 316

def randomkey
  send_command([:randomkey])
end

#rename(old_name, new_name) ⇒ String

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

Parameters:

  • old_name (String)
  • new_name (String)

Returns:

  • (String)

    ‘OK`



325
326
327
# File 'lib/redis/commands/keys.rb', line 325

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.

Parameters:

  • old_name (String)
  • new_name (String)

Returns:

  • (Boolean)

    whether the key was renamed or not



334
335
336
# File 'lib/redis/commands/keys.rb', line 334

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.

Parameters:

  • key (String)
  • ttl (String)
  • serialized_value (String)
  • options (Hash)
    • ‘:replace => Boolean`: if false, raises an error if key already exists

Returns:

  • (String)

    ‘“OK”`

Raises:



152
153
154
155
156
157
# File 'lib/redis/commands/keys.rb', line 152

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

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"]]

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

    • ‘:type => String`: return keys only of the given type

Returns:

  • (String, Array<String>)

    the next cursor and all found keys



25
26
27
# File 'lib/redis/commands/keys.rb', line 25

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

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

Scan the keyspace

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"

Parameters:

  • options (Hash)
    • ‘:match => String`: only return keys matching the pattern

    • ‘:count => Integer`: return count keys at most per iteration

    • ‘:type => String`: return keys only of the given type

Returns:

  • (Enumerator)

    an enumerator for all found keys



49
50
51
52
53
54
55
56
57
58
# File 'lib/redis/commands/keys.rb', line 49

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

Parameters:

  • key (String)
  • options (Hash)
    • ‘:by => String`: use external key to sort elements by

    • ‘:limit => [offset, count]`: skip `offset` elements, return a maximum

    of ‘count` elements

    • ‘:get => [String, Array<String>]`: single key or array of keys to

    retrieve per element in the result

    • ‘:order => String`: combination of `ASC`, `DESC` and optionally `ALPHA`

    • ‘:store => String`: key to store the result at

Returns:

  • (Array<String>, Array<Array<String>>, Integer)
    • when ‘:get` is not specified, or holds a single element, an array of elements

    • when ‘:get` is specified, and holds more than one element, an array of

    elements where every element is an array with the result for every element specified in ‘:get`

    • when ‘:store` is specified, the number of elements in the stored result



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/redis/commands/keys.rb', line 363

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.

Parameters:

  • key (String)

Returns:

  • (Integer)

    remaining time to live in seconds.



98
99
100
# File 'lib/redis/commands/keys.rb', line 98

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

#type(key) ⇒ String

Determine the type stored at key.

Parameters:

  • key (String)

Returns:

  • (String)

    ‘string`, `list`, `set`, `zset`, `hash` or `none`



393
394
395
# File 'lib/redis/commands/keys.rb', line 393

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

Unlink one or more keys.

Parameters:

  • keys (String, Array<String>)

Returns:

  • (Integer)

    number of keys that were unlinked



199
200
201
# File 'lib/redis/commands/keys.rb', line 199

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