Redis: Scan

Created on 17 Aug 2015  路  2Comments  路  Source: go-redis/redis

Here is a simple example:

package main

import (
    "fmt"
    "gopkg.in/redis.v3"
)

func Connect() *redis.Client {
    client := redis.NewClient(&redis.Options{
        Addr:     "127.0.0.1:6379",
    })

    return client
}

func main() {
    client := Connect()

    // Generate objects
    cursor, _, _ := client.Scan(0, "tracking_insert_click_*", 0).Result()

    if cursor > 0 {
        _, keys, _ := client.Scan(0, "tracking_insert_click_*", cursor).Result()
        fmt.Println(keys)

    }

}

Is this really the right way of using scan?

I tried initially the code from : https://github.com/go-redis/redis/blob/master/commands_test.go#L552

But I had no results.

Please clarify.

Most helpful comment

How about:

package main

import (
    "fmt"
    "os"

    "gopkg.in/redis.v3"
)

func Connect() *redis.Client {
    client := redis.NewClient(&redis.Options{
        Addr: "127.0.0.1:6379",
    })

    return client
}

func main() {
    client := Connect()

    // Seed some keys
    for i := 0; i < 240; i++ {
        client.Set(fmt.Sprintf("k%04d", i), "value", 0)
    }

    // Scan all keys
    var cursor int64
    var err error

    for {
        var keys []string
        if cursor, keys, err = client.Scan(cursor, "", 50).Result(); err != nil {
            fmt.Println("ERROR: %s", err)
            os.Exit(2)
        }

        if len(keys) > 0 {
            fmt.Printf("found %d keys\n", len(keys))
        }

        if cursor == 0 {
            break
        }
    }
}

/*
$ go run main.go
found 50 keys
found 50 keys
found 51 keys
found 51 keys
found 38 keys
*/

All 2 comments

How about:

package main

import (
    "fmt"
    "os"

    "gopkg.in/redis.v3"
)

func Connect() *redis.Client {
    client := redis.NewClient(&redis.Options{
        Addr: "127.0.0.1:6379",
    })

    return client
}

func main() {
    client := Connect()

    // Seed some keys
    for i := 0; i < 240; i++ {
        client.Set(fmt.Sprintf("k%04d", i), "value", 0)
    }

    // Scan all keys
    var cursor int64
    var err error

    for {
        var keys []string
        if cursor, keys, err = client.Scan(cursor, "", 50).Result(); err != nil {
            fmt.Println("ERROR: %s", err)
            os.Exit(2)
        }

        if len(keys) > 0 {
            fmt.Printf("found %d keys\n", len(keys))
        }

        if cursor == 0 {
            break
        }
    }
}

/*
$ go run main.go
found 50 keys
found 50 keys
found 51 keys
found 51 keys
found 38 keys
*/

Thanks, the for loop was the missing piece for me!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

krak3n picture krak3n  路  4Comments

youcandoit95 picture youcandoit95  路  3Comments

aahoughton picture aahoughton  路  5Comments

chenweiyj picture chenweiyj  路  3Comments

mikhailsizov picture mikhailsizov  路  5Comments