3

I am using jedis for redis connect in java.

I want to delete similar pattern keys from redis server using jedis. e.g.
1. 1_pattern
2. 2_pattern
3. 3_pattern
4. 4_pattern
5. 5_pattern

We can use del(key), but it will delete only one key.

I want something like del("*_pattern")

dipendra
  • 235
  • 4
  • 12

4 Answers4

1

It should use regex in redis. In your code:

String keyPattern = "*"+"pattern";
// or String keyPattern = "*_"+"pattern";
Set<String> keyList = jedis.keys(keyPattern);
for(String key:keyList){
    jedis.del(key);
}

// free redis resource I think above solution work well.

VanThaoNguyen
  • 792
  • 9
  • 20
1

One of the most efficient way is to reduce the redis calls.

        String keyPattern = "*"+"pattern";
        Set<String>  keys = redis.keys(keyPattern);
        if (null != keys && keys.size() > 0) {
            redis.del(keys.toArray(new String[keys.size()]));
        }
 
0

You could combine the DEL key [key ...] command with the KEYS pattern command to get what you want.

For example, you can do this with Jedis like so (pseudocode):

// or use "?_pattern" 
jedis.del(jedis.keys("*_pattern"));

But be aware that this operation could take a long time since KEYS is O(N) where N is the number of keys in the database, DEL is O(M) where M is the number of keys, and for each key being deleted that is a list/set/etc, its O(P), where P is the length of the list/set/etc.

kuporific
  • 10,053
  • 3
  • 42
  • 46
0

See my answer here.

In your case, it's a simple call to deleteKeys("*_pattern");

Community
  • 1
  • 1
corindiano
  • 724
  • 7
  • 6