Core Commands and Data StructuresLesson 2.2
Redis Hash commands: HSET, HGET, HMGET, HDEL, HGETALL
HSET multiple fields, HGET, HMGET, HGETALL, HDEL, HEXISTS, HLEN, HINCRBY, hash vs string tradeoffs
Working with Hashes
A Hash stores multiple field-value pairs under one key. It is the natural fit for objects like users, products, or config records.
Writing and reading fields
# Set multiple fields at once (Redis 4+)
HSET user:42 name "Alice" age 30 email "alice@example.com"
# Read one field
HGET user:42 name # โ "Alice"
# Read multiple fields
HMGET user:42 name email # โ ["Alice", "alice@example.com"]
# Read all fields
HGETALL user:42
# โ { name: Alice, age: 30, email: alice@example.com }Checking and deleting
HEXISTS user:42 phone # โ 0 (field absent)
HDEL user:42 email # removes the email field
HLEN user:42 # โ 2 (fields remaining)Numeric fields
HINCRBY user:42 age 1 # increments age atomically โ 31Hash vs multiple Strings
Storing user:42:name, user:42:age as separate String keys works but wastes memory due to per-key overhead. A Hash collapses all fields under one key and uses a compact encoding (ziplist) for small hashes, saving significant memory. Use Hashes when an object has multiple attributes you read together.
