Kat
Kat

Reputation: 2500

How can I get a key count for StackExchange.Redis?

I have an azure redis cache. I've set it up so that I can do stringGet key setting based off this example. It works pretty great.

However, I want to know if the cache is empty or not, or if there are any entries of (x) type of a C# object I have. I currently want to see if I can get a key count. I haven't found any solutions for this.

My only idea is to do a key scan that would search for every key (a get all) and then do a count. But that seems inefficient. Is there a more "meta" data style solution?

Thanks!

Upvotes: 5

Views: 5068

Answers (2)

Riaan
Riaan

Reputation: 3552

Try the following snippet of code.

It will take some time to calculate and fetch it all as its using paging by default. If you on the same network and close proximity, 4 million records should take roughly 10 seconds to return a result.

var redis = ConnectionMultiplexer.Connect(configuration);

var db = redis.GetDatabase();

var keyCount = db.Multiplexer.GetEndPoints()
   .Select(endPoint => db.Multiplexer.GetServer(endPoint))
   .Sum(server => server.Keys().Count());

Alternatively, you may also run the following command in C# to get a response from the server instantaneously.

var result = db.Execute("DBSIZE");
var keyCount = (long)result;

Upvotes: 0

Bruce Chen
Bruce Chen

Reputation: 18465

Per my understanding, you could leverage IServer.Keys to retrieve all keys with matching pattern as follows:

var endpoints=ConnectionMultiplexer.GetEndPoints();
var server = ConnectionMultiplexer.GetServer(endpoints.First());
var keys = server.Keys();

For more details about keys scanning, you could refer to this tutorial.

Upvotes: 7

Related Questions