Hashes are the natural way to keep records like users or sessions while updating fields independently.
A hash is a map of field names to string values stored under one key, like a small row or object: HSET user:42 name Ana plan pro logins 0.
HGET key fieldandHMGET key f1 f2read fields,HGETALL keyreads all of them,HSETcreates or updates one or more fields and returns how many were new,HINCRBY key field nincrements one numeric field atomically,HDEL,HEXISTS,HLEN,HKEYS,HVALSdo what they say, andHSETNXsets a field only if absent.
Compared with a JSON string, a hash lets you change one field without reading and rewriting the whole object, and concurrent updates to different fields don't overwrite each other. Values are flat strings, though; nested structures need either several keys, a serialized field, or the JSON data type built into Redis 8.
Small hashes are stored in a compact listpack encoding, which makes many small hashes very memory efficient compared with many separate string keys.
Expiry normally applies to the whole key. Since Redis 7.4 you can also expire individual fields with HEXPIRE, handy for per-field caches.
HGETALL on a hash with hundreds of thousands of fields is a slow, blocking call; iterate big hashes with HSCAN or keep them bounded.
Example
redis-cli HSET user:42 name Ana plan pro logins 0 # (integer) 3
redis-cli HGET user:42 plan # "pro"
redis-cli HINCRBY user:42 logins 1 # (integer) 1
redis-cli HSET user:42 plan team # (integer) 0 (updated, not new)
redis-cli HMGET user:42 name plan email
# 1) "Ana"
# 2) "team"
# 3) (nil)
redis-cli HGETALL user:42
# 1) "name" 2) "Ana" 3) "plan" 4) "team" 5) "logins" 6) "1"
redis-cli HDEL user:42 logins # (integer) 1
redis-cli HLEN user:42 # (integer) 2Remember
- A hash is a flat field -> string map under one key
- Update one field with HSET or HINCRBY without touching the others
- Small hashes use a compact encoding and save memory
- Expiry is per key; HEXPIRE (7.4+) expires single fields
Watch out for
- Calling HGETALL on huge hashes in hot paths.