Module: Redis::Commands::Strings

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

Instance Method Summary collapse

Instance Method Details

#append(key, value) ⇒ Integer

Append a value to a key.

Parameters:

  • key (String)
  • value (String) —

    value to append

Returns:

  • (Integer) —

    length of the string after appending



408
409
410
# File 'lib/redis/commands/strings.rb', line 408

def append(key, value)
  send_command([:append, key, value])
end

#decr(key) ⇒ Integer

Decrement the integer value of a key by one.

Examples:

redis.decr("value")
  # => 4

Parameters:

  • key (String)

Returns:

  • (Integer) —

    value after decrementing it



14
15
16
# File 'lib/redis/commands/strings.rb', line 14

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

#decrby(key, decrement) ⇒ Integer

Decrement the integer value of a key by the given number.

Examples:

redis.decrby("value", 5)
  # => 0

Parameters:

  • key (String)
  • decrement (Integer)

Returns:

  • (Integer) —

    value after decrementing it



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

def decrby(key, decrement)
  send_command([:decrby, key, Integer(decrement)])
end

#delex(key, ifeq: nil, ifne: nil, ifdeq: nil, ifdne: nil) ⇒ Integer

Delete a key, optionally only if its current value or value digest matches a condition.

Examples:

Without options

redis.delex("foo")
  # => 1

With IFEQ

redis.delex("foo", ifeq: "bar")
  # => 1 (if the current value of "foo" was "bar"), 0 otherwise

Parameters:

  • key (String)
  • options (Hash) —
    • :ifeq => String: Only delete the key if its current value equals the given value. Mutually exclusive with :ifne, :ifdeq, and :ifdne.
    • :ifne => String: Only delete the key if its current value does not equal the given value. Mutually exclusive with :ifeq, :ifdeq, and :ifdne.
    • :ifdeq => String: Only delete the key if the digest of its current value (see #digest) equals the given digest. Mutually exclusive with :ifeq, :ifne, and :ifdne.
    • :ifdne => String: Only delete the key if the digest of its current value does not equal the given digest. Mutually exclusive with :ifeq, :ifne, and :ifdeq.

Returns:

  • (Integer) —

    1 if the key was deleted, 0 if it did not exist or the condition was not met



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/redis/commands/strings.rb', line 238

def delex(key, ifeq: nil, ifne: nil, ifdeq: nil, ifdne: nil)
  # Value-bearing options: a deliberately-passed `false` must count as given —
  # only `nil` means "not given" (see #set).
  if [ifeq, ifne, ifdeq, ifdne].count { |option| !option.nil? } > 1
    raise ArgumentError, "ifeq, ifne, ifdeq, and ifdne are mutually exclusive"
  end

  args = [:delex, key]
  args << "IFEQ" << ifeq.to_s unless ifeq.nil?
  args << "IFNE" << ifne.to_s unless ifne.nil?
  args << "IFDEQ" << ifdeq.to_s unless ifdeq.nil?
  args << "IFDNE" << ifdne.to_s unless ifdne.nil?

  send_command(args)
end

#digest(key) ⇒ String?

Compute a digest of the string value stored at a key, suitable for later comparison via SET's :ifdeq/:ifdne or DELEX's :ifdeq/:ifdne options without transmitting the full value.

Examples:

redis.set("foo", "bar")
redis.digest("foo")
  # => "<hex digest>"

Parameters:

  • key (String)

Returns:

  • (String, nil) —

    the digest of the value stored at key, as a 16-character lowercase hex String, or nil if the key does not exist



469
470
471
# File 'lib/redis/commands/strings.rb', line 469

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

#get(key) ⇒ String

Get the value of a key.

Parameters:

  • key (String)

Returns:

  • (String)


343
344
345
# File 'lib/redis/commands/strings.rb', line 343

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

#getdel(key) ⇒ String

Get the value of key and delete the key. This command is similar to GET, except for the fact that it also deletes the key on success.

Parameters:

  • key (String)

Returns:

  • (String) —

    the old value stored in the key, or nil if the key did not exist



428
429
430
# File 'lib/redis/commands/strings.rb', line 428

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

#getex(key, ex: nil, px: nil, exat: nil, pxat: nil, persist: false) ⇒ String

Get the value of key and optionally set its expiration. GETEX is similar to GET, but is a write command with additional options. When no options are provided, GETEX behaves like GET.

Parameters:

  • key (String)
  • options (Hash) —
    • :ex => Integer: Set the specified expire time, in seconds.
    • :px => Integer: Set the specified expire time, in milliseconds.
    • :exat => true: Set the specified Unix time at which the key will expire, in seconds.
    • :pxat => true: Set the specified Unix time at which the key will expire, in milliseconds.
    • :persist => true: Remove the time to live associated with the key.

Returns:

  • (String) —

    The value of key, or nil when key does not exist.



446
447
448
449
450
451
452
453
454
455
# File 'lib/redis/commands/strings.rb', line 446

def getex(key, ex: nil, px: nil, exat: nil, pxat: nil, persist: false)
  args = [:getex, key]
  args << "EX" << Integer(ex) if ex
  args << "PX" << Integer(px) if px
  args << "EXAT" << Integer(exat) if exat
  args << "PXAT" << Integer(pxat) if pxat
  args << "PERSIST" if persist

  send_command(args)
end

#getrange(key, start, stop) ⇒ Integer

Get a substring of the string stored at a key.

Parameters:

  • key (String)
  • start (Integer) —

    zero-based start offset

  • stop (Integer) —

    zero-based end offset. Use -1 for representing the end of the string

Returns:

  • (Integer) —

    0 or 1



399
400
401
# File 'lib/redis/commands/strings.rb', line 399

def getrange(key, start, stop)
  send_command([:getrange, key, Integer(start), Integer(stop)])
end

#getset(key, value) ⇒ String

Set the string value of a key and return its old value.

Parameters:

  • key (String)
  • value (String) —

    value to replace the current value with

Returns:

  • (String) —

    the old value stored in the key, or nil if the key did not exist



418
419
420
# File 'lib/redis/commands/strings.rb', line 418

def getset(key, value)
  send_command([:getset, key, value.to_s])
end

#incr(key) ⇒ Integer

Increment the integer value of a key by one.

Examples:

redis.incr("value")
  # => 6

Parameters:

  • key (String)

Returns:

  • (Integer) —

    value after incrementing it



39
40
41
# File 'lib/redis/commands/strings.rb', line 39

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

#incrby(key, increment) ⇒ Integer

Increment the integer value of a key by the given integer number.

Examples:

redis.incrby("value", 5)
  # => 10

Parameters:

  • key (String)
  • increment (Integer)

Returns:

  • (Integer) —

    value after incrementing it



52
53
54
# File 'lib/redis/commands/strings.rb', line 52

def incrby(key, increment)
  send_command([:incrby, key, Integer(increment)])
end

#incrbyfloat(key, increment) ⇒ Float

Increment the numeric value of a key by the given float number.

Examples:

redis.incrbyfloat("value", 1.23)
  # => 1.23

Parameters:

  • key (String)
  • increment (Float)

Returns:

  • (Float) —

    value after incrementing it



65
66
67
# File 'lib/redis/commands/strings.rb', line 65

def incrbyfloat(key, increment)
  send_command([:incrbyfloat, key, Float(increment)], &Floatify)
end

#increx(key, by: nil, lbound: nil, ubound: nil, saturate: nil, ex: nil, px: nil, exat: nil, pxat: nil, persist: nil, enx: nil) ⇒ Array(Integer, Integer), Array(Float, Float)

Increment the numeric value of a key atomically, with optional bounds and expiration control. Uses 0 as the initial value if the key does not exist.

Unlike incr/incrby, the reply is a two-element array of the new value and the increment that was actually applied. When the result would fall outside lbound:/ubound: (or the type limits) the operation is skipped and the reply is [current_value, 0]; with saturate: true the result is capped at the bound instead and the second element reflects the saturated delta.

Examples:

Increment by 1 (integer mode default)

redis.increx("counter")
  # => [1, 1]

Window counter rate limiter: cap at 100, TTL only on window creation

value, applied = redis.increx("ratelimit:#{user_id}", by: 1, ubound: 100, ex: 60, enx: true)
reject_request if applied == 0

Float mode — selected by the Ruby type of by:

redis.increx("temp", by: 0.25)
  # => [1.75, 0.25]

Parameters:

  • key (String)
  • by (Integer, Float) (defaults to: nil) —

    the increment (may be negative). The Ruby type selects the mode: an Integer is sent as BYINT (requires an integer-typed stored value, replies with Integers), a Float as BYFLOAT (stored value may be integer or float, replies with Floats) — so by: 5 and by: 5.0 behave differently. Other types raise TypeError. Without by:, increments by 1 in integer mode.

  • lbound (Integer, Float) (defaults to: nil) —

    lower bound for the result. In float mode any numeric is accepted; in integer mode it must be an Integer (a Float raises TypeError rather than silently truncating, since bounds decide whether the increment applies)

  • ubound (Integer, Float) (defaults to: nil) —

    upper bound for the result, with the same typing rules as lbound

  • saturate (Boolean) (defaults to: nil) —

    cap/floor an out-of-bounds result at the bound instead of skipping the operation

  • ex (Integer) (defaults to: nil) —

    expiration in seconds

  • px (Integer) (defaults to: nil) —

    expiration in milliseconds

  • exat (Integer) (defaults to: nil) —

    expiration as a Unix timestamp in seconds

  • pxat (Integer) (defaults to: nil) —

    expiration as a Unix timestamp in milliseconds

  • persist (Boolean) (defaults to: nil) —

    remove the key's expiration

  • enx (Boolean) (defaults to: nil) —

    only set the expiration when the key has no TTL (the increment is applied regardless); requires one of ex/px/exat/pxat

Returns:

  • (Array(Integer, Integer), Array(Float, Float)) —

    [new_value, applied_increment] — Integers in integer mode, Floats in float mode (under RESP2 and RESP3 alike); applied_increment is 0 when the operation was skipped as out of bounds

Raises:

  • (ArgumentError)


117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/redis/commands/strings.rb', line 117

def increx(key, by: nil, lbound: nil, ubound: nil, saturate: nil,
           ex: nil, px: nil, exat: nil, pxat: nil, persist: nil, enx: nil)
  if [ex, px, exat, pxat, persist].count { |option| option } > 1
    raise ArgumentError, "ex, px, exat, pxat and persist are mutually exclusive"
  end
  raise ArgumentError, "enx is incompatible with persist" if enx && persist
  raise ArgumentError, "enx requires one of ex, px, exat or pxat" if enx && !(ex || px || exat || pxat)

  # The Ruby type of `by` selects the wire mode; anything else would
  # have to silently pick a mode, so it is rejected instead.
  float_mode = case by
  when nil, Integer then false
  when Float then true
  else raise TypeError, "by must be an Integer (BYINT) or a Float (BYFLOAT), got #{by.class}"
  end

  args = [:increx, key]
  args << (float_mode ? "BYFLOAT" : "BYINT") << by if by
  args << "LBOUND" << increx_bound(:lbound, lbound, float_mode) if lbound
  args << "UBOUND" << increx_bound(:ubound, ubound, float_mode) if ubound
  args << "SATURATE" if saturate
  args << "EX" << Integer(ex) if ex
  args << "PX" << Integer(px) if px
  args << "EXAT" << Integer(exat) if exat
  args << "PXAT" << Integer(pxat) if pxat
  args << "PERSIST" if persist
  args << "ENX" if enx

  if float_mode
    # RESP2 replies with bulk strings, RESP3 with native doubles;
    # converge both on Float.
    send_command(args) { |reply| reply.is_a?(Array) ? reply.map(&Floatify) : reply }
  else
    send_command(args)
  end
end

#lcs(key1, key2, len: false, idx: false, minmatchlen: nil, withmatchlen: false) ⇒ String, ...

Find the longest common subsequence of the strings stored at two keys.

Matching characters need not be contiguous: the LCS of "foo" and "fao" is "fo". Runs in O(N*M) on the server, so keep the strings small.

Examples:

Get the subsequence

redis.mset("key1", "ohmytext", "key2", "mynewtext")
redis.lcs("key1", "key2")
  # => "mytext"

Get only its length

redis.lcs("key1", "key2", len: true)
  # => 6

Get the match positions, last match first

redis.lcs("key1", "key2", idx: true)
  # => { "matches" => [[[4, 7], [5, 8]], [[2, 3], [0, 1]]], "len" => 6 }

Only matches of at least 4 characters, each with its length

redis.lcs("key1", "key2", idx: true, minmatchlen: 4, withmatchlen: true)
  # => { "matches" => [[[4, 7], [5, 8], 4]], "len" => 6 }

Parameters:

  • key1 (String)
  • key2 (String)
  • options (Hash) —
    • :len => true: return the length of the subsequence instead of the subsequence
    • :idx => true: return the match positions instead of the subsequence
    • :minmatchlen => Integer: (idx) only report matches at least this long
    • :withmatchlen => true: (idx) append each match's length to its entry

Returns:

  • (String, Integer, Hash) —
    • by default, the subsequence ("" when there is none)
    • with :len, its length
    • with :idx, { "matches" => [[[start1, end1], [start2, end2], (len)], ...], "len" => Integer }


513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'lib/redis/commands/strings.rb', line 513

def lcs(key1, key2, len: false, idx: false, minmatchlen: nil, withmatchlen: false)
  args = [:lcs, key1, key2]
  args << "LEN" if len
  args << "IDX" if idx
  args << "MINMATCHLEN" << Integer(minmatchlen) if minmatchlen
  args << "WITHMATCHLEN" if withmatchlen

  if idx
    send_command(args, &Hashify)
  else
    send_command(args)
  end
end

#mapped_mget(*keys) ⇒ Hash

Get the values of all the given keys.

Examples:

redis.mapped_mget("key1", "key2")
  # => { "key1" => "v1", "key2" => "v2" }

Parameters:

  • keys (Array<String>) —

    array of keys

Returns:

  • (Hash) —

    a hash mapping the specified keys to their values

See Also:



372
373
374
375
376
377
378
379
380
# File 'lib/redis/commands/strings.rb', line 372

def mapped_mget(*keys)
  mget(*keys) do |reply|
    if reply.is_a?(Array)
      Hash[keys.zip(reply)]
    else
      reply
    end
  end
end

#mapped_mset(hash) ⇒ String

Set one or more values.

Examples:

redis.mapped_mset({ "f1" => "v1", "f2" => "v2" })
  # => "OK"

Parameters:

  • hash (Hash) —

    keys mapping to values

Returns:

  • (String) —

    "OK"

See Also:



307
308
309
# File 'lib/redis/commands/strings.rb', line 307

def mapped_mset(hash)
  mset(hash.flatten)
end

#mapped_msetnx(hash) ⇒ Boolean

Set one or more values, only if none of the keys exist.

Examples:

redis.mapped_msetnx({ "key1" => "v1", "key2" => "v2" })
  # => true

Parameters:

  • hash (Hash) —

    keys mapping to values

Returns:

  • (Boolean) —

    whether or not all values were set

See Also:



335
336
337
# File 'lib/redis/commands/strings.rb', line 335

def mapped_msetnx(hash)
  msetnx(hash.flatten)
end

#mget(*keys, &blk) ⇒ Array<String>

Get the values of all the given keys.

Examples:

redis.mget("key1", "key2")
  # => ["v1", "v2"]

Parameters:

  • keys (Array<String>)

Returns:

  • (Array<String>) —

    an array of values for the specified keys

See Also:



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

def mget(*keys, &blk)
  keys.flatten!(1)
  send_command([:mget, *keys], &blk)
end

#mset(*args) ⇒ String

Set one or more values.

Examples:

redis.mset("key1", "v1", "key2", "v2")
  # => "OK"

Parameters:

  • args (Array<String>) —

    array of keys and values

Returns:

  • (String) —

    "OK"

See Also:



293
294
295
# File 'lib/redis/commands/strings.rb', line 293

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

#msetnx(*args) ⇒ Boolean

Set one or more values, only if none of the keys exist.

Examples:

redis.msetnx("key1", "v1", "key2", "v2")
  # => true

Parameters:

  • args (Array<String>) —

    array of keys and values

Returns:

  • (Boolean) —

    whether or not all values were set

See Also:



321
322
323
# File 'lib/redis/commands/strings.rb', line 321

def msetnx(*args)
  send_command([:msetnx, *args], &Boolify)
end

#psetex(key, ttl, value) ⇒ String

Set the time to live in milliseconds of a key.

Parameters:

  • key (String)
  • ttl (Integer)
  • value (String)

Returns:

  • (String) —

    "OK"



270
271
272
# File 'lib/redis/commands/strings.rb', line 270

def psetex(key, ttl, value)
  send_command([:psetex, key, Integer(ttl), value.to_s])
end

#set(key, value, ex: nil, px: nil, exat: nil, pxat: nil, nx: nil, xx: nil, ifeq: nil, ifne: nil, ifdeq: nil, ifdne: nil, keepttl: nil, get: nil) ⇒ String, Boolean

Set the string value of a key.

Parameters:

  • key (String)
  • value (String)
  • options (Hash) —
    • :ex => Integer: Set the specified expire time, in seconds.
    • :px => Integer: Set the specified expire time, in milliseconds.
    • :exat => Integer : Set the specified Unix time at which the key will expire, in seconds.
    • :pxat => Integer : Set the specified Unix time at which the key will expire, in milliseconds.
    • :nx => true: Only set the key if it does not already exist. Mutually exclusive with :xx, :ifeq, :ifne, :ifdeq, and :ifdne.
    • :xx => true: Only set the key if it already exist. Mutually exclusive with :nx, :ifeq, :ifne, :ifdeq, and :ifdne.
    • :ifeq => String: Only set the key if its current value equals the given value. Mutually exclusive with :nx, :xx, :ifne, :ifdeq, and :ifdne.
    • :ifne => String: Only set the key if its current value does not equal the given value. Mutually exclusive with :nx, :xx, :ifeq, :ifdeq, and :ifdne.
    • :ifdeq => String: Only set the key if the digest of its current value (see #digest) equals the given digest. Mutually exclusive with :nx, :xx, :ifeq, :ifne, and :ifdne.
    • :ifdne => String: Only set the key if the digest of its current value does not equal the given digest. Mutually exclusive with :nx, :xx, :ifeq, :ifne, and :ifdeq.
    • :keepttl => true: Retain the time to live associated with the key.
    • :get => true: Return the old string stored at key, or nil if key did not exist, regardless of whether :nx/:xx/:ifeq/:ifne/:ifdeq/:ifdne was satisfied.

Returns:

  • (String, Boolean) —

    "OK", or true/false if :nx, :xx, :ifeq, :ifne, :ifdeq, or :ifdne is given without :get



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/redis/commands/strings.rb', line 182

def set(key, value, ex: nil, px: nil, exat: nil, pxat: nil, nx: nil, xx: nil,
        ifeq: nil, ifne: nil, ifdeq: nil, ifdne: nil, keepttl: nil, get: nil)
  # nx/xx are pure flags (only truthiness matters); ifeq/ifne/ifdeq/ifdne are
  # value-bearing, so a deliberately-passed `false` (e.g. comparing against the
  # literal string "false") must count as given — only `nil` means "not given".
  active_conditions = [nx, xx, !ifeq.nil?, !ifne.nil?, !ifdeq.nil?, !ifdne.nil?]
  if active_conditions.count { |active| active } > 1
    raise ArgumentError, "nx, xx, ifeq, ifne, ifdeq, and ifdne are mutually exclusive"
  end

  args = [:set, key, value.to_s]
  args << "EX" << Integer(ex) if ex
  args << "PX" << Integer(px) if px
  args << "EXAT" << Integer(exat) if exat
  args << "PXAT" << Integer(pxat) if pxat
  args << "NX" if nx
  args << "XX" if xx
  args << "IFEQ" << ifeq.to_s unless ifeq.nil?
  args << "IFNE" << ifne.to_s unless ifne.nil?
  args << "IFDEQ" << ifdeq.to_s unless ifdeq.nil?
  args << "IFDNE" << ifdne.to_s unless ifdne.nil?
  args << "KEEPTTL" if keepttl
  args << "GET" if get

  # GET always returns the previous value (or nil) verbatim; boolifying it would
  # both mangle a previous value that happened to be "OK" and turn a "key didn't
  # exist" nil into a misleading false.
  if !get && active_conditions.any?
    send_command(args, &BoolifySet)
  else
    send_command(args)
  end
end

#setex(key, ttl, value) ⇒ String

Set the time to live in seconds of a key.

Parameters:

  • key (String)
  • ttl (Integer)
  • value (String)

Returns:

  • (String) —

    "OK"



260
261
262
# File 'lib/redis/commands/strings.rb', line 260

def setex(key, ttl, value)
  send_command([:setex, key, Integer(ttl), value.to_s])
end

#setnx(key, value) ⇒ Boolean

Set the value of a key, only if the key does not exist.

Parameters:

  • key (String)
  • value (String)

Returns:

  • (Boolean) —

    whether the key was set or not



279
280
281
# File 'lib/redis/commands/strings.rb', line 279

def setnx(key, value)
  send_command([:setnx, key, value.to_s], &Boolify)
end

#setrange(key, offset, value) ⇒ Integer

Overwrite part of a string at key starting at the specified offset.

Parameters:

  • key (String)
  • offset (Integer) —

    byte offset

  • value (String)

Returns:

  • (Integer) —

    length of the string after it was modified



388
389
390
# File 'lib/redis/commands/strings.rb', line 388

def setrange(key, offset, value)
  send_command([:setrange, key, Integer(offset), value.to_s])
end

#strlen(key) ⇒ Integer

Get the length of the value stored in a key.

Parameters:

  • key (String)

Returns:

  • (Integer) —

    the length of the value stored in the key, or 0 if the key does not exist



478
479
480
# File 'lib/redis/commands/strings.rb', line 478

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