Incremental keyspace inspection
Traverse a large keyspace in bounded batches instead of requesting every key at once.
Redis · Command
SCAN incrementally iterates over key names in the currently selected Redis database. Continue with each returned cursor until it becomes 0, optionally filtering by pattern, count hint, or type.
SCAN incrementally iterates key names in the currently selected database. Each call receives a cursor and returns a new cursor plus a batch of keys; continue until the cursor returns to 0, optionally constraining results with MATCH, COUNT, or TYPE.
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]| Name | Type | Description |
|---|---|---|
cursor | integer | Cursor position; use 0 to begin and the returned cursor for the next call. |
MATCH pattern | string | Optional glob-style pattern used to filter returned key names. |
COUNT count | integer | Optional work-count hint for each call; it is not an exact result count. |
TYPE type | string | Optional Redis data type used to restrict returned keys. |
A two-element array containing the next cursor and an array of key names.
const Redis = require('ioredis');
(async () => {
const redis = new Redis();
await redis.mset('user:1','Ada','user:2','Linus','session:1','active');
let cursor = '0';
do {
const result = await redis.scan(cursor, 'MATCH', 'user:*', 'COUNT', 100);
cursor = result[0];
for (const key of result[1]) console.log(key);
} while (cursor !== '0');
await redis.quit();
})();Starts at cursor 0, repeatedly supplies the returned cursor, filters keys with MATCH, and stops when Redis returns cursor 0.
Traverse a large keyspace in bounded batches instead of requesting every key at once.
Find keys belonging to a namespace without using a blocking whole-keyspace command.
Process only keys whose Redis data type is appropriate for an operation.
SCAN iterates keys in the selected database without requiring a key argument. Start with cursor 0, pass each returned cursor into the next call, and finish when it becomes 0.
Follow-up: How would you avoid scanning keys of the wrong type? Use the optional TYPE argument, while remembering that matching and iteration behavior still apply.
MATCH accepts a glob-style pattern and limits which returned keys are reported. COUNT suggests how much work Redis should do per call, but it does not guarantee the batch length.
Follow-up: Why might MATCH return an empty batch? Matching is performed after Redis retrieves elements, so a batch may contain no matching keys.
Each call has constant operation complexity, while completing an iteration is O(N), where N is the number of elements in the database. SCAN is therefore suitable for incremental traversal rather than one large blocking result.
Follow-up: What property must production code handle? Results are not ordered and may repeat, so consumers should tolerate duplicates and avoid relying on order.
SSCANHSCANZSCANKEYS