You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
A Redis Hash is a map of field-value pairs stored under a single key. It is conceptually similar to a row in a relational database table, a JavaScript object, or a Python dictionary. Hashes are ideal for storing objects such as user profiles, product records, or configuration settings.
HSET stores one or more field-value pairs. HGET retrieves a single field:
127.0.0.1:6379> HSET user:1001 name "Alice" email "alice@example.com" age "30"
(integer) 3
127.0.0.1:6379> HGET user:1001 name
"Alice"
127.0.0.1:6379> HGET user:1001 email
"alice@example.com"
The key user:1001 is a common Redis naming convention — using a colon-separated namespace to group related keys.
Retrieve multiple specific fields at once with HMGET, or every field with HGETALL:
127.0.0.1:6379> HMGET user:1001 name age
1) "Alice"
2) "30"
127.0.0.1:6379> HGETALL user:1001
1) "name"
2) "Alice"
3) "email"
4) "alice@example.com"
5) "age"
6) "30"
HGETALL returns alternating field names and values. In production, prefer HMGET with only the fields you need to avoid transferring unnecessary data.
# Delete a field
127.0.0.1:6379> HDEL user:1001 age
(integer) 1
# Check if a field exists
127.0.0.1:6379> HEXISTS user:1001 age
(integer) 0 # 0 = does not exist
# Count the fields
127.0.0.1:6379> HLEN user:1001
(integer) 2
Like String integers, Hash field values that represent numbers can be incremented atomically:
127.0.0.1:6379> HSET product:42 stock 100
(integer) 1
127.0.0.1:6379> HINCRBY product:42 stock -5
(integer) 95
127.0.0.1:6379> HINCRBYFLOAT product:42 price 0.50
"10.50"
Retrieve only the field names or only the values:
127.0.0.1:6379> HKEYS user:1001
1) "name"
2) "email"
127.0.0.1:6379> HVALS user:1001
1) "Alice"
2) "alice@example.com"
Use a Hash when an entity has multiple attributes that you may want to update independently. Use a String (with a serialised JSON value) when you always read and write the entire object as a unit. Hashes are more memory-efficient for objects with many fields because Redis uses a compact encoding (ziplist or listpack) for small hashes.
Hashes are among the most practical Redis types for real-world application data modelling.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.