Dragonfly Cloud is now available in the AWS Marketplace - learn more

Java Redis Delete Keys by Prefix (Detailed Guide w/ Code Examples)

Use Case(s)

Deleting keys with a certain prefix is common when you want to clear a subset of data within your Redis database. This is usually done in scenarios where related keys have a common prefix, such as session ids for particular users or cached values from a specific operation.

Code Examples

In Java, we use the Jedis library to interact with Redis. Below are the code examples.

  1. Deleting all keys with a given prefix:

    import redis.clients.jedis.Jedis; import java.util.Set; public class Main { public static void main(String[] args) { Jedis jedis = new Jedis("localhost"); Set<String> keys = jedis.keys("prefix*"); keys.forEach(jedis::del); jedis.close(); } }

    Here, we first connect to the Redis server running on localhost. Then we get all the keys that start with 'prefix' using the keys method. Finally, we delete each key using the del method.

Best Practices

  • Be careful while deleting keys as it can lead to loss of important data.
  • It's best not to use the keys command in a production environment as it can potentially block the Redis server while it is executing, especially when the key space is large. Instead, consider using SCAN in combination with MATCH for safer deletion.

Common Mistakes

  • A common mistake is trying to delete keys without checking if they exist or not. Always ensure that the keys you're trying to delete actually exist.

FAQs

  • Q: Can I delete multiple keys in Redis at once? A: Yes, Redis allows deletion of multiple keys at once using the del command.

Was this content helpful?

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost