首页 > 解决方案 > 在 redis 中使用 ZINCRBY 存储哈希

问题描述

我正在尝试使用 redis 来缓存我的站点搜索的自动完成。我遇到了一个教程,该教程向您展示了如何存储纯字符串:

$redis.zincrby "search-suggestions:#{prefix.downcase}", 1, term.downcase

我想知道是否有办法在仍然使用ZINCRBY. 我正在考虑尝试做这样的事情:

$redis.zincrby "search-suggestions:#{prefix.downcase}", 1, {key: val, ...}

完整代码示例:

class SearchSuggestion
  def self.terms_for(prefix)
    $redis.zrevrange "search-suggestions:#{prefix.downcase}", 0, 9
  end 

  def self.index_products
    Product.find_each do |product|
      index_term(product.name)
      product.name.split.each { |t| index_term(t) }
      index_term(product.category)
    end
  end

  def self.index_term(term)
    1.upto(term.length - 1) do |n|
      prefix = term[0, n]
      $redis.zincrby "search-suggestions:#{prefix.downcase}", 1, term.downcase
    end
  end
end

资料来源:Railscast:第 399 集

标签: ruby-on-railsrubyredis

解决方案


zincrby使用已排序的字符串集,但没有什么能阻止您使用对象的 JSON 表示:

交互式redis示例

$redis.zincrby "search-suggestions:#{prefix.downcase}",
               1,
               JSON.dump({key: val, ...})

推荐阅读