Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis/Jedis - Delete by pattern?

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:*
like image 928
iCodeLikeImDrunk Avatar asked Jan 23 '14 19:01

iCodeLikeImDrunk


People also ask

How to delete keys in Redis using 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.

How do I delete a specific data in Redis?

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.

How to delete multiple keys in Redis cli?

You have to use the SCAN command to get all keys that match the pattern, then use the DEL command to remove these keys.

How does Jedis connect to Redis?

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.


1 Answers

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()]));
}
like image 61
Aprille Avatar answered Oct 01 '22 08:10

Aprille