Concept Flow - KEYS pattern matching (avoid in production)
Start
Input pattern
Scan all keys in Redis
Match keys against pattern
Return matched keys
End
The KEYS command scans all keys in Redis and returns those matching the given pattern.
KEYS user:*
# Returns all keys starting with 'user:'| Step | Action | Current Key | Pattern | Match Result | Output Keys |
|---|---|---|---|---|---|
| 1 | Start scanning keys | user:* | [] | ||
| 2 | Check key | user:1 | user:* | Match | ["user:1"] |
| 3 | Check key | user:2 | user:* | Match | ["user:1", "user:2"] |
| 4 | Check key | session:1 | user:* | No Match | ["user:1", "user:2"] |
| 5 | Check key | user:profile | user:* | Match | ["user:1", "user:2", "user:profile"] |
| 6 | Check key | config | user:* | No Match | ["user:1", "user:2", "user:profile"] |
| 7 | Finish scanning | user:* | ["user:1", "user:2", "user:profile"] |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | After 5 | Final |
|---|---|---|---|---|---|---|---|
| Output Keys | [] | ["user:1"] | ["user:1", "user:2"] | ["user:1", "user:2"] | ["user:1", "user:2", "user:profile"] | ["user:1", "user:2", "user:profile"] | ["user:1", "user:2", "user:profile"] |
KEYS pattern matching in Redis: - Syntax: KEYS <pattern> - Scans all keys to find matches - Patterns use * as wildcard - Not recommended in production due to blocking and performance - Use SCAN for safer iteration
KEYS * do?KEYS commandKEYS command searches for keys matching a given pattern.** matches all keys in the current database.KEYS * lists all keys [OK]user:* without quotes to match keys starting with 'user:'.user:1, user:2, admin:1, what is the output of KEYS user:*?user:*user:1 and user:2.admin:1 does not start with 'user:', so it is excluded.KEYS user?*?? matches exactly one character in Redis patterns.user?*? matches exactly one character [OK]KEYS is discouraged in productionKEYS blocks Redis and can cause performance issues on large datasets.SCAN with MATCH for safe iterationSCAN iterates keys incrementally without blocking, using MATCH *session* to filter keys containing 'session'.SCAN 0 MATCH *session* iteratively -> Option BSCAN is safe for production key matching [OK]Pass the test and this pattern moves unknown