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.
This code connects to a local Redis instance, then it scans keys that match the prefix
myprefix. Matching keys are then deleted using
KEYScommand followed by
DELin production environments.
KEYScan block the server when used against large databases, prefer
Q: Can I delete keys with multiple different prefixes at once?
A: No, you need to run separate
Del operations for each prefix.
Q: What happens if there are no keys matching the prefix?
Scan function will simply return an empty list, and no keys will be deleted.