Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve a list of all keys stored in Redis (Ruby)

Tags:

ruby

redis

Is there a function in the redis-rb gem that returns a list of all the keys stored in the DB? My end goal is to iterate over all my key/value pairs and do perform some action on them.

like image 462
Vikram Sundaram Avatar asked Aug 02 '13 16:08

Vikram Sundaram


People also ask

How do I get all Redis keys?

To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.

How do I view Redis data?

A Redis server has 16 databases by default. You can check the actual number by running redis-cli config get databases. In interactive mode, the database number is displayed in the prompt within square braces. For example, 127.0. 0.1:6379[13] shows that the 13th database is in use.

How do I view the contents of Redis cache?

By clicking on a Redis key name, all its contents will open in a new editor tab. With a collection type Redis key, clicking on it will reveal the individual elements under the key name.

Which command is used to obtain all the keys in a database?

The Redis KEYS command returns all the keys in the database that match a pattern (or all the keys in the key space). Similar commands for fetching all the fields stored in a hash is HGETALL and for all fetching the members of a SMEMBERS. The keys in Redis themselves are stored in a dictionary (aka a hash table).


2 Answers

Sure, the redis-rb exposes all of the Redis commands and represents them as methods on your client object.

redis.keys('*') 
like image 134
Alex Peachey Avatar answered Oct 04 '22 07:10

Alex Peachey


If you have any substantial amount of records in your db, kernel will kill your redis.keys because it will be taking too much RAM.

What you want is extracting keys in batches. redis-rb has a wonderful method for this (not present in redis itself):

    redis.scan_each(match: 'user:*') do |resume_key_name|         resume_key_name #=> "user:12"     end 

If you want all the keys, just don't use the match option.

like image 45
lakesare Avatar answered Oct 04 '22 05:10

lakesare