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
Scancommands 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 theScancommands family—MatchandCount.The
Matchoption: AMatchoption is nothing but a glob-style pattern. For example, using theScanoperation with auser1*pattern will only iterate keys with a name that starts withuser1. ...