2017-08-08 66 views
0

我有redis鍵和這些鍵的值作爲哈希集(鍵,值對)。我正在使用python來檢索關鍵值。 例如:使用通配符搜索迭代Redis哈希鍵

top_link:files 
    key: file_path/foldername1 
    value: filename1 

    key: file_path/foldername2 
    value: filename2 

    key: test_path/foldername3 
    value: filename3 

我想找出所有的hash組鍵,其鍵名稱以「FILE_PATH」

我試圖

all_keys = redis_connection.hscan_iter("top_link:files") 
for key in all_keys: 
    if key.startswith("file_path"): 
    redis_connection.hget("top_link:files",key) 

開始有沒有更好的方式來發現所有的哈希以「file_path」開頭的密鑰。 SCAN似乎正在做我正在努力實現的目標。但是所有的例子都顯示了頂層關鍵字(top_link:files)的掃描,而不是關於散列鍵的掃描。有什麼建議麼? 謝謝。

回答

1

您可以在hscan_iter中提供match模式以獲得僅匹配的密鑰對。通過hscan_iter,您可以獲得鍵值對,如tuple s。因此,您不必使用hget來獲取值。

matched_pairs = redis_connection.hscan_iter('top_link:files', match='file_path*') 
for keyvalue in matched_pairs: 
    # Here `keyvalue` is a tuple containing key and value 
    print keyvalue[0], keyvalue[1] 

輸出:

file_path/foldername2 filename2 
file_path/foldername1 filename1 
+0

當我如下使用HSCAN,它給了我整個哈希集合的元組。 但你能告訴我如何獲取匹配的密鑰?redis_connection.hscan(「top_link:files」,match =「file_path *」) – user2406718

+0

謝謝。有效。 – user2406718