Redis Stack Exchange how to delete or get keys by pattern

25,482

Solution 1

Deletion is separate by key, unless you are flushing the entire database.

Key scanning is readily available on the IServer API, and is discussed much more here: https://stackexchange.github.io/StackExchange.Redis/KeysScan

However, it should still usually be avoided in production - that isn't the intended use-case for redis.

Solution 2

You can do as the following to batch delete items from redis cache. (StackExchange.Redis.StrongName v1.0.488)

foreach (var ep in _muxer.GetEndPoints())
{
    var server = _muxer.GetServer(ep);
    var keys = server.Keys(database: _redisDatabase, pattern: pattern + "*").ToArray();
    _db.KeyDeleteAsync(keys);
}

_muxer is instance of ConnectionMultiplexer

It does not delete by pattern as you asked but much faster than deleting each key separately.

Share:
25,482
Robert
Author by

Robert

Updated on July 05, 2022

Comments

  • Robert
    Robert almost 2 years

    I installed Stack Exchange redis client in C#. I can only delete one key or array of keys but I don't know how to delete keys with prefix. Or another solution can be first get all keys by pattern and then delete them. But I don't know how to get keys by pattern too.

  • MaurGi
    MaurGi over 6 years
    How does this work in a cluster? We are getting twice as many endpoints (including the slaves) and deleting too many keys, should we filter for server.IsSlave == false ?
  • Kerem Demirer
    Kerem Demirer over 6 years
    Haven't tried it but I think you should invoke the same servers which used in single delete methods.
  • ErroneousFatality
    ErroneousFatality over 5 years
    Your documentation link is dead.
  • Marc Gravell
    Marc Gravell over 5 years
    @ErroneousFatality fixed, ta
  • Ali Karaca
    Ali Karaca almost 3 years
    Also reader should consider that there may be another databases if using cluster(_redisDatabase default is 0)
  • Anton Semenov
    Anton Semenov over 2 years
    It works. One thing to add I had a problem slowing me with direct connections to master/slave nodes. For me helped disabling vpn on local machine or running the code on prod machines. IP addresses could not be resolved for some reason.
  • ScubaSteve
    ScubaSteve over 2 years
    What's the DI for _muxer? I am using services.AddStackExchangeRedisCache and tried DIing ConnectionMultiplexer, but it comes back as null.
  • Kerem Demirer
    Kerem Demirer over 2 years
    I've been using this approach for old .net and am not sure how it's registered in .netcore. This may help maybe: stackoverflow.com/questions/56272957/…