0
0
Redisquery~5 mins

SCAN for safe key iteration in Redis

Choose your learning style9 modes available
Introduction
SCAN helps you look through all keys in Redis without freezing the database. It is safer than getting all keys at once.
When you want to find keys matching a pattern without stopping Redis.
When your database has many keys and you want to avoid slow commands.
When you want to process keys in small parts instead of all at once.
When you want to build a tool that checks or cleans keys safely.
When you want to avoid blocking other users while searching keys.
Syntax
Redis
SCAN cursor [MATCH pattern] [COUNT count]
The cursor starts at 0 and moves forward with each call until it returns 0 again.
MATCH lets you filter keys by pattern, COUNT suggests how many keys to return per call.
Examples
Start scanning all keys from the beginning.
Redis
SCAN 0
Scan keys that start with 'user:'.
Redis
SCAN 0 MATCH user:*
Try to return about 100 keys in this scan call.
Redis
SCAN 0 COUNT 100
Sample Program
This command scans keys starting with 'session:' in small groups of 10 to avoid blocking.
Redis
SCAN 0 MATCH session:* COUNT 10
OutputSuccess
Important Notes
SCAN does not guarantee to return all keys in one call; you must repeat calls with the new cursor.
The cursor returned is a string number; when it returns '0', the scan is complete.
COUNT is a hint, not a guarantee; Redis may return more or fewer keys.
Summary
SCAN lets you safely look through keys without blocking Redis.
Use MATCH to filter keys by pattern and COUNT to control batch size.
Repeat SCAN calls with the returned cursor until it returns 0.