Implementing Search Patterns

1. Using Pattern Matching

GlobMatch
*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
PropertyBehavior
CursorOpaque; start with 0, stop when 0 returns
GuaranteesAll keys present for full iteration; may revisit

3. Scanning Hash Fields

CommandNotes
HSCAN key cursor [MATCH p] [COUNT n] [NOVALUES]NOVALUES reduces transfer 7.4+

4. Scanning Set Members

CommandDescription
SSCAN key cursor [MATCH p] [COUNT n]Incremental member scan

5. Scanning Sorted Set Members

CommandReturns
ZSCAN key cursor [MATCH p] [COUNT n]Member/score pairs

6. Setting Scan Count

COUNTEffect
Default 10Hint, not exact
100-1000Faster iteration, more work per call

7. Using Pattern Filters

Note: MATCH filters AFTER fetching the batch — pattern reduces returned data but not server work.
StrategyEffect
Use COUNT >> expected matchesAvoids many empty round-trips with selective patterns

8. Using TYPE Filter with SCAN

CommandDescription
SCAN 0 TYPE hash MATCH user:* COUNT 1000Filter by type server-side 6.0+

9. Using NOVALUES Option

CommandDescription
HSCAN key 0 NOVALUESReturn only field names — saves bandwidth on large hashes

10. Handling Large Keyspaces

PatternRecommendation
AlwaysSCAN over KEYS
Multi-nodeRun SCAN on every shard
Large hashesHSCAN with NOVALUES, then HMGET

11. Implementing Efficient Pagination

Example: Score-based pagination on sorted set

ZRANGE leaderboard 0 -1 REV BYSCORE LIMIT 0 20 WITHSCORES
MethodUse
ZRANGE BYSCORE + LIMITStable 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.
ReplaceWith
KEYS patternSCAN 0 MATCH pattern COUNT 1000