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 is 0, the client can assume that the iteration is complete. In addition to the cursor, there are two other constructs that are common across the Scan commands family—Match and Count.

  • The Match option: A Match option is nothing but a glob-style pattern. For example, using the Scan operation with a user1* pattern will only iterate keys with a name that starts with user1.

  • The Count option: The Count option is used to limit the number of elements returned on each iteration. Please note that Scan 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 1200+ tech skills courses.