How to Use Redis HSET and HGET in Python
This code demonstrates how to store and retrieve hash data in Redis using Python's redis library with HSET, HGET, HGETALL, and HDEL commands.
pip install redis
Python code
27 linesimport redis
# Connect to Redis (adjust host/port as needed)
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
# Clear any existing data for demonstration
r.delete('user:1')
# HSET - Store a hash
r.hset('user:1', mapping={'name': 'Alice', 'age': 30, 'city': 'New York'})
# HGET - Retrieve a single field
print("Name:", r.hget('user:1', 'name'))
# HGETALL - Retrieve all fields
print("All fields:", r.hgetall('user:1'))
# Update an existing field
r.hset('user:1', 'age', 31)
print("Updated age:", r.hget('user:1', 'age'))
# Delete a field
r.hdel('user:1', 'city')
print("After deletion:", r.hgetall('user:1'))
# Close connection
r.close()
Output
Name: Alice
All fields: {'name': 'Alice', 'age': '30', 'city': 'New York'}
Updated age: 31
After deletion: {'name': 'Alice', 'age': '31'}
How it works
The decode_responses=True parameter ensures that Redis returns strings instead of bytes, making output more readable. hset can store multiple fields via the mapping parameter or a single field when given key-value arguments. hget retrieves a specific field's value, while hgetall returns all fields as a dictionary. The hdel command removes specified fields from the hash. The connection is closed at the end to free resources.
Common mistakes
- Forgetting to set `decode_responses=True` can lead to byte-string outputs that are hard to read.
- Using `hget` on a non-existent field or key returns `None`; ensure the field exists before expecting a value.
- Neglecting to close the Redis connection can cause resource leaks in long-running applications.
Variations
- Use `hmset` (deprecated) or `hset` with a dictionary for setting multiple fields at once.
- Use `hgetall` followed by dictionary methods to process all fields efficiently.
Real-world use cases
- Caching user profiles with fields like name, email, and preferences for fast retrieval.
- Storing session data as hashes with attributes such as user ID and last activity.
- Maintaining product attributes in Redis for e-commerce workspaces to speed up lookups.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader easy
- Cache Data in Redis with Python easy
- Cache Penetration Null Object Mock in Python medium
- Cache Stampede Prevention with SingleFlight in Python medium
- Cache Warming with Python: Preload Hot Keys easy
- Coalescing duplicate in-flight requests: one shared result for concurrent callers hard
Keep learning
Related tutorials and quizzes for this topic.