Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackExchange Redis delete all keys that start with

I have a key in the format:

Error.1
Error.24
Error.32

Using StackExchange.Redis, how would I go about KeyDelete on all keys that match the format Error.?

On another answer I've seen the LUA script:

EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 Error.*

But I'm unsure how to call this using Database.ScriptEvaluate()

like image 505
Tom Gullen Avatar asked Dec 20 '16 17:12

Tom Gullen


1 Answers

Just get all keys matching the pattern, iterate and delete, something like this:

using (var redisConnection = ConnectionMultiplexer.Connect(...))
{
    var server = redisConnection.GetServer(endpoint:...);

    if (server != null)
    {
         foreach (var key in server.Keys(pattern: "Error.*"))
         {
               redisConnection.Database.KeyDelete(key);
         }
    }
}

Later edit:

Example of setting up a Redis Connection: https://gist.github.com/cristipufu/9ad47caf3dba60d712484d0c880597b9

The multiplexer should be stored and reused, not disposed and recreated each time. https://stackexchange.github.io/StackExchange.Redis/Basics

Performance can be significantly increased by adjusting / specifying the pageSize parameter of the Keys call. Its default value is 10. Try 1,000.

StackExchange.Redis server.Keys(pattern:"IsVerySlow*")

like image 159
Cristi Pufu Avatar answered Nov 03 '22 15:11

Cristi Pufu