Redis Hashes (Part 1)

A hash is a key-value collection, ideal for storing objects. This lesson covers basic hash operations.

What is a Hash?

A hash is similar to:

A single Redis hash key can store multiple field-value pairs:

user:1
├─ name  → "Alice"
├─ age   → "25"
├─ city  → "Beijing"
└─ email → "alice@example.com"
💡 Advantage: Hashes allow you to modify individual fields without reading the entire object. They are also more memory-efficient than storing JSON strings.

HSET and HGET: Set and Get Fields

HSET: Set a Single Field

REDIS
# Set a single field
HSET user:1 name "Alice"
(integer) 1  # Returns the number of newly added fields

# Set multiple fields
HSET user:1 age 25 city "Beijing"
(integer) 2  # Added 2 new fields

# Update an existing field
HSET user:1 name "Bob"
(integer) 0  # Field already exists, returns 0

HGET: Get a Single Field

REDIS
HGET user:1 name
"Alice"

HGET user:1 age
"25"

# Field does not exist
HGET user:1 notexist
(nil)

HSETNX: Set Only if Field Does Not Exist

REDIS
# Set only if the field does not exist
HSETNX user:1 name "Charlie"
(integer) 0  # Field already exists, failed

HSETNX user:1 phone "13800138000"
(integer) 1  # Field does not exist, set successfully

HMSET and HMGET: Batch Operations

HMSET: Batch Set Fields

REDIS
HMSET user:2 name "Bob" age 30 city "Shanghai" email "bob@example.com"
OK
⚠️ Note: After Redis 4.0.0, HMSET is deprecated. Use HSET for setting multiple fields instead.

HMGET: Batch Get Fields

REDIS
HMGET user:2 name age city
1) "Bob"
2) "30"
3) "Shanghai"

# Including non-existent fields
HMGET user:2 name email phone
1) "Bob"
2) "bob@example.com"
3) (nil)  # phone does not exist

HGETALL: Get All Fields and Values

REDIS
HGETALL user:2
1) "name"
2) "Bob"
3) "age"
4) "30"
5) "city"
6) "Shanghai"
7) "email"
8) "bob@example.com"
⚠️ Note: HGETALL returns an alternating array of field names and values. If the hash is large, this uses significant memory and network bandwidth — use with caution!

HKEYS and HVALS: Get All Field Names or Values

HKEYS: Get All Field Names

REDIS
HKEYS user:2
1) "name"
2) "age"
3) "city"
4) "email"

HVALS: Get All Values

REDIS
HVALS user:2
1) "Bob"
2) "30"
3) "Shanghai"
4) "bob@example.com"

HEXISTS: Check if Field Exists

REDIS
HEXISTS user:2 name
(integer) 1  # Exists

HEXISTS user:2 phone
(integer) 0  # Does not exist

HDEL: Delete Fields

REDIS
# Delete a single field
HDEL user:2 email
(integer) 1  # Deleted 1 field

# Delete multiple fields
HDEL user:2 age city
(integer) 2  # Deleted 2 fields

# Delete a non-existent field
HDEL user:2 notexist
(integer) 0

HLEN: Get Number of Fields

REDIS
HSET user:3 name "Charlie" age 28
HLEN user:3
(integer) 2  # Has 2 fields

# Key does not exist
HLEN notexist
(integer) 0

HSTRLEN: Get Field Value Length

REDIS
HSET user:1 name "Alice" bio "Software Engineer"
HSTRLEN user:1 name
(integer) 5  # "Alice" has length 5

HSTRLEN user:1 bio
(integer) 17  # "Software Engineer" has length 17

Hash Use Cases

Use Case 1: Storing User Info

REDIS
# Store basic user info
HSET user:1001 name "Alice" age 25 email "alice@example.com" role "admin"

# Get user name
HGET user:1001 name

# Update user age
HSET user:1001 age 26

# Get all user info
HGETALL user:1001

Use Case 2: Shopping Cart

REDIS
# User 1's shopping cart
HSET cart:user:1 product:101 2    # Product 101, quantity 2
HSET cart:user:1 product:102 1    # Product 102, quantity 1
HSET cart:user:1 product:103 5    # Product 103, quantity 5

# View all items in cart
HGETALL cart:user:1

# Update item quantity
HSET cart:user:1 product:101 3

# Remove an item
HDEL cart:user:1 product:102

# Check how many items in cart
HLEN cart:user:1

Use Case 3: Article Metadata

REDIS
# Store article info
HSET article:123 title "Redis Tutorial" author "Alice" views 1000 likes 50

# Increment view count (requires HINCRBY)
HINCRBY article:123 views 1

# Increment like count
HINCRBY article:123 likes 1

# Get article title and author
HMGET article:123 title author

Use Case 4: Product Cache

REDIS
# Cache product details
HSET product:2001 name "iPhone 15" price 5999 stock 100 category "phone"

# Get product price
HGET product:2001 price

# Update stock
HSET product:2001 stock 95

# Check if product exists
HEXISTS product:2001 name

Hash vs String for Storing Objects

Method 1: String with JSON

REDIS
SET user:1 '{"name":"Alice","age":25,"email":"alice@example.com"}'

# Get the whole object
GET user:1

# Modify age: need to read, parse, modify, serialize, write back
# Multiple steps, inefficient

Method 2: Hash

REDIS
HSET user:1 name "Alice" age 25 email "alice@example.com"

# Get a single field
HGET user:1 name

# Modify age: one-step operation
HSET user:1 age 26

# Get multiple fields
HMGET user:1 name age

Comparison Summary

Aspect String (JSON) Hash
Modify single field Need to read the whole object Direct modification
Memory usage Larger (JSON format overhead) Smaller (compact storage)
Query single field Need to parse JSON Direct access
Complex nested objects ✅ Supported ❌ Not supported
Partial update ❌ Difficult ✅ Simple
💡 Selection guide:

  • Simple objects (flat structure): use Hash
  • Complex objects (nested structure): use String with JSON
  • Frequently modifying individual fields: use Hash

Hash Encoding Optimization

Redis automatically selects encoding based on hash size:

Encoding Condition Description
ziplist Fields <= 512, value length <= 64 bytes Compressed list, saves memory
hashtable Fields > 512 or value length > 64 bytes Hash table, better performance

Checking Encoding Type

REDIS
HSET small:hash field1 "value1" field2 "value2"
OBJECT ENCODING small:hash
"ziplist"

# After adding many fields
HSET large:hash field1 "value1" field2 "value2" ... field600 "value600"
OBJECT ENCODING large:hash
"hashtable"
ℹ️ Note: Encoding is automatically selected by Redis. You can adjust thresholds through config parameters.

❓ FAQ

Q How many fields can a hash store?
A Theoretically unlimited (2^32 - 1), but practically limited by memory. It's recommended to keep individual hashes under a few thousand fields.
Q Does HGETALL affect performance?
A Yes. If the hash is large, HGETALL returns a lot of data, consuming memory and bandwidth. Use HSCAN for iterative retrieval.
Q Can hash field values be numeric?
A Yes. All values in Redis are strings, but numeric strings support arithmetic operations (HINCRBY).
Q How do I delete an entire hash key?
A Use DEL to delete the key, not HDEL to delete fields: DEL user:1.
Q Does hash support nesting?
A No. Hash values can only be strings. For nesting, use String with JSON.

📖 Summary

📝 Exercises

  1. User info: Use a hash to store user info (name, age, email, city), then retrieve all info
  2. Shopping cart: Implement a shopping cart with a hash — add 3 products, modify 1 quantity, delete 1 product
  3. Field operations: Use HEXISTS to check field existence, HLEN to count fields
  4. Comparison practice: Store the same object with both String JSON and Hash, compare the steps to modify a single field

Next Lesson

In the next lesson, we will learn Redis Hashes (Part 2), covering advanced hash operations and numeric calculations.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏