redis Redis Keys Scanning the Redis Keyspace


Redis provides the SCAN command to iterate over the keys in the database matching a particular pattern. Redis supports glob style pattern matching in the SCAN command.

The SCAN command provides a cursor-based iterator over the Redis keyspace. The iterative call sequence to SCAN starts with the user making a call with the cursor argument set to 0. The result of that call is a batch of items and an updated cursor which is supplied to the next call to SCAN. This iteration continues until Redis returns a 0 cursor.

The following Python function demonstrates the basic usage of SCAN:

def scan_keys(r, pattern):
    "Returns a list of all the keys matching a given pattern"

    result = []
    cur, keys  = r.scan(cursor=0, match=pattern, count=2)
    while cur != 0:
        cur, keys = r.scan(cursor=cur, match=pattern, count=2)
    return result

The SCAN command is the recommended way to search for keys in the database, and is recommended over the KEYS * command.