Skip to content

Get all keys

Redis allows iterating over all keys using the SCAN command:

var cursor uint64
for {
    var keys []string
    var err error
    keys, cursor, err = rdb.Scan(ctx, cursor, "key*", 0).Result()
    if err != nil {
        panic(err)
    }

    for _, key := range keys {
        fmt.Println("key", key)
    }

    if cursor == 0 { // no more keys
        break
    }
}

go-redis allows to simplify the code above to:

iter := rdb.Scan(ctx, 0, "key*", 0).Iterator()
for iter.Next(ctx) {
    fmt.Println(iter.Val())
}
if err := iter.Err(); err != nil {
    panic(err)
}

With Redis Cluster and Redis Ring you need to scan each cluster node separately:

err := rdb.ForEachMaster(ctx, func(ctx context.Context, rd *redis.Client) error {
    iter := rdb.Scan(ctx, 0, "key*", 0).Iterator()

    ...

    return iter.Err()
})
if err != nil {
    panic(err)
}