扫描迭代

遍历SCAN,HSCAN等。

Redis 有一小系列相关命令,用于检索 键,在某些情况下,它们的关联值:

  • SCAN检索键 来自主 Redis 键空间。
  • HSCAN检索 key 和(可选)的 它们的值。
  • SSCANSet 对象中检索键。
  • ZSCANSorted Set 对象中检索键及其 score 值。

这些命令可能会返回大量结果,因此 Redis 提供分页机制,以小批量、单独的批处理访问结果。 使用基本命令时,必须在代码中维护 cursor 值 以跟踪当前页面。作为一个方便的替代方案,redis-py还允许您使用 Iterator 访问结果。 这将透明地处理分页,因此您只需将 它以for循环或传递 iterator object 本身代替序列

每个命令都有自己的等效迭代器。以下示例显示了 如何使用SCANiterator 在 Redis 键空间上。请注意,与SCAN命令,则结果不会按任何特定顺序排序。此外,您 可以通过match,count_typeparameters 设置为scan_iter()约束 它返回的键集(请参阅SCAN命令页面)。

import redis

r = redis.Redis(decode_responses=True)

r.set("key:1", "a")
r.set("key:2", "b")
r.set("key:3", "c")
r.set("key:4", "d")
r.set("key:5", "e")

for key in r.scan_iter():
    print(f"Key: {key}, value: {r.get(key)}")
# >>> Key: key:1, value: a
# >>> Key: key:4, value: d
# >>> Key: key:3, value: c
# >>> Key: key:2, value: b
# >>> Key: key:5, value: e

The iterators for the other commands are also named with _iter() after the name of the basic command (hscan_iter(), sscan_iter(), and zscan_iter()). They work in a similar way to scan_iter() except that you must pass a key to identify the object you want to scan. The example below shows how to iterate through the items in a sorted set using zscan_iter().

r.zadd("battles", mapping={
    "hastings": 1066,
    "agincourt": 1415,
    "trafalgar": 1805,
    "somme": 1916,
})

for item in r.zscan_iter("battles"):
    print(f"Key: {item[0]}, value: {int(item[1])}")
# >>> Key: hastings, value: 1066
# >>> Key: agincourt, value: 1415
# >>> Key: trafalgar, value: 1805
# >>> Key: somme, value: 1916

Note that in this case, the item returned by the iterator is a tuple with two elements for the key and score. By default, hscan_iter() also returns a 2-tuple for the key and value, but you can pass a value of True for the no_values parameter to retrieve just the keys:

r.hset("details", mapping={
    "name": "Mr Benn",
    "address": "52 Festive Road",
    "hobbies": "Cosplay"
})

for key in r.hscan_iter("details", no_values=True):
    print(f"Key: {key}, value: {r.hget("details", key)}")
# >>> Key: name, value: Mr Benn
# >>> Key: address, value: 52 Festive Road
# >>> Key: hobbies, value: Cosplay
RATE THIS PAGE
Back to top ↑