Hashes
Hashes — a flat dictionary under one key
Section titled “Hashes — a flat dictionary under one key”Redis Hashes store multiple field-value pairs under a single key. Think of it as a flat dictionary or a row in a database — one key holds many named fields.
HSET and HGET
Section titled “HSET and HGET”HSET key field value [field value ...] sets one or more fields. Redis 7+ allows multiple field-value pairs in a single call. HGET key field retrieves one field by name. If the field does not exist, Redis returns (nil).
127.0.0.1:6379> HSET product:1 name "Redis Mug" price "12.99" stock "200"(integer) 3127.0.0.1:6379> HGET product:1 name"Redis Mug"127.0.0.1:6379> HGET product:1 price"12.99"127.0.0.1:6379> HGET product:1 missing-field(nil)HSET product:1 name "Redis Mug" price "12.99" stock "200"
HGET product:1 name
HGET product:1 price
HGET product:1 missing-fieldHMGET and HGETALL
Section titled “HMGET and HGETALL”HMGET key field [field ...] fetches multiple fields in one round-trip and returns (nil) for any field that does not exist. HGETALL key returns every field-value pair in the hash as an alternating list of field names and values.
127.0.0.1:6379> HMGET product:1 name stock1) "Redis Mug"2) "200"127.0.0.1:6379> HGETALL product:11) "name"2) "Redis Mug"3) "price"4) "12.99"5) "stock"6) "200"HMGET product:1 name stock
HGETALL product:1HDEL and HEXISTS
Section titled “HDEL and HEXISTS”HDEL key field [field ...] removes one or more fields and returns the number of fields actually deleted. HEXISTS key field returns 1 if the field exists, 0 if it does not — useful for conditional logic without fetching the value itself.
127.0.0.1:6379> HEXISTS product:1 price(integer) 1127.0.0.1:6379> HEXISTS product:1 color(integer) 0127.0.0.1:6379> HDEL product:1 price(integer) 1127.0.0.1:6379> HEXISTS product:1 price(integer) 0HSET product:1 name "Redis Mug" price "12.99" stock "200"
HEXISTS product:1 price
HEXISTS product:1 color
HDEL product:1 price
HEXISTS product:1 price
HKEYS product:1
HVALS product:1
HLEN product:1HKEYS, HVALS, and HLEN
Section titled “HKEYS, HVALS, and HLEN”HKEYS key returns all field names. HVALS key returns all field values. HLEN key returns the total number of fields in the hash. After deleting price above, the hash now has two fields: name and stock.
127.0.0.1:6379> HKEYS product:11) "name"2) "stock"127.0.0.1:6379> HVALS product:11) "Redis Mug"2) "200"127.0.0.1:6379> HLEN product:1(integer) 2