Redis Key Pattern Matching with KEYS Command¶
In Redis, the KEYS command is used to retrieve all keys matching a specific pattern^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. This functionality is frequently used when an application needs to find or iterate over data without knowing the specific key names in advance.
Usage¶
The basic syntax involves passing a pattern string to the command.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]
In the Go go-redis client library, this is executed via the Keys method on the client, passing a context and the pattern:
keys, err := redisClient.Keys(ctx, "*").Result()
Supported Patterns¶
Redis supports glob-style patterns for key matching^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]:
?: Matches any single character.*: Matches any count of any characters.[]: Matches any character within the brackets.
Practical Example¶
A common use case involves fetching all keys to reconstruct a data set. For example, to retrieve a list of all video objects stored as individual JSON records:
- Fetch Keys: Use
KEYSwith a wildcard (e.g.,"*") to get all relevant key names^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. - Iterate: Loop through the returned keys^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
- Retrieve Values: For each key, perform a lookup (e.g.,
GET) to deserialize the value (such as a JSON struct)^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
Related Concepts¶
- [[Redis Data Types]]
- [[Go Redis Client]]
- [[Redis Sentinel]]
Sources¶
^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]