Created
September 4, 2013 00:38
-
-
Save mouse-lin/6431429 to your computer and use it in GitHub Desktop.
use redis to store autocomplete feature
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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