The Scan Family of Commands
Learn how to iterate data using the Scan family of commands.
The Scan
commands
In Redis, Scan
is a family or group of similar commands used to traverse keys or collections (such as set, sorted set, or hash). For instance, it’s possible to use the KEYS
commands to search for keys using string matching patterns, however, it’s risky to use this in production or with a large database that has millions of keys (or more). This can end up blocking the Redis server, impacting performance. Similarly, invoking SMEMBERS
on a set with lot of elements can block for long time.
This is where Scan
and its related family of operations come in, providing an efficient way to achieve this.
The following commands belong to the Scan
family:
Scan
: Iterates over the set of all the possible keys.SScan
: Iterates over elements in a set.HScan
: Iterates over elements in a hash.ZScan
: Iterates over elements in a sorted set.
The Scan
commands: Key concepts
Let's explore some of the key concepts of the Scan
command family.
Cursor: The
Scan
commands use cursors, in other words, they use cursor-based iterators. The cursor holds the state required to manage the iteration. At every invocation, Redis returns a new cursor and the client application simply needs to use it as an argument in the next invocation. As soon as the cursor returned is0
, the client can assume that the iteration is complete. In addition to the cursor, there are two other constructs that are common across theScan
commands family—Match
andCount
.The
Match
option: AMatch
option is nothing but a glob-style pattern. For example, using theScan
operation with auser1*
pattern will only iterate keys with a name that starts withuser1
.The
Count
option: TheCount
option is used to limit the number of elements returned on each iteration. Please note thatScan
doesn’t provide strong guarantees on this. It means that the actual number of elements returned may be slightly more or less than the specified count.
Let’s explore these commands individually.
The Scan
commands
As mentioned before, Scan
commands are cursor based and the cursor is returned to the client at the end of each iteration.
Click the “Run” button in the code widget below to execute the Scan
operations:
Get hands-on with 1400+ tech skills courses.