Introducing Dragonfly Cloud! Learn More

Deleting Redis Keys by Pattern in Golang (Detailed Guide w/ Code Examples)

Use Case(s)

Deleting keys by a pattern is commonly used when you need to remove all keys that match a certain pattern. This can be useful for instance when you want to delete session data related to a particular user, or clear entries of a specific type.

Code Examples

To use Golang with Redis, we commonly use the go-redis library. Below are examples showing how to delete keys by pattern.

Example 1: Deleting keys using a single pattern

package main import ( "github.com/go-redis/redis" "fmt" ) func main() { client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) pattern := "user:*" keys, err := client.Keys(pattern).Result() if err != nil { panic(err) } for _, key := range keys { err := client.Del(key).Err() if err != nil { panic(err) } } fmt.Println("Deleted keys:", keys) }

Best Practices

When deleting keys by pattern, ensure to limit the usage in production environments because the KEYS command can be resource-intensive and might affect the performance of the Redis server if the key-space is large. Always test this operation in a controlled setting.

Common Mistakes

One common mistake is not handling errors correctly when getting keys or deleting them. It's important to always check for errors so that you can handle them appropriately and prevent your application from crashing unexpectedly.

FAQs

Q: What if I want to delete keys across all databases? A: In Redis, the KEYS command only operates on the currently selected database. You would need to run the deletion script individually for each database.

Was this content helpful?

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.