Skip to content

Instantly share code, notes, and snippets.

@tysonmote
Last active January 2, 2019 23:18
Show Gist options
  • Save tysonmote/5cd9e880712477f851c8 to your computer and use it in GitHub Desktop.
Save tysonmote/5cd9e880712477f851c8 to your computer and use it in GitHub Desktop.
Utility functions for performing operations on large Redis keyspaces
require 'redis'
REDIS = Redis.new( url: "..." )
def each_keys_chunk( pattern = nil, &block )
opts = { count: 100 }
opts[:match] = pattern if pattern
cursor = 0
loop do
cursor, keys = REDIS.scan( cursor, opts )
yield keys unless keys.size == 0
break if cursor.to_i == 0
end
end
def count_keys( pattern )
count = 0
each_keys_chunk( pattern ) { |keys| count += keys.size }
count
end
def del_keys( pattern )
count = 0
each_keys_chunk( pattern ) do |keys|
REDIS.pipelined do
keys.each { |key| REDIS.del( key ) }
end
count += keys.size
puts "Deleted #{count} keys"
end
puts "Done! Deleted #{count} keys"
end
def expire_keys( pattern, expiration )
count = 0
each_keys_chunk( pattern ) do |keys|
REDIS.pipelined do
keys.each { |key| REDIS.expire( key, expiration ) }
end
count += keys.size
puts "Set TTL on #{count} keys"
end
puts "Done! Set TTL on #{count} keys"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment