In Golang applications that utilize Redis as a key-value store, it might be necessary to delete keys based on a certain prefix. This can be used for data cleanup processes or when related keys need to be removed at once.
The following example shows how to use the Scan
function with a specified prefix and then remove the matching keys. Please install the go-redis/redis
package before running this code.
package main import ( "github.com/go-redis/redis/v8" "context" "fmt" ) func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) ctx := context.Background() var cursor uint64 var n int for { var keys []string var err error keys, cursor, err = rdb.Scan(ctx, cursor, "myprefix*", 10).Result() if err != nil { panic(err) } for _, key := range keys { fmt.Println("deleting key: ", key) rdb.Del(ctx, key) } if cursor == 0 { break } } fmt.Printf("Deleted %d keys\n", n) }
This code connects to a local Redis instance, then it scans keys that match the prefix myprefix
. Matching keys are then deleted using Del
function.
Scan
and Del
functions.KEYS
command followed by DEL
in production environments. KEYS
can block the server when used against large databases, prefer SCAN
instead.Q: Can I delete keys with multiple different prefixes at once?
A: No, you need to run separate Scan
and Del
operations for each prefix.
Q: What happens if there are no keys matching the prefix?
A: The Scan
function will simply return an empty list, and no keys will be deleted.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.