public
Last active

  • Download Gist
compl1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
# 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{|n|
n.strip!
(1..(n.length)).each{|l|
prefix = n[0...l]
r.zadd(:compl,0,prefix)
}
r.zadd(:compl,0,n+"*")
}
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 [] if !start
while results.length != count
range = r.zrange(:compl,start,start+rangelen-1)
start += rangelen
break if !range or range.length == 0
range.each {|entry|
minlen = [entry.length,prefix.length].min
if entry[0...minlen] != prefix[0...minlen]
count = results.count
break
end
if entry[-1..-1] == "*" and results.length != count
results << entry[0...-1]
end
}
end
return results
end
 
complete(r,"marcell",50).each{|res|
puts res
}

Quick line-by-line (ish) port to Python: http://gist.github.com/577852

What is the advantage over loading the entries in memory (as a ruby constant) and use that constant for autocompletion? Assuming redis will hold the entries in memory.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.