Introducing Dragonfly Cloud! Learn More

PHP Redis: Get All Keys Matching Pattern (Detailed Guide w/ Code Examples)

Use Case(s)

Finding keys in a Redis database matching a certain pattern is useful when you want to perform a mass operation on these keys, or need to filter keys based on specific criteria.

Code Examples

Let's assume we have a few keys such as user:1, user:2, user:3 and we're looking for all keys starting with 'user'.

The Predis client library can be used to connect PHP with Redis:

require "vendor/autoload.php"; Predis\Autoloader::register(); $client = new Predis\Client(); $keys = $client->keys('user:*'); print_r($keys);

The keys method of the Predis client object is used to fetch all keys that match a given pattern. The '*' character is a wildcard that matches any sequence of characters.

Best Practices

  • Since using KEYS command can be expensive in production as it might lead to blocking the entire Redis instance while scanning keys, consider using SCAN if possible.
  • Always limit the number of keys being fetched at one time to prevent memory issues.

Common Mistakes

  • Using the wrong type of wildcard can lead to unexpected results. Be sure you understand how wildcards work in Redis.
  • Forgetting that key scanning in Redis is case-sensitive.

FAQs

  • Q: Can I use multiple patterns in a single KEYS command? A: No, the Redis KEYS command only supports a single pattern.
  • Q: What happens if there are no keys matching the pattern? A: The KEYS command returns an empty list if no keys match the pattern.

Was this content helpful?

Start building today 

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