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

26,566

Solution 1

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

redis.keys('*')

Solution 2

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.

Solution 3

redis.keys this will return the result in array form.

more info : http://www.rubydoc.info/github/ezmobius/redis-rb/Redis

Share:
26,566
Vikram Sundaram
Author by

Vikram Sundaram

Updated on December 21, 2020

Comments

  • Vikram Sundaram
    Vikram Sundaram over 3 years

    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.

  • Abe Voelker
    Abe Voelker over 7 years
    This was extremely slow for me; it took like 15 seconds to return on a Redis database with only 5.6K keys.
  • Fangxing
    Fangxing about 7 years
    @AbeVoelker You can use redis with pipelined, which will be faster
  • Siwei
    Siwei about 6 years
    see @Alex answer. simple and straightforward
  • Evgenia Karunus
    Evgenia Karunus about 6 years
    @SiweiShen申思维, his answer will fail for too many keys. But it is nice for a couple hundred.
  • littleDucky
    littleDucky about 5 years
    @SiweiShen申思维 , using .keys is discouraged because of blocking issues and performance.
  • littleDucky
    littleDucky about 5 years
    .keys will cause blocking and performance issues. .scan or .scan_each should be used instead. stackoverflow.com/questions/22143659/…
  • littleDucky
    littleDucky about 5 years