This is article 40 in the Big Data series. This article systematically organizes the core commands and production scenario selection guide for Redis five data types.
Complete illustrated version: CSDN Original | Juejin
Common Key Operations
Before operating on specific data types, master these generic commands unrelated to keys:
| Command | Time Complexity | Description |
|---|---|---|
EXISTS key | O(1) | Check if key exists |
DEL key1 [key2…] | O(m) | Delete one or more keys, m is number of keys |
EXPIRE key seconds | O(1) | Set expiration time (seconds) |
TTL key | O(1) | Query remaining TTL, -1 means never expire, -2 means does not exist |
TYPE key | O(1) | Return data type of key |
KEYS pattern | O(N) | Pattern matching search (disabled in production, use SCAN instead) |
SCAN cursor [MATCH pattern] [COUNT count] | O(N) | Cursor iteration, does not block service |
RENAME key newkey | O(1) | Atomic rename |
String
String is the most basic type, supporting up to 512MB storage with binary safety.
Common Commands
# Set value (with expiration and conditions)
SET key "value" EX 60 # Expires after 60 seconds
SET key "value" NX # Only set if key does not exist (common for distributed locks)
# Get value
GET key
MGET key1 key2 key3 # Batch get to reduce network round trips
# Atomic increment/decrement
INCR counter # +1
INCRBY counter 10 # +N
INCRBYFLOAT price 0.5 # Supports floating point
# Bitmap operations
SETBIT sign:uid:20240801 0 1 # Check-in
GETBIT sign:uid:20240801 0
BITCOUNT sign:uid:20240801 # Count check-in days
# Other operations
APPEND key " suffix"
STRLEN key
GETSET key newvalue # Atomic read-then-write
Typical Scenarios
- Caching:
SET user:1001 <json> EX 3600 - Counters: Page PV/UV, inventory deduction
- Distributed Locks:
SET lock:resource uuid NX EX 30
List
Doubly linked list structure, head/tail operations are O(1), random access is O(N).
Common Commands
LPUSH list 1 2 3 9 4 5 # Batch push from left
RPUSH list a b c # Push from right
LRANGE list 0 9 # View elements at index 0-9
LPOP list # Pop from left
RPOP list
BLPOP queue 5 # Blocking pop, wait up to 5 seconds (common for message queues)
LLEN list # Get length
LTRIM list 0 99 # Keep first 100 elements, discard rest
LMOVE src dst LEFT RIGHT # Atomically move elements
Typical Scenarios
- Simple Message Queue:
LPUSHfor produce,BRPOPfor blocking consumption - Latest Activity:
LPUSH+LTRIMto maintain fixed-length list - Circular Log: Fixed-length sliding window log
Set
Unordered, unique elements. Internally automatically switches between intset (pure integer small sets) and hashtable.
Common Commands
SADD tag:redis u1 u2 u3 # Add members
SMEMBERS tag:redis # Get all members (use carefully on large sets)
SISMEMBER tag:redis u1 # Check if member exists, O(1)
SCARD tag:redis # Set size
SRANDMEMBER tag:redis 3 # Randomly get 3 (without removing)
SPOP tag:redis # Randomly pop one
# Set operations
SUNION set1 set2 # Union
SINTER set1 set2 # Intersection (common friends)
SDIFF set1 set2 # Difference
SSCAN set1 0 COUNT 100 # Cursor iteration for large sets
Typical Scenarios
- Common Friends:
SINTER user:1:friends user:2:friends - Lottery:
SRANDMEMBERorSPOP - Tag Deduplication: Article tags, user interests
Sorted Set (ZSet)
Each member is associated with a score value, sorted by score. Supports querying by rank and by score range.
Common Commands
ZADD rank 100 item1 20 item2 30 item3 # Add members with scores
ZCARD rank # Total members
ZSCORE rank item3 # Query member's score
ZRANK rank item1 # Query rank (ascending, starting from 0)
ZREVRANK rank item1 # Rank descending
ZRANGE rank 0 9 WITHSCORES # Get by rank ascending
ZREVRANGE rank 0 9 WITHSCORES # Get by rank descending
ZRANGEBYSCORE rank 80 100 # Query by score range
ZINCRBY rank 5 item1 # Atomically increment score (+5)
ZCOUNT rank 80 100 # Count members in score range
ZREM rank item2 # Remove member
ZREMRANGEBYRANK rank 0 9 # Remove members by rank range
Typical Scenarios
- Leaderboard:
ZINCRBYto update scores,ZREVRANGEto get Top N - Hot Search: Real-time update search frequency, sort by frequency
- Delayed Queue:
score = execution timestamp, periodically pollZRANGEBYSCOREfor expired tasks
Hash
Store multiple field-value pairs under a single key, suitable for structured objects.
Common Commands
HSET u:1001 name "wzk" age 27 city "Beijing" # Batch set fields
HGET u:1001 name # Get single field
HMGET u:1001 name age # Get multiple fields
HGETALL u:1001 # Get all fields (use carefully on large objects)
HINCRBY u:1001 age 1 # Atomically increment field
HEXISTS u:1001 phone # Check if field exists
HLEN u:1001 # Number of fields
HDEL u:1001 city # Delete field
HRANDFIELD u:1001 2 # Randomly get 2 fields
Typical Scenarios
- User Information:
HSET user:uid field value, read individual fields as needed, avoid deserializing entire JSON - Shopping Cart:
HSET cart:uid product_id quantity - Object Caching: Field-level updates are more efficient than storing JSON in String
Data Type Selection Cheat Sheet
| Scenario | Recommended Type | Reason |
|---|---|---|
| Simple KV Cache | String | Most versatile, supports atomic operations |
| Object Property Storage | Hash | Field-level read/write, saves serialization overhead |
| Message Queue | List | Ordered, supports blocking consumption |
| Deduplication/Tags | Set | Natural uniqueness, supports set operations |
| Leaderboard/Delayed Queue | Sorted Set | Ordered by score, efficient range queries |