2013-02-12 56 views
3

我有一個有序集合 - 我已經通過了創業板redis的「得分,並添加到我的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查找範圍和集合的交集的最佳方法?

+0

我是有Redis的2.2.5中的問題。當我試圖調用zinterstore命令時,我會得到這個錯誤。 「無法連接到Redis 127.0.0.1:6379:連接被拒絕。」升級到Redis 2.4.13後,這個錯誤消失了。 – Swards 2013-02-12 19:10:37

+0

另一個說明 - 關於redis 2.4.13,我無法使用zionterstore中的sunionstore的結果。升級再次解決了這個問題。現在在版本2.6.10上運行良好。 – Swards 2013-02-16 19:20:41

回答

2

的關鍵點是有序集合的命令也接受常規集合作爲參數。因此,您可以先與該集合相交,然後使用正常範圍命令根據分數進行過濾。

實施例:

# 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 
+0

感謝您刪除臨時商店的提示 – Swards 2013-02-12 19:09:46

1

我不知道有一種方法先獲取範圍,然後再相交。你可以做什麼,雖然是使集的交集,然後執行範圍:

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

我明白了 - 這很有道理。 – Swards 2013-02-12 19:02:31