Redis Data Structures Deep Dive: Beyond Basic Key-Value
Explore Redis's powerful data structures: lists, sets, sorted sets, and hashes. Learn when and how to use each structure effectively.
Redis Data Structures Deep Dive
While Redis is often thought of as a simple key-value store, it’s actually a powerful data structure server. Understanding these structures is crucial for building efficient applications.
Redis Data Types Overview
Redis supports five main data types:
- Strings - Simple key-value pairs
- Lists - Ordered collections of strings
- Sets - Unordered collections of unique strings
- Sorted Sets - Sets with scores for ordering
- Hashes - Field-value pairs within a key
Lists: Ordered Collections
Lists in Redis are implemented as linked lists, making operations at the head and tail very fast.
Common List Operations
# Add elements to the left (head)
LPUSH mylist "item1" "item2"
# Add elements to the right (tail)
RPUSH mylist "item3" "item4"
# Get list length
LLEN mylist
# Get elements by index
LINDEX mylist 0
# Get range of elements
LRANGE mylist 0 -1Use Cases for Lists
- Message Queues: Use LPUSH/RPOP for FIFO queues
- Recent Activity: Store recent user actions
- Leaderboards: Maintain ordered lists of items
Sets: Unique Collections
Sets store unique strings and provide fast membership testing.
Set Operations
# Add members
SADD myset "member1" "member2" "member3"
# Check membership
SISMEMBER myset "member1"
# Get all members
SMEMBERS myset
# Set operations
SUNION set1 set2    # Union
SINTER set1 set2     # Intersection
SDIFF set1 set2      # DifferenceUse Cases for Sets
- Tagging: Store tags for articles or products
- Friend Lists: Social network connections
- Unique Visitors: Track unique IP addresses
Sorted Sets: Ranked Collections
Sorted sets combine sets with scores, enabling efficient range queries and ranking.
Sorted Set Operations
# Add members with scores
ZADD leaderboard 100 "player1" 200 "player2"
# Get rank of member
ZRANK leaderboard "player1"
# Get range by score
ZRANGEBYSCORE leaderboard 100 200
# Get top N members
ZREVRANGE leaderboard 0 9Use Cases for Sorted Sets
- Leaderboards: Game scores, user rankings
- Time Series: Timestamped data points
- Priority Queues: Tasks with different priorities
Hashes: Field-Value Maps
Hashes store field-value pairs within a single key, perfect for object storage.
Hash Operations
# Set field values
HSET user:1001 name "John" email "[email protected]"
# Get field value
HGET user:1001 name
# Get all fields and values
HGETALL user:1001
# Increment numeric field
HINCRBY user:1001 score 10Use Cases for Hashes
- User Profiles: Store user information
- Session Data: Session attributes
- Configuration: Application settings
Performance Considerations
Memory Usage
- Strings: Most memory-efficient for simple values
- Lists: Good for small to medium collections
- Sets: Memory overhead for uniqueness
- Sorted Sets: Highest memory usage due to score storage
- Hashes: Efficient for structured data
Operation Complexity
Understanding Big O complexity helps choose the right structure:
- O(1): HGET, SET, SADD
- O(log N): ZADD, ZRANK
- O(N): LRANGE, SMEMBERS
- O(N+M): Set operations (SUNION, SINTER)
Best Practices
Choose the Right Structure
- Simple values: Use Strings
- Ordered data: Use Lists or Sorted Sets
- Unique items: Use Sets
- Ranked data: Use Sorted Sets
- Object data: Use Hashes
Memory Optimization
# Use appropriate data types
# Instead of storing JSON strings
SET user:1001 '{"name":"John","email":"[email protected]"}'
# Use hashes for structured data
HSET user:1001 name "John" email "[email protected]"Expiration Strategies
# Set expiration on keys
EXPIRE mykey 3600
# Set expiration on creation
SETEX mykey 3600 "value"Real-World Example: Social Media Feed
Let’s build a simple social media feed using Redis data structures:
# User posts (List)
LPUSH user:1001:posts "Post about Redis"
LPUSH user:1001:posts "Another post"
# User followers (Set)
SADD user:1001:followers "user:1002" "user:1003"
# Timeline generation
# Get followers
SMEMBERS user:1001:followers
# For each follower, get recent posts
LRANGE user:1001:posts 0 9Next Steps
Now that you understand Redis data structures, you’re ready to:
- Design efficient data models for your applications
- Choose optimal structures for different use cases
- Implement complex features like leaderboards and feeds
- Optimize performance through proper structure selection
In our next post, we’ll explore Redis persistence mechanisms and how to ensure data durability.
This post is part of our Redis for Coders series. Check out the complete course for hands-on Redis training.