skyork
skyork

Reputation: 7381

Find all the keys matching a prefix and retrieve their values in Redis

I have a bunch of keys of the following pattern:

config:id:attr

Now I want to read all the configs by first finding all the keys starting with config:, and then retrieving their associated values.

What is an efficient way of doing this?

Note: keys() method does the job, but is not recommended for production usage.

Upvotes: 4

Views: 7288

Answers (1)

dpick
dpick

Reputation: 153

Keys is not recommended to use in production because it is O(N) where N is the number of keys in your redis instance. If you don't have a lot of config values it would be reasonable to use keys. However, it wouldn't be very scalable and I wouldn't recommend it.

My solution would be to just store all the config key names in another list in redis. Just insert into the list as well when you add a new config value.

Another reasonable alternative would be to just store all the config values in a hash like:

config => { "id:attr" => value }

You could then get all the config keys by calling hkeys('config').

Upvotes: 4

Related Questions