3

I am trying to go through the list of dbX in Redis via StackExchange.Redis and look for the particular type of the keys. There are string, list, set, zset, hash types of keys. Lets say I would like to find the list types of keys in the db1, I tried the following:

RedisCacheClient _client;
...
IRedisDatabase database = _client.GetDb(1);
List<InfoDetail> categorizedInfo = await database.GetInfoCategorizedAsync();
IEnumerable<InfoDetail> infos = categorizedInfo.Where(i => i.Category == "Keyspace");

This helps me with getting the basic info about the keys keys=9,expires=0,avg_ttl=0 but not the types.

I can find all the keys:

IEnumerable<string> keys = await database.SearchKeysAsync("*");

But that gives me only the names, not the types of the keys. So, how do I find the type of the key?.

Is this possible to do?

Thanks.

tridy
  • 1,166
  • 1
  • 12
  • 21

2 Answers2

2

I think I have found the solution. the IRedisDatabase type has the Database propery of type IDatabase, and IDatabase type has KeyType() method that I could use (it should have been GetKeyType(), I think, which would've made it much easier to find). With that, I was able to list the keys with types:

RedisCacheClient _client;
...
IRedisDatabase redisDatabase = _client.GetDb(1);
IEnumerable<string> keys = await redisDatabase.SearchKeysAsync("*");
IDatabase database = redisDatabase.Database;
Dictionary<string, RedisType> keysWithTypes = keys.ToDictionary(k => k, k => database.KeyType(k));

the result looks something like this:

{[myHash, Hash]}
{[myZSet, SortedSet]}
{[myString, String]}
{[mySet, Set]}
{[mylist, List]}
tridy
  • 1,166
  • 1
  • 12
  • 21
  • 1
    after some time experimenting around with searching keys, I think it is worth adding that listing all keys from Redis is done better via SCAN, and in StackExchange.Redis, there is server.Keys method that does it in a more efficiant way than SearchKeysAsync("*") from my example. It is explained in the following post: https://stackoverflow.com/a/26440148/1694087 – tridy Nov 26 '19 at 23:13
-1

Redis has TYPE command which gives you the type of the key. I suppose any client would support this.

Returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset, hash and stream.

https://redis.io/commands/type

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54