redis Redis Keys Scanning the Redis Keyspace

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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)
    result.extend(keys)
    while cur != 0:
        cur, keys = r.scan(cursor=cur, match=pattern, count=2)
        result.extend(keys)
        
    return result

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



Got any redis Question?