Created
March 15, 2013 23:23
-
-
Save martinx/5173984 to your computer and use it in GitHub Desktop.
基于redis的SearchSuggestion
This file contains 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
class SearchSuggestion | |
def self.terms_for(prefix) | |
return if prefix.blank? | |
puts "prefix:#{prefix}" | |
prefix_array = prefix.split | |
puts prefix_array | |
unless prefix_array.empty? | |
$redis.zinterstore "$tmp",prefix_array | |
terms = $redis.zrevrange "$tmp", 0, 4 | |
puts terms | |
product_ids = [] | |
terms.each do |term| | |
product_id = term.split("|").last | |
product_ids << product_id if product_id.to_i > 0 | |
end | |
@productrs = Product. | |
where(:id=>product_ids). | |
includes(:product_category,:merchant). | |
select("name value,price,image_url") | |
end | |
end | |
def self.index_products | |
begin_at = Time.now | |
puts "#{begin_at.strftime('%Y-%m-%d %H:%M:%S')}\tbegin" | |
$redis.flushdb #flushall | |
Product.find_each do |product| | |
print '.' | |
product.name.split.each { |term| index_term(term,product.id,product.name) } | |
end | |
end_at = Time.now | |
puts "\n#{end_at.strftime('%Y-%m-%d %H:%M:%S')}\tend,cost:#{end_at - begin_at}s" | |
end | |
def self.index_term(term,product_id,product_name) | |
product_name = product_name.gsub(/\s+/," ").gsub(" ","/") | |
1.upto(term.length) do |n| | |
prefix = term[0, n] | |
$redis.zincrby "#{prefix.downcase}", 1, "#{product_name.downcase}|#{product_id}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment