Skip to content

Instantly share code, notes, and snippets.

@dasch
Forked from antirez/compl1.rb
Created September 10, 2010 17:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dasch/574082 to your computer and use it in GitHub Desktop.
Save dasch/574082 to your computer and use it in GitHub Desktop.
Redis auto-completion
# compl1.rb - Redis autocomplete example
# download female-names.txt from http://antirez.com/misc/female-names.txt
require 'rubygems'
require 'redis'
r = Redis.new
# Create the completion sorted set
if !r.exists(:compl)
puts "Loading entries in the Redis DB\n"
File.new('female-names.txt').each_line do |n|
n.strip!
1.upto(n.length).each do |l|
prefix = n[0...l]
r.zadd(:compl, 0, prefix)
end
r.zadd(:compl,0,n+"*")
end
else
puts "NOT loading entries, there is already a 'compl' key\n"
end
# Complete the string "mar"
def complete(r, prefix, count)
results = []
rangelen = 50 # This is not random, try to get replies < MTU size
start = r.zrank(:compl, prefix)
return [] unless start
while results.length != count
range = r.zrange(:compl, start, start + rangelen - 1)
break if range.length == 0
range.each do |entry|
if entry[-1..-1] == "*" and results.length != count
results << entry[0...-1]
end
end
end
return results
end
complete(r, "mar", 10).each do |res|
puts res
end
@dasch
Copy link
Author

dasch commented Sep 10, 2010

More Ruby-ish version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment