user
How to create HASH in Redis with Python?
alphonsio

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.


Step-by-Step Guide

1. Install redis package

pip install redis

2. Connect to Redis

import redis

# Connect to Redis server
r = redis.Redis(host='localhost', port=6379, db=0)

๐Ÿ”ง Create and Use a HASH

3. Set fields in a hash (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'})

4. Get fields from a hash (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()})

5. Other useful hash commands

# 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)

๐Ÿงน Optional: Delete fields or hash

# Delete a specific field
r.hdel('user:1001', 'email')

# Delete entire hash (just delete the key)
r.delete('user:1000')

โœ… Summary

OperationRedis CommandPython Method
Set fieldHSETr.hset()
Get fieldHGETr.hget()
Get all fieldsHGETALLr.hgetall()
Increment fieldHINCRBYr.hincrby()
Delete fieldHDELr.hdel()
Delete hashDELr.delete()