Ruby on rails Redis:查找范围和无序集的交点

Ruby on rails Redis:查找范围和无序集的交点,ruby-on-rails,redis,Ruby On Rails,Redis,我有一个有序的集合-我通过gem'redis'为我的redis db评分并添加的项目如下: 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或以上的所有项目,并将其与具有特定

我有一个有序的集合-我通过gem'redis'为我的redis db评分并添加的项目如下:

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查找范围和集合的交集的最佳方法是什么?

我不知道如何先获取范围,然后再进行交集。不过,您可以做的是将集合相交,然后进行范围计算:

ZINTERSTORE items_with_tag_foo 2 items tag_foo AGGREGATE MAX
ZRANGEBYSCORE items_with_tag_foo 17 +inf

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

示例:

# 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

感谢您提供有关删除临时存储的提示我在Redis 2.2.5中遇到问题。当我试图调用zinterstore命令时,我会得到这个错误。“无法在127.0.0.1:6379连接到Redis:连接被拒绝。”升级到Redis 2.4.13后,此错误消失。另一个注意事项是,在Redis 2.4.13上,我无法使用zinterstore中sunionstore的结果。再次升级修复了这个问题。现在,在2.6.10版上,一切都很好。