Hashes
HSET, HGET, HMGET, and efficient object storage
Skills taught: redis.hashes
Redis Hashes
Hashes store field-value pairs under a single key — like a mini-document. They're perfect for user profiles, session data, and product records where you want to read or update individual fields without loading the whole object.
# Store an object
HSET user:1 name "Alice" email "alice@example.com" age 30 city "London"
# Read one field
HGET user:1 name # "Alice"
# Read multiple fields in one round-trip
HMGET user:1 name email # ["Alice", "alice@example.com"]
# Read all fields
HGETALL user:1
# 1) "name"
# 2) "Alice"
# 3) "email"
# 4) "alice@example.com"
# ...
# Check field existence
HEXISTS user:1 email # 1
HEXISTS user:1 phone # 0
# Count fields
HLEN user:1 # 4
Modifying Hash Fields
# Update one field without touching others
HSET user:1 city "Paris"
# Delete a field
HDEL user:1 phone
# Atomic increment of a numeric field
HSET user:1 loginCount 0
HINCRBY user:1 loginCount 1 # 1
HINCRBY user:1 loginCount 1 # 2
HINCRBYFLOAT user:1 score 1.5 # floating point increment
# Set field only if not exists
HSETNX user:1 role "admin" # only sets if 'role' field doesn't exist
# Get all keys or values
HKEYS user:1 # ["name", "email", "age", "city"]
HVALS user:1 # ["Alice", "alice@example.com", "30", "Paris"]
Session Storage with Hashes
Hashes are ideal for session storage. You can update individual session fields (like last activity) without reading and rewriting the entire session object.
async function createSession(sessionId, userId, data) {
const key = `session:${sessionId}`;
await redis.hSet(key, {
userId,
createdAt: Date.now(),
lastActive: Date.now(),
ip: data.ip,
userAgent: data.userAgent,
});
await redis.expire(key, 86400); // 24-hour session
}
async function touchSession(sessionId) {
// Update just the lastActive field — no full read/write
const key = `session:${sessionId}`;
await redis.hSet(key, 'lastActive', Date.now());
await redis.expire(key, 86400); // extend TTL
}
async function getSessionUser(sessionId) {
// Fetch only what you need
return redis.hGet(`session:${sessionId}`, 'userId');
}
Hash vs JSON String for Objects
- Redis Hash: Native field-value map
- JSON String (GET/SET): Serialized object as a string
Tip: Use HMGET instead of multiple HGET calls to fetch several fields in one network round-trip. For reading the entire object, HGETALL is equivalent but returns all fields — be cautious on large hashes.
Warning: Avoid very large hashes (thousands of fields). For user activity logs or large datasets, use separate keys or Redis Streams instead.
Frequently Asked Questions
How many fields can a Redis hash have?
Up to 2^32 - 1 (over 4 billion) fields. In practice, keep hashes small and focused — large hashes with thousands of fields are better split across multiple keys.
Can I expire a single hash field?
Redis 7.4 added HEXPIRE for field-level expiry, but it's not yet available on all managed services. For older versions, use separate string keys if you need per-field TTL.
What is HSCAN for?
HSCAN iterates over hash fields in cursor-based batches without blocking. Use it instead of HGETALL on very large hashes to avoid a single O(N) blocking operation.