Hasan
Hasan

Reputation: 67

C# Redis Cache get multiple entries

So I'm using "StackExchange.Redis" and I was wondering if I can get multiple values by key pattern or by key list in order to have one trip to the redis cache and get all the data that I need.

I already tried to use "star" in the key when using the "GetObject" method something like this:

User user = RedisContext.Cache.GetObject("User*");

but this returns null.

And I also tried to get all the keys by pattern which did work but I couldn't get the values in one go, like this:

var endpoint = RedisContext.GetConnectionMultiplexer().GetEndPoints().First();
var keys = RedisContext.GetConnectionMultiplexer().GetServer(endpoint.ToString()).Keys(pattern: "User*");
List<string> keyList = new List<string>();
foreach (var _key in keys)
{
      keyList.Add(_key);
}

List<User> users = RedisContext.Cache.GetObjectsByTag<dynamic>(keyList.ToArray());

But this gives me an exception. Is there something that I'm missing?

Upvotes: 1

Views: 9764

Answers (1)

slorello
slorello

Reputation: 1149

Can you get multiple keys in one fell swoop?

Sort of answered here already

You can pass an array of RedisKeys into the StringGet or StringGetAsync methods on the IDatabase object - see the following example from nothing:

var muxer = ConnectionMultiplexer.Connect("localhost");

var db = muxer.GetDatabase();

db.StringSet("foo", "bar");
db.StringSet("baz", "foo");
db.StringSet("bar", "baz");

var result = await db.StringGetAsync(new RedisKey[]{"foo","bar","baz"});

foreach (var item in result)
{
    Console.WriteLine((string)item);
}

Can you get all the keys by pattern in one shot

You can, but shouldn't unless you want to build a secondary index. You could write a lua script to match a key pattern and then pull back all the keys with that pattern, but that will be horribly inefficient and dangerous as you would be committing to looking over your entire keyspace in one operation which is one of those things that can really hang a Redis Server.

What you can do is create a secondary index and search for the the keys matching a given pattern. This can either be done the traditional way, or you could use a module like RediSearch to help build them for you.

Upvotes: 3

Related Questions