Introducing Dragonfly Cloud! Learn More

Deleting Redis Keys by Prefix in PHP (Detailed Guide w/ Code Examples)

Use Case(s)

The 'delete by prefix' functionality can be used when there's a need to remove a set of keys that share a common prefix. This is common in situations where keys are namespaced or grouped by prefixes, such as session tokens for a specific user or cached data from certain parts of an application.

Code Examples

Unfortunately, Redis does not provide a direct command to delete keys by prefix. To accomplish this, we first need to fetch all keys matching the prefix and then delete them. Here's how you can do it using PHP and the phpredis extension:

$redis = new Redis(); $redis->connect('127.0.0.1', 6379); $prefix = 'yourPrefix*'; $keys = $redis->keys($prefix); foreach($keys as $key) { $redis->del($key); }

In this example, we first establish a connection to the Redis server. Then, we use the keys function to fetch all keys that match the given prefix, and finally we iterate over these keys to delete them using the del function.

Best Practices

While the above example works, using the KEYS command in a production environment is generally not recommended because it might cause performance issues on large databases. An alternative approach is to use the SCAN command, which allows you to incrementally iterate over the keys in a more performance-friendly manner.

Common Mistakes

One common mistake is to forget about the potential performance impact of the keys function. If your database is large, fetching all keys at once can be very slow and consume a lot of resources. It's recommended to use the scan function instead, as it is designed to handle large datasets more efficiently.

FAQs

Q: Why isn't there a direct command for deleting keys by prefix in Redis?

A: Redis operations are atomic and operate on a single key-value pair at a time. This provides benefits in concurrent environments but means that some bulk operations like 'delete by prefix' are not directly supported.

Was this content helpful?

Start building today 

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