使用通配符搜索迭代 Redis 哈希键

iterating over Redis hash keys with a wild card search

我有 redis 键和这些键的值作为哈希集(键,值对)。我正在使用 python 来检索键值。 例如:

top_link:files
    key: file_path/foldername1
    value: filename1

    key: file_path/foldername2
    value: filename2

    key: test_path/foldername3
    value: filename3

我想找出键名以"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) 的扫描,而不是对哈希键的扫描。有什么建议么? 谢谢。

您可以在 hscan_iter 中提供 match 模式以获取成对的匹配键。通过 hscan_iter,您将获得 tuple 的键值对。因此,您不必使用 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