gpt4 book ai didi

ruby-on-rails - Redis 查找 set 包含元素的键

转载 作者:可可西里 更新时间:2023-11-01 10:59:10 26 4
gpt4 key购买 nike

我有一个关于让 Redis 根据集合中的属性搜索键的问题。例如,我有一个发送通知的应用程序,出于某种原因,我不想使用数据库来存储已发送通知的数组,而我目前必须这样做。该应用程序使用 Ruby on Rails 和 ruby​​ redis gem。我有:

项目.rb

def red
red = Redis.new(:host => "localhost", :port => redis_port, :db => 3)
end

# where I store the ids of notified users for the project
def notified_users
red.smembers("projects:" + self.id.to_i.to_s + ":notifications")
end

# method to add the user_id to notifications list, called from a background job that sends mails
def notify!(user_id)
red.sadd("projects:" + self.id.to_i.to_s + ":notifications", user_id.to_i)
end

问题是我如何找到那些 project_id,或者至少找到所有 redis_objects 的键,其中包含某个 user_id?我正在尝试写类似的东西:

def self.notified_projects(user_id)
# return all the keys from redis where user_id is inside a set
end

也许我错过了文档中的某些内容,但我没有找到任何方法可以做到这一点。我感谢任何帮助。

最佳答案

Redis 是一个键值存储,在键值存储中,大多数键是可搜索的,并且是查询的一部分(大部分)。我建议您不要搜索值集,而是以某种方式更改您的设计,以便您可以将元素表示为键而不是设置值,您可以轻松地将其与 wildcard 匹配。

因此,使用它们自己的键分别存储您的元素,并将该键标识符添加到您的集合中。

'notification_set': ['project:343', 'project:3423']
'project:343': 'project 343 value'
'project:3423': 'project 3423 value'

SSCAN 命令可以迭代设置值。检查出来:- SSCAN

关于ruby-on-rails - Redis 查找 set 包含元素的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32743153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com