How to get all keys that match a specific pattern

2019-06-25 09:03发布

问题:

I would like to get all keys, with its values, from a hash, where the keys match a specific pattern. I use redis with the c# library ServiceStack.Redis.

I have found the command Keys with a pattern: http://redis.io/commands/keys if it is simple string_key -- string_val but nothing if its within a hash.

There is List<string> GetValuesFromHash(string hashId, params string[] keys); but it only works if the keys perfectyl match the keys in redis. A key:* would return null

e.g.

myHash = 
key:1 -- val1, 
asdf -- asdfe,
key:2 -- val2

Now I would like to get all keys with its values from myHash if the key, within the hash, matches the following pattern: key:*

That would result in

key:1 -- val1, 
key:2 -- val2

回答1:

Redis does not support this directly: http://redis.io/commands#hash

You are limited to querying all keys at once or one or more keys specified by their exact name. This usage pattern probably means you need a hash plus another data structure (e.g. set) to keep record of the interesting keys, or two or more separate hashes. Since Redis supports atomic updates to multiple structures at once this is usually the way to go.