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 kGETDEL reads and removes:
SET visits 10
GETDEL visits
EXISTS visitsMSET and MGET
One round trip for many keys:
MSET a 1 b 2 c 3
MGET a b c missingMSETNX is all-or-nothing. One existing key refuses the whole batch:
SET a 1
MSETNX a 9 b 2
EXISTS bINCR and DECR
INCR needs no initialisation. A missing key counts as zero:
INCR counter
INCRBY counter 5
DECR counter
DECRBY counter 3The value is still a string, and it must look like an integer:
SET name ada
INCR nameSteps and floats
INCRBYFLOAT takes a decimal step, including a negative one:
SET price 10.50
INCRBYFLOAT price 0.25
INCRBYFLOAT price -1Now 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.2One INCRBYFLOAT makes a key permanently non-integer:
SET n 5
INCRBYFLOAT n 0.5
INCR nStrings as buffers
APPEND adds to the end, creating the key if needed, and returns the new length:
APPEND fresh "abc"
GET freshSTRLEN and GETRANGE read without fetching the whole value:
SET log "line1"
APPEND log " line2"
STRLEN log
GETRANGE log 0 4
GETRANGE log -5 -1SETRANGE
It overwrites in place, from an offset:
SET greet "hello world"
SETRANGE greet 6 "redis"
GET greetWriting past the end extends the string, and the gap is filled with zero bytes:
SET s "ab"
SETRANGE s 5 "z"
GET sStoring JSON
The most common pattern in Redis, and it works:
SET user:1 '{"name":"ada","age":36}'
GET user:1
STRLEN user:1