Skip to content

Instantly share code, notes, and snippets.

@mouse-lin
Created September 4, 2013 00:38
Show Gist options
  • Save mouse-lin/6431429 to your computer and use it in GitHub Desktop.
Save mouse-lin/6431429 to your computer and use it in GitHub Desktop.
use redis to store autocomplete feature
require "redis"
redis = Redis.new
def get_prefixes word
Array.new(word.length) do |i|
if i == word.length - 1
"#{ word }*"
else
word[0..i]
end
end
end
redis.del "autocomplete"
argv = []
File.open("content.txt").each_line do |word|
get_prefixes(word.chomp).each do |prefix|
argv << [0, prefix]
end
end
redis.zadd "autocomplete", argv
while prefix = gets.chomp do
result = []
if rank = redis.zrank("autocomplete", prefix)
redis.zrange("autocomplete", rank + 1, rank + 100).each do |words|
if words[-1] == "*" && prefix == words[0..prefix.length - 1]
result << words[0..-2]
end
end
end
puts result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment