2012-05-11 58 views
3

我正在使用redis.py並想知道如何按給定字段排序。我已經閱讀了文檔並嘗試了谷歌搜索的例子,但沒有發現任何有趣的事情。redis.py - 按特定字段排序哈希

在這種情況下,我有一個時間列表和相應的溫度。對於給定範圍的'時間',比如說1000到1100,我會返回給定時間範圍內的最高值'temp',並將其分配給變量hightemp。同樣,我也想用lowtemp來做。

是否有可能Redis的範圍內做到這一點,而不是再翻譯一切恢復到內存中,如果我整理使用python

import redis 
red = redis.Redis() 

red.hmset('temperature', {'time':900, 'temp':123}) 
red.hmset('temperature', {'time':930, 'temp':123}) 
red.hmset('temperature', {'time':1000, 'time':121}) 
red.hmset('temperature', {'time':1030, 'time':125}) 
red.hmset('temperature', {'time':1100, 'time':126}) 
red.hmset('temperature', {'time':1130, 'time':127}) 
red.hmset('temperature', {'time':1200, 'time':128}) 

回答

5

經過一段時間的思考,我不得不說它是棘手的。我可以想出的最佳解決方案是:將數據存儲在sorted set中,其中time作爲分數,time:temperature作爲值(以保持值獨一無二)。然後你使用ZRANGEBYSCORE得到需要的子集:

redis 127.0.0.1:6379> zadd temperature 1000 1000:123 
(integer) 1 
redis 127.0.0.1:6379> zadd temperature 1050 1050:122 
(integer) 1 
redis 127.0.0.1:6379> zadd temperature 1100 1100:125 
(integer) 1 
redis 127.0.0.1:6379> zrangebyscore temperature 1000 1100 
1) "1000:123" 
2) "1050:122" 
3) "1100:125" 
redis 127.0.0.1:6379> 

這些值,但是,將在得分排序,即溫度。因此,您將不得不在客戶端中對子集進行排序:

# Result from Redis 
result = ['1000:123', '1050:122', '1100:125'] 
# Weed out the temperatures 
temperatures = [int(x.split(':')[1]) for x in result] 
# Get max and min temperatures 
max_temp, min_temp = max(temperatures), min(temperatures) 

這不是超級漂亮,但它應該工作。 Lloyd Moore在他的回答中說的是真實的,並且您可以通過哈希中的字段進行排序,但SORT命令不會讓您輕鬆選擇子集。如果我想到更好的解決方案,我會更新這個答案,否則我們只希望在評論中進行健康的討論!

編輯:從蟒蛇sort()更改爲max/min後迪迪埃Speza的建議。

+0

要計算最小和最大溫度,不需要適當的排序。 Python中的溫度列表中的簡單O(n)掃描更好一些:maxt,mint = max(溫度),min(溫度) –

+0

感謝@DidierSpezia,已更新! –

+0

謝謝!我原本使用這種方法,但我同意,似乎凌亂。但是,我並不認爲有更好的解決方法。只要我重新分配和覆蓋'結果'和'溫度'的變量,我應該可以確定我想要的資源。這可能會導致在不同地區的溫度大規模操作。 – snakesNbronies

2

每次運行red.hmset時間會出現這種情況你正在覆蓋溫度的值。鑑於您想對這些值進行排序,您需要爲每個條目指定一個唯一的標識符。

溫度:1,溫度:2 ...

然後,您可以使用Redis的sort命令

SORT MYLIST BY weight_ * GET object_ *

的外部鍵。

希望能以某種方式提供幫助。讓我知道你是否需要更多的幫助。

+0

是否有可能得到一個**子集**哈希?這是迄今爲止我一直在努力的問題。 – snakesNbronies