0
0
RedisHow-ToBeginner · 3 min read

How to Use KEYS Command in Redis: Syntax and Examples

The KEYS command in Redis returns all keys matching a given pattern. Use KEYS <pattern> where the pattern can include wildcards like * to match multiple keys. It is useful for searching keys but should be used carefully on large databases due to performance impact.
📐

Syntax

The KEYS command syntax is simple:

  • KEYS <pattern>: Returns all keys matching the pattern.
  • The pattern supports wildcards like * (matches any number of characters), ? (matches one character), and character ranges like [a-z].
redis
KEYS <pattern>
💻

Example

This example shows how to find all keys starting with user: in Redis.

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> SET session:1 "xyz"
OK
127.0.0.1:6379> KEYS user:*
1) "user:1"
2) "user:2"
Output
1) "user:1" 2) "user:2"
⚠️

Common Pitfalls

Using KEYS on a large Redis database can cause performance issues because it scans all keys. Avoid using it in production environments with many keys.

Instead, consider using SCAN for incremental iteration without blocking Redis.

redis
Wrong way (may block Redis):
KEYS *

Right way (safer for production):
SCAN 0 MATCH * COUNT 100
📊

Quick Reference

CommandDescription
KEYS Returns all keys matching the pattern
* (wildcard)Matches any number of characters
? (wildcard)Matches exactly one character
[abc]Matches any one character inside the brackets
SCAN 0 MATCH COUNT Incrementally iterates keys matching pattern

Key Takeaways

Use KEYS <pattern> to find keys matching a pattern in Redis.
Patterns support wildcards like * and ? for flexible matching.
Avoid KEYS on large databases to prevent performance issues.
Use SCAN command for safer, incremental key searching in production.
Always test key patterns carefully to avoid unexpected results.