Hashes
One key, many fields — and per-field expiry.
Chapter 3 stored a user as a JSON string and named the cost: changing one field means rewriting the whole value. A hash is the fix.
HSET and HGET
Fields live inside one key, and HSET takes as many pairs as you like:
HSET user:1 name ada age 36
HGET user:1 name
HGET user:1 age
HGET user:1 missingThe reply counts new fields, not written ones:
HSET u a 1 b 2
HSET u a 9 c 3
HGET u aReading a whole hash
HGETALL returns fields and values interleaved; HKEYS and HVALS return one side each:
HSET user:1 name ada age 36 city London
HGETALL user:1
HKEYS user:1HMGET fetches named fields, with (nil) holding the position of a missing one:
HSET user:1 name ada age 36 city London
HMGET user:1 name city nopeManaging fields
HSET u a 1 b 2 c 3
HLEN u
HEXISTS u a
HEXISTS u z
HDEL u a z
HLEN uRemove the last field and the key itself disappears:
HSET u only 1
HDEL u only
EXISTS u
TYPE uHINCRBY
Chapter 3’s atomic counter, per field:
HINCRBY stats views 1
HINCRBY stats views 10
HINCRBYFLOAT stats rate 0.5
HGETALL statsA non-numeric field is an error, with its own message:
HSET u name ada
HINCRBY u name 1A hash or many keys
The same user, stored both ways:
HSET user:1 name ada age 36 city London
DBSIZEMSET user:1:name ada user:1:age 36 user:1:city London
DBSIZEPer-field expiry
HEXPIRE gives one field a lifetime, and HTTL reads it back:
HSET session:1 token abc user ada
HEXPIRE session:1 100 FIELDS 1 token
HTTL session:1 FIELDS 2 token userThe field goes and the key stays:
HSET s a 1 b 2
HPEXPIRE s 200 FIELDS 1 a
HLEN sHLEN s
HGETALL s
EXISTS sHSCAN
The cursor walk from chapter 2, over fields instead of keys:
HSET h f1 a
HSCAN h 0NOVALUES asks for field names only, which halves a large reply:
HSET h f1 a f2 b
HSCAN h 0 NOVALUES