Implementing Search Patterns
1. Using Pattern Matching
| Glob | Match |
* | Any sequence |
? | Single char |
[abc] | Char set |
[^a] | Negation |
\\ | Escape |
2. Implementing Cursor-Based Iteration
Example: SCAN loop in bash
cursor=0
while :; do
resp=$(redis-cli SCAN $cursor MATCH "user:*" COUNT 500)
cursor=$(echo "$resp" | head -1)
echo "$resp" | tail -n +2
[ "$cursor" = "0" ] && break
done
| Property | Behavior |
| Cursor | Opaque; start with 0, stop when 0 returns |
| Guarantees | All keys present for full iteration; may revisit |
3. Scanning Hash Fields
| Command | Notes |
HSCAN key cursor [MATCH p] [COUNT n] [NOVALUES] | NOVALUES reduces transfer 7.4+ |
4. Scanning Set Members
| Command | Description |
SSCAN key cursor [MATCH p] [COUNT n] | Incremental member scan |
5. Scanning Sorted Set Members
| Command | Returns |
ZSCAN key cursor [MATCH p] [COUNT n] | Member/score pairs |
6. Setting Scan Count
| COUNT | Effect |
| Default 10 | Hint, not exact |
| 100-1000 | Faster iteration, more work per call |
7. Using Pattern Filters
Note: MATCH filters AFTER fetching the batch — pattern reduces returned data but not server work.
| Strategy | Effect |
| Use COUNT >> expected matches | Avoids many empty round-trips with selective patterns |
8. Using TYPE Filter with SCAN
| Command | Description |
SCAN 0 TYPE hash MATCH user:* COUNT 1000 | Filter by type server-side 6.0+ |
9. Using NOVALUES Option
| Command | Description |
HSCAN key 0 NOVALUES | Return only field names — saves bandwidth on large hashes |
10. Handling Large Keyspaces
| Pattern | Recommendation |
| Always | SCAN over KEYS |
| Multi-node | Run SCAN on every shard |
| Large hashes | HSCAN with NOVALUES, then HMGET |
ZRANGE leaderboard 0 -1 REV BYSCORE LIMIT 0 20 WITHSCORES
| Method | Use |
| ZRANGE BYSCORE + LIMIT | Stable pagination by value |
| Cursor (last score+id) | Keyset pagination |
12. Avoiding KEYS in Production
Warning: KEYS blocks the server O(N) — disable via rename-command KEYS "" in production.
| Replace | With |
KEYS pattern | SCAN 0 MATCH pattern COUNT 1000 |