41

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.

Vikram Sundaram
  • 483
  • 1
  • 5
  • 7

3 Answers3

44

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

redis.keys('*')
Alex Peachey
  • 4,606
  • 22
  • 18
  • 4
    `.keys` will cause blocking and performance issues. `.scan` or `.scan_each` should be used instead. https://stackoverflow.com/questions/22143659/ruby-redis-client-scan-vs-keys – ives Mar 02 '19 at 18:34
29

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.

Evgenia Karunus
  • 10,715
  • 5
  • 56
  • 70
8

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

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

sudistack
  • 109
  • 1
  • 4