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")

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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()]));
        }
 

Comments

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.

Comments

0

See my answer here.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.