Redis supports multiple data structures, each with its specific use cases and underlying implementations:
1. String
Underlying Implementation: Uses SDS (Simple Dynamic String), similar to C strings but with length information and space pre-allocation.
Use Cases:
- Caching user information, configuration data
- Counters (INCR, DECR commands)
- Distributed locks
- Session storage
Common Commands: SET, GET, INCR, DECR, MGET, MSET, SETEX, etc.
2. Hash
Underlying Implementation: Uses ziplist (compressed list) when elements are few, and hashtable when elements are many.
Use Cases:
- Storing objects (e.g., user information)
- Shopping carts
- Article like statistics
Common Commands: HSET, HGET, HMGET, HGETALL, HINCRBY, HDEL, etc.
3. List
Underlying Implementation: Uses ziplist when elements are few, and linkedlist (doubly linked list) or quicklist when elements are many.
Use Cases:
- Message queues
- Recent lists (e.g., recent articles)
- Timelines
- Stack and queue operations
Common Commands: LPUSH, RPUSH, LPOP, RPOP, LRANGE, LLEN, LTRIM, etc.
4. Set
Underlying Implementation: Uses intset (integer set) or hashtable.
Use Cases:
- Tag systems
- Common followers/friends
- Lottery systems
- Deduplication
Common Commands: SADD, SREM, SMEMBERS, SISMEMBER, SINTER, SUNION, etc.
5. ZSet (Sorted Set)
Underlying Implementation: Uses a combination of skiplist and hashtable. Hashtable is for fast lookups, and skiplist is for sorting.
Use Cases:
- Leaderboards
- Delayed queues
- Priority queues
- Range queries
Common Commands: ZADD, ZREM, ZRANGE, ZREVRANGE, ZRANK, ZSCORE, etc.
6. Bitmap
Underlying Implementation: Based on String type, each bit represents a state.
Use Cases:
- User check-in statistics
- Online user statistics
- Bloom filters
Common Commands: SETBIT, GETBIT, BITCOUNT, BITOP, etc.
7. HyperLogLog
Underlying Implementation: Uses probabilistic algorithms, occupying 12KB of memory.
Use Cases:
- Website unique visitor statistics (UV)
- Large-scale data deduplication statistics
Common Commands: PFADD, PFCOUNT, PFMERGE, etc.
8. Geo (Geospatial)
Underlying Implementation: Based on ZSet, using the Geohash algorithm.
Use Cases:
- Nearby people
- Distance calculation
- Location services
Common Commands: GEOADD, GEODIST, GEOPOS, GEORADIUS, etc.
Each data structure has specific conversion thresholds. For example, Hash and List will convert from ziplist to more complex data structures when the number of elements and size exceed certain thresholds, to balance memory usage and performance.