Here is the simplest way to create a HASH in Redis with Python:
# Set individual field
r.hset('user:1000', 'name', 'Alice')
r.hset('user:1000', 'age', 30)
or:
# Set multiple fields at once
r.hset('user:1001', mapping={'name': 'Bob', 'age': 25, 'email': 'bob@example.com'})
To create and manipulate a HASH in Redis using Python, you typically use the redis-py
library.
A Redis HASH is a data structure that stores a mapping between fields and values, similar to a Python dictionary.
redis
packagepip install redis
import redis
# Connect to Redis server
r = redis.Redis(host='localhost', port=6379, db=0)
hset
)# Set individual field
r.hset('user:1000', 'name', 'Alice')
r.hset('user:1000', 'age', 30)
# Or set multiple fields at once
r.hset('user:1001', mapping={'name': 'Bob', 'age': 25, 'email': 'bob@example.com'})
hget
, hgetall
)# Get a single field
name = r.hget('user:1000', 'name')
print(name.decode()) # Output: Alice
# Get all fields and values
user_data = r.hgetall('user:1001')
print({k.decode(): v.decode() for k, v in user_data.items()})
# Check if a field exists
exists = r.hexists('user:1001', 'email') # True
# Get all field names
fields = r.hkeys('user:1001')
# Get all field values
values = r.hvals('user:1001')
# Increment numeric field
r.hincrby('user:1000', 'age', 1)
# Delete a specific field
r.hdel('user:1001', 'email')
# Delete entire hash (just delete the key)
r.delete('user:1000')
Operation | Redis Command | Python Method |
---|---|---|
Set field | HSET | r.hset() |
Get field | HGET | r.hget() |
Get all fields | HGETALL | r.hgetall() |
Increment field | HINCRBY | r.hincrby() |
Delete field | HDEL | r.hdel() |
Delete hash | DEL | r.delete() |