2016-05-03 31 views

回答

1

可以使用ZRANGEBYSCORE用Lua的腳本。想象一下以下有序集合:

zadd test 1 a 
zadd test 2 b 
zadd test 4 c 

你有得分爲1,2,4 3組的元素和你想打電話ceiling(3)。將下面的Lua腳本script.lua

local key = KEYS[1] 
local givenScore = tonumber(ARGV[1]) 
local scores = redis.call("ZRANGEBYSCORE", key, givenScore, "+inf", "withscores", "limit", 0, 1) 
if (scores == nil or #scores<2) then 
    return nil 
end 
return tonumber(scores[2]) 

,並稱之爲:

$ redis-cli eval "$(cat script.lua)" 1 test 3 

下面是一些示例與上面的數據集運行:

$ redis-cli eval "$(cat script.lua)" 1 test 2 
(integer) 2 
$ redis-cli eval "$(cat script.lua)" 1 test 3 
(integer) 4 
$ redis-cli eval "$(cat script.lua)" 1 test 4 
(nil) 
+0

感謝杜魯,它是確定你的腳本,但它不適合我的數據。我有13200000個按鍵。將範圍從1變爲-1,然後忽略幾乎所有的東西是不可能的。我可以得出結論:對於redis中的排序集合,沒有「ceiling」或「scalable O(log n max)上限技巧」?如果是這樣,請編輯你的答案,我會接受它:)再次感謝:) – Costin

+0

@Costin現在我明白了。我已經用更有效的解決方案更新了我的答案。它是'O(log(n))',所以應該適合你的情況:) –

+0

我使用這個地理定位。輸入數據是一個字典'range:value':'ip1-ip2':'location'。 IP是一個整數。我想象一個對應於有序集合的鍵,並將分數保持爲'ip2',並將其作爲'位置'的成員。如果我要求'ip2-1',我希望獲得與'ip2'相同的位置(假設ip1小於ip2)。就像Java中的NavigableSet.ceiling(key)一樣:) – Costin

相關問題