Set and Get Hash Fields
Learn to set and get hash fields in Redis with a hands-on walkthrough. Understand the core concept, compare options, and troubleshoot common issues. This step-by-step lesson is designed for developers building on prior Redis knowledge.
Focus: set and get hash fields
Have you ever needed to store a complex object — say a user profile or configuration — in Redis, only to realize that using simple string keys forces you to serialize and deserialize the entire structure every time you want to read or update a single field? That painful pattern introduces latency, extra code, and risk of data corruption. Redis Hashes solve this exact problem: they let you store and manipulate individual fields inside a single key, making partial updates and reads as cheap as a single command. In this lesson, you'll learn how to set and get hash fields with precision, avoiding common pitfalls and building the muscle memory you need for production systems.
The Problem This Lesson Solves
Storing structured data (e.g., a customer record, session metadata, or game state) in Redis using plain SET/GET for the whole object forces you to:
- Serialize the entire object (e.g., to JSON) on every write.
- Deserialize the entire object on every read, even if you only need one field.
- Risk overwriting unrelated fields when modifying a single attribute.
This approach is slow, wasteful, and error-prone. Redis Hashes provide a native data type that stores field-value pairs under a single key, allowing you to:
- Update one field without affecting others.
- Read one field without fetching the entire object.
- Set multiple fields atomically in a single round trip.
The "set and get hash fields" operation is the foundational building block for this capability.
Core Concept / Mental Model
Think of a Redis Hash as a flat, small dictionary or a two-level namespace:
- Level 1 (Key): The hash key — like a folder or table name. For example,
user:1001. - Level 2 (Fields): Inside that key, you have named slots. For example,
name,email,age.
Each field holds a single string value. You can set, get, check existence of, and delete individual fields without touching the others.
Analogy: A Physical File Folder
Imagine a physical folder labeled "User 1001" (the hash key). Inside that folder are separate sheets of paper: one for Name, one for Email, one for Age. You can:
- Set a field: Pull out the Email sheet, write a new value, and put it back — the Name sheet remains unchanged.
- Get a field: Open the folder, take out only the Name sheet, read it, and return it.
Commands You'll Master
| Command | Purpose |
|---|---|
HSET |
Set one or more fields in a hash. Creates the hash if it does not exist. |
HGET |
Retrieve the value of a single field. |
HMSET |
(Deprecated) Use HSET with multiple field-value pairs. |
HMGET |
Get multiple fields in one command. |
Pro Tip:
HSETis the modern Swiss Army knife — it handles both single and multiple field sets. AvoidHMSETin Redis 4.0.0+; it's been deprecated.
How It Works Step by Step
Let's walk through setting and getting hash fields in a logical order.
Step 1: Set a Single Hash Field
Use HSET <key> <field> <value>.
HSET user:1001 name "Alice Johnson"
- If
user:1001does not exist, Redis creates it as a hash. - Sets the field
nameto"Alice Johnson". - Returns
(integer) 1if a new field was created,(integer) 0if the field already existed and was updated.
Step 2: Set Multiple Fields Atomically
HSET user:1001 email "alice@example.com" age 30 active 1
- Sets
email,age, andactivein one command. - Returns the count of new fields created, e.g.,
(integer) 3.
Step 3: Get a Single Field
HGET user:1001 email
Returns the value "alice@example.com". If the field does not exist, returns (nil).
Step 4: Get Multiple Fields
HMGET user:1001 name age active
Returns an array of values: 1) "Alice Johnson", 2) "30", 3) "1". If a field is missing, (nil) appears in its position.
Step 5: Get All Fields and Values
HGETALL user:1001
Returns an array alternating field names and values, e.g., 1) "name", 2) "Alice Johnson", 3) "email", 4) "alice@example.com", etc.
Hands-On Walkthrough
Let's build a real scenario: tracking a user's session data.
Prerequisites
Assume you have redis-cli installed. Start your Redis server.
Example 1: Storing User Session
redis-cli
> HSET session:abc123 user_id 1001 created_at "2025-01-15T10:00:00Z" ttl 3600
(integer) 3
> HGET session:abc123 user_id
"1001"
> HMGET session:abc123 created_at ttl
1) "2025-01-15T10:00:00Z"
2) "3600"
> HGETALL session:abc123
1) "user_id"
2) "1001"
3) "created_at"
4) "2025-01-15T10:00:00Z"
5) "ttl"
6) "3600"
Example 2: Updating a Single Field
> HSET session:abc123 ttl 1800
(integer) 0 # field already existed, updated
> HGET session:abc123 ttl
"1800"
Example 3: From Python (Using redis-py)
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
# Set multiple fields
r.hset('car:1234', mapping={'make': 'Tesla', 'model': 'Model 3', 'year': 2023})
# Get one field
make = r.hget('car:1234', 'make')
print(make) # Output: Tesla
# Get multiple fields
fields = r.hmget('car:1234', ['make', 'year'])
print(fields) # Output: ['Tesla', '2023']
Expected output:
Tesla
['Tesla', '2023']
Example 4: Checking Field Existence
> HEXISTS car:1234 make
(integer) 1
> HEXISTS car:1234 color
(integer) 0
Compare Options / When to Choose What
| Operation | When to Use | Pros | Cons |
|---|---|---|---|
HSET (single field) |
You need to update exactly one field. | Minimal network overhead. | Multiple commands for multiple fields. |
HSET (multiple fields) |
You need to set several related fields in one atomic operation. | Atomic, one round trip. | Larger payload. |
HGET |
You need the value of one specific field. | Fast, cheap. | Only one field at a time. |
HMGET |
You need values of multiple known fields. | One round trip for multiple fields. | Requires knowing field names ahead. |
HGETALL |
You need every field in the hash. | Complete snapshot. | Memory-intensive for large hashes. |
Rule of Thumb:
- Use
HGETfor single field reads. - Use
HMGETwhen you need 2–5 specific fields. - Use
HGETALLonly for small hashes (e.g., < 100 fields) or debugging. - For large hashes, use
HSCAN(covered in a later lesson) to iterate without blocking.
Troubleshooting & Edge Cases
Problem 1: Field Does Not Exist
> HGET user:9999 nonexistent
(nil)
Fix: Always check with HEXISTS before reading if a missing field has special meaning in your application.
Problem 2: Wrong Data Type
If the key was created as a different type (e.g., a string), HSET and HGET will throw an error:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
Fix: Use TYPE user:1001 to inspect. Delete (DEL) or migrate the key.
Problem 3: Hash Becomes Too Large
A hash with millions of fields will slow down HGETALL and memory usage. Redis is still fast, but HGETALL on a million-field hash blocks the server.
Fix: Limit hash size. Consider sharding (e.g., user:1001:part1, user:1001:part2) or using a sorted set for large collections.
Problem 4: Field Name Collision with Reserved Characters
Field names containing spaces, newlines, or null bytes are technically allowed but can cause confusion in scripts.
Fix: Sanitize field names. Use alphanumeric and underscores for safety.
What You Learned & What's Next
You now understand how to set and get hash fields using the correct Redis commands. You can:
- Store structured data efficiently with
HSET. - Retrieve single or multiple fields with
HGETandHMGET. - Update individual fields without touching the rest.
- Recognize and avoid common pitfalls like wrong data types or oversized hashes.
This foundation unlocks the next step: deleting fields and incrementing numeric fields in hashes (HDEL, HINCRBY). Those commands let you safely remove fields and update counters — essential for building real-time analytics or leaderboards.
Pro Tip: In your next project, whenever you find yourself storing a serialized JSON blob in a string key, ask: "Could this be a hash?" The answer is often yes — and your code will thank you.
Practice recap
Open redis-cli and create a hash named book:1984 with fields title, author, year, and ratings. Use HSET to set all four fields. Then practice using HGET, HMGET, and HGETALL. Finally, update only the ratings field and verify with HGET. This mini-exercise solidifies the core pattern.
Common mistakes
- Using
HMSETinstead ofHSET—HMSETis deprecated and has no advantage overHSETwith multiple field-value pairs. - Assuming
HGETALLis cheap for large hashes — it can block Redis if the hash has thousands of fields; preferHSCANfor iteration. - Forgetting that
HGETreturns(nil)for missing fields, not an error — handleNonein Python ornullin JavaScript accordingly. - Creating a hash with a field name that contains spaces or special characters — they work, but are harder to debug and prone to scripting bugs.
Variations
- Using
HSETNXto set a field only if it does not already exist — useful for idempotent creation. - Using
HSTRLENto get the length of a field's value — helpful for validation. - Using
HKEYSandHVALSto retrieve only field names or only values — lighter thanHGETALL.
Real-world use cases
- Store user profile data (name, email, preferences) in a single hash per user — update name without touching email.
- Track game session state (score, level, health) in Redis — increment score atomically while reading health separately.
- Cache configuration objects (e.g., feature flags with a TTL) — individual fields allow partial updates without overwriting unrelated flags.
Key takeaways
- Redis Hashes store field-value pairs under a single key, enabling cheap partial updates and reads.
- Use
HSETfor setting fields (single or multiple) andHGET/HMGETfor retrieving them. HGETALLis convenient but dangerous for large hashes — preferHMGETorHSCAN.- Always verify the data type of a key before applying hash commands to avoid
WRONGTYPEerrors. - Hashes are ideal for structured objects with a fixed or moderate number of fields.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.