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
Author by
Vikram Sundaram
Updated on December 21, 2020Comments
-
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 over 7 yearsThis was extremely slow for me; it took like 15 seconds to return on a Redis database with only 5.6K keys.
-
Fangxing about 7 years@AbeVoelker You can use redis with
pipelined
, which will be faster -
Siwei about 6 yearssee @Alex answer. simple and straightforward
-
Evgenia Karunus about 6 years@SiweiShen申思维, his answer will fail for too many keys. But it is nice for a couple hundred.
-
littleDucky about 5 years@SiweiShen申思维 , using
.keys
is discouraged because of blocking issues and performance. -
littleDucky about 5 years
.keys
will cause blocking and performance issues..scan
or.scan_each
should be used instead. stackoverflow.com/questions/22143659/… -
littleDucky about 5 years