ruby-on-rails - 在 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 集
解决方案
zincrby
使用已排序的字符串集,但没有什么能阻止您使用对象的 JSON 表示:
$redis.zincrby "search-suggestions:#{prefix.downcase}",
1,
JSON.dump({key: val, ...})
推荐阅读
- javascript - : 和 :? 的区别
- django - Django:如何在两个FormFields之间验证/验证一个“更大的”?
- go - 如何在不出现死锁错误的情况下获得所有结果
- oracle - 如何动态旋转字符串
- c# - OpenXml Word 文档 - 在文件中发现不可读的内容
- python - 在python中将列表列表合并到单个列表中时删除重复项
- c# - 使查询异步
- kubernetes - 在 Kubernetes 或 OpenShift 上使用 Ansible Operator 时,如何获取嵌套规范项的值?
- javascript - 何时使用 Svelte 的 use:action 与 onMount 和 onDestroy?
- html - 如何使用内联 CSS 在中心的无序列表中对齐项目符号