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.
Asked
Active
Viewed 3.4k times
3 Answers
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
-
1This was extremely slow for me; it took like 15 seconds to return on a Redis database with only 5.6K keys. – Abe Voelker Sep 13 '16 at 08:04
-
-
-
@SiweiShen申思维, his answer will fail for too many keys. But it is nice for a couple hundred. – Evgenia Karunus Feb 18 '18 at 09:29
-
@SiweiShen申思维 , using `.keys` is discouraged because of blocking issues and performance. – ives Mar 02 '19 at 18:33
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
-
https://stackoverflow.com/questions/22143659/ruby-redis-client-scan-vs-keys – ives Mar 02 '19 at 18:39