gpt4 book ai didi

ruby-on-rails - Redis:查找范围和无序集的交集

转载 作者:IT王子 更新时间:2023-10-29 06:01:41 27 4
gpt4 key购买 nike

我有一个有序的集合 - 我已经评分并通过 gem 'redis' 添加到我的 redis 数据库的项目,如下所示:

Item.each { |item|
$redis.zadd("scores", item.score, item.id)
}

还有一组包含基于标签 ID 的键的项目。

Tag.each { |tag|
tag.items.each { |item|
$redis.sadd("tag_#{tag.id}", item.id)
}
}

我正在尝试获取得分为 x 或更高 的所有项目,并将其与具有特定标签的所有项目相交。我不需要对结果进行排序。我不确定首先是否需要使用有序集,但这似乎是一种存储和检索结果的有效方式。

使用 Redis 查找范围和集合的交集的最佳方法是什么?

最佳答案

关键是排序集命令也接受普通集作为参数。因此,您可以先与集合相交,然后使用正常范围命令根据分数进行过滤。

示例:

# Populate some sorted set and set
./redis-cli zadd scores 1 a 2 b 3 c 4 d 5 e 6 f 7 g 8 h
(integer) 8
./redis-cli sadd tag_1 a c d g h
(integer) 5

# Here you need to use a weight clause to avoid altering the score
./redis-cli zinterstore res 2 scores tag_1 weights 1 0
(integer) 5

# Now fetch the expected items (here we want items with score >= 4)
./redis-cli zrangebyscore res 4 +inf withscores
1) "d"
2) "4"
3) "g"
4) "7"
5) "h"
6) "8"

# Finally drop the temporary result
./redis-cli del res
(integer) 1

关于ruby-on-rails - Redis:查找范围和无序集的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14823841/

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