Normally, I get the key set then use a look to delete each key/value pair.
Is it possible to just delete all keys via pattern?
ie:
Del sample_pattern:*
Redis does not offer a way to bulk delete keys. You can however use redis-cli and a little bit of command line magic to bulk delete keys without blocking redis. This command will delete all keys matching users:* If you are in redis 4.0 or above, you can use the unlink command instead to delete keys in the background.
There are two major commands to delete the keys present in Redis: FLUSHDB and FLUSHALL. We can use the Redis CLI to execute these commands. The FLUSHDB command deletes the keys in a database. And the FLUSHALL command deletes all keys in all databases.
You have to use the SCAN command to get all keys that match the pattern, then use the DEL command to remove these keys.
The Java CodeJedis jedis = new Jedis("localhost"); // prints out "Connection Successful" if Java successfully connects to Redis server. Here is a breakdown of the above code: Jedis jedis = new Jedis("localhost"); This connects our Java to Redis server running on our local host.
KEYS is not recommended to use due to its inefficiencies when used in production. Please see https://redis.io/commands/keys. Instead, it is better to use SCAN. Additionally, a more efficient call than repeated calls to jedis.del() is to make one single call to jedis to remove the matching keys, passing in an array of keys to delete. A more efficient solution is presented below:
Set<String> matchingKeys = new HashSet<>();
ScanParams params = new ScanParams();
params.match("sample_pattern:*");
try(Jedis jedis = jedisPoolFactory.getPool().getResource()) {
String nextCursor = "0";
do {
ScanResult<String> scanResult = jedis.scan(nextCursor, params);
List<String> keys = scanResult.getResult();
nextCursor = scanResult.getStringCursor();
matchingKeys.addAll(keys);
} while(!nextCursor.equals("0"));
if (matchingKeys.size() == 0) {
return;
}
jedis.del(matchingKeys.toArray(new String[matchingKeys.size()]));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With