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

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 missing
Output(integer) 2"ada""36"(nil)

The reply counts new fields, not written ones:

HSET u a 1 b 2
HSET u a 9 c 3
HGET u a
Output(integer) 2(integer) 1"9"

Reading 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:1
Output(integer) 31) "name"2) "ada"3) "age"4) "36"5) "city"6) "London"1) "name"2) "age"3) "city"

HMGET 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 nope
Output(integer) 31) "ada"2) "London"3) (nil)

Managing fields

HSET u a 1 b 2 c 3
HLEN u
HEXISTS u a
HEXISTS u z
HDEL u a z
HLEN u
Output(integer) 3(integer) 3(integer) 1(integer) 0(integer) 1(integer) 2

Remove the last field and the key itself disappears:

HSET u only 1
HDEL u only
EXISTS u
TYPE u
Output(integer) 1(integer) 1(integer) 0none

HINCRBY

Chapter 3’s atomic counter, per field:

HINCRBY stats views 1
HINCRBY stats views 10
HINCRBYFLOAT stats rate 0.5
HGETALL stats
Output(integer) 1(integer) 11"0.5"1) "views"2) "11"3) "rate"4) "0.5"

A non-numeric field is an error, with its own message:

HSET u name ada
HINCRBY u name 1
Output(integer) 1(error) ERR hash value is not an integer

A hash or many keys

The same user, stored both ways:

HSET user:1 name ada age 36 city London
DBSIZE
Output(integer) 3(integer) 1
MSET user:1:name ada user:1:age 36 user:1:city London
DBSIZE
OutputOK(integer) 3

Per-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 user
Output(integer) 21) (integer) 11) (integer) 1002) (integer) -1

The field goes and the key stays:

HSET s a 1 b 2
HPEXPIRE s 200 FIELDS 1 a
HLEN s
Output(integer) 21) (integer) 1(integer) 2
continues:after=0.6
HLEN s
HGETALL s
EXISTS s
Output(integer) 11) "b"2) "2"(integer) 1

HSCAN

The cursor walk from chapter 2, over fields instead of keys:

HSET h f1 a
HSCAN h 0
Output(integer) 11) "0"2) 1) "f1" 2) "a"

NOVALUES asks for field names only, which halves a large reply:

HSET h f1 a f2 b
HSCAN h 0 NOVALUES
Output(integer) 21) "0"2) 1) "f1" 2) "f2"