Redis Hash Examples#

This notebook demonstrates how to work with Redis Hashes using redis-py. Hashes are maps between string fields and string values, making them perfect for representing objects (e.g., a user profile).

[1]:
import redis

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

Set and get a single field#

[2]:
r.hset('user:1', 'name', 'Alice')
print(r.hget('user:1', 'name'))  # Alice
Alice

Set multiple fields at once#

[3]:
r.hset('user:1', mapping={
    'name': 'Alice',
    'age': '30',
    'email': 'alice@example.com'
})
print(r.hgetall('user:1'))
{'name': 'Alice', 'age': '30', 'email': 'alice@example.com'}

Check if a field exists#

[4]:
print(r.hexists('user:1', 'email'))   # True
print(r.hexists('user:1', 'phone'))   # False
True
False

Get all fields and values#

Note that Redis does not guarantee any particular order for hash fields, so don’t rely on the order of the hkeys() and hvals() results.

[5]:
print(r.hkeys('user:1'))
print(r.hvals('user:1'))
print(r.hlen('user:1'))     # 3
['name', 'age', 'email']
['Alice', '30', 'alice@example.com']
3

Increment a numeric field#

[6]:
r.hset('user:1', 'age', '30')
r.hincrby('user:1', 'age', 1)
print(r.hget('user:1', 'age'))  # 31
31

Delete a field#

[7]:
r.hdel('user:1', 'email')
print(r.hgetall('user:1'))  # email is gone
{'name': 'Alice', 'age': '31'}

Cleanup#

[8]:
r.delete('user:1')
[8]:
1