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.
In Java, we use the Jedis library to interact with Redis. Below are the code examples.
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.
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.del
command.Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.