Skip to content
Sign inGet all access
Chapter 3·10 minFree

Strings and Numbers

The type that is not just text — counters, buffers and the float surprise.

Chapter 1 used SET and GET. The string type is also where Redis keeps counters, which is the reason many people reach for it.

Get and replace

Reading and writing in one round trip, with the old value coming back:

SET k old
SET k new GET
GET k
OutputOK"old""new"

GETDEL reads and removes:

SET visits 10
GETDEL visits
EXISTS visits
OutputOK"10"(integer) 0

MSET and MGET

One round trip for many keys:

MSET a 1 b 2 c 3
MGET a b c missing
OutputOK1) "1"2) "2"3) "3"4) (nil)

MSETNX is all-or-nothing. One existing key refuses the whole batch:

SET a 1
MSETNX a 9 b 2
EXISTS b
OutputOK(integer) 0(integer) 0

INCR and DECR

INCR needs no initialisation. A missing key counts as zero:

INCR counter
INCRBY counter 5
DECR counter
DECRBY counter 3
Output(integer) 1(integer) 6(integer) 5(integer) 2

The value is still a string, and it must look like an integer:

SET name ada
INCR name
OutputOK(error) ERR value is not an integer or out of range

Steps and floats

INCRBYFLOAT takes a decimal step, including a negative one:

SET price 10.50
INCRBYFLOAT price 0.25
INCRBYFLOAT price -1
OutputOK"10.75""9.75"

Now the surprise. This is 0.1 + 0.2, and the answer is not what your language gives you:

SET x 0.1
INCRBYFLOAT x 0.2
OutputOK"0.3"

One INCRBYFLOAT makes a key permanently non-integer:

SET n 5
INCRBYFLOAT n 0.5
INCR n
OutputOK"5.5"(error) ERR value is not an integer or out of range

Strings as buffers

APPEND adds to the end, creating the key if needed, and returns the new length:

APPEND fresh "abc"
GET fresh
Output(integer) 3"abc"

STRLEN and GETRANGE read without fetching the whole value:

SET log "line1"
APPEND log " line2"
STRLEN log
GETRANGE log 0 4
GETRANGE log -5 -1
OutputOK(integer) 11(integer) 11"line1""line2"

SETRANGE

It overwrites in place, from an offset:

SET greet "hello world"
SETRANGE greet 6 "redis"
GET greet
OutputOK(integer) 11"hello redis"

Writing past the end extends the string, and the gap is filled with zero bytes:

SET s "ab"
SETRANGE s 5 "z"
GET s
OutputOK(integer) 6"ab\x00\x00\x00z"

Storing JSON

The most common pattern in Redis, and it works:

SET user:1 '{"name":"ada","age":36}'
GET user:1
STRLEN user:1
OutputOK"{\"name\":\"ada\",\"age\":36}"(integer) 23