How to Find All Keys in Redis Quickly and Safely
To find all keys in Redis, use the
KEYS * command to list all keys matching a pattern, or use SCAN 0 for a safer, incremental approach. KEYS * returns all keys at once but can block Redis if there are many keys, while SCAN iterates keys without blocking.Syntax
The main commands to find keys in Redis are:
KEYS pattern: Returns all keys matching the given pattern.SCAN cursor [MATCH pattern] [COUNT count]: Iterates keys incrementally without blocking Redis.
Use * as the pattern to match all keys.
redis
KEYS *
SCAN 0 [MATCH pattern] [COUNT count]Example
This example shows how to list all keys using both KEYS and SCAN commands.
redis
127.0.0.1:6379> SET user:1 "Alice" OK 127.0.0.1:6379> SET user:2 "Bob" OK 127.0.0.1:6379> KEYS * 1) "user:1" 2) "user:2" 127.0.0.1:6379> SCAN 0 1) "0" 2) 1) "user:1" 2) "user:2"
Output
1) "user:1"
2) "user:2"
1) "0"
2) 1) "user:1"
2) "user:2"
Common Pitfalls
Using KEYS * on a large database can block Redis and slow down your server. It is not recommended in production environments.
SCAN is safer because it returns keys in small batches and does not block Redis, but you must loop until the cursor returns to 0 to get all keys.
redis
Wrong (may block Redis): KEYS * Right (safe incremental scan): 127.0.0.1:6379> SCAN 0 # Repeat SCAN with returned cursor until cursor is 0
Quick Reference
| Command | Description |
|---|---|
| KEYS * | Returns all keys matching pattern (blocks Redis if many keys) |
| SCAN 0 | Incrementally scans keys without blocking, returns cursor and keys |
| SCAN cursor MATCH pattern | Scan keys matching pattern incrementally |
| SCAN cursor COUNT count | Hint to Redis about how many keys to return per call |
Key Takeaways
Use
KEYS * only for small datasets or debugging because it blocks Redis.Use
SCAN to safely iterate all keys without blocking the server.Repeat
SCAN calls until the cursor returned is 0 to get all keys.You can filter keys by pattern using the
MATCH option with SCAN.Avoid running
KEYS * on production Redis instances with many keys.