Skip to content
This repository was archived by the owner on Feb 21, 2023. It is now read-only.

Commit e41b41c

Browse files
hrandfield (redis/redis-py#1513) Signed-off-by: Andrew-Chen-Wang <[email protected]>
1 parent b7ede71 commit e41b41c

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

aioredis/client.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2041,6 +2041,28 @@ def pttl(self, name: KeyT) -> Awaitable:
20412041
"""Returns the number of milliseconds until the key ``name`` will expire"""
20422042
return self.execute_command("PTTL", name)
20432043

2044+
def hrandfield(
2045+
self, key: str, count: int = None, withvalues: bool = False
2046+
) -> Awaitable:
2047+
"""
2048+
Return a random field from the hash value stored at key.
2049+
2050+
count: if the argument is positive, return an array of distinct fields.
2051+
If called with a negative count, the behavior changes and the command
2052+
is allowed to return the same field multiple times. In this case,
2053+
the number of returned fields is the absolute value of the
2054+
specified count.
2055+
withvalues: The optional WITHVALUES modifier changes the reply so it
2056+
includes the respective values of the randomly selected hash fields.
2057+
"""
2058+
params = []
2059+
if count is not None:
2060+
params.append(count)
2061+
if withvalues:
2062+
params.append("WITHVALUES")
2063+
2064+
return self.execute_command("HRANDFIELD", key, *params)
2065+
20442066
def randomkey(self) -> Awaitable:
20452067
"""Returns the name of a random key"""
20462068
return self.execute_command("RANDOMKEY")

tests/test_commands.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -962,6 +962,19 @@ async def test_pttl_no_key(self, r: aioredis.Redis):
962962
"""PTTL on servers 2.8 and after return -2 when the key doesn't exist"""
963963
assert await r.pttl("a") == -2
964964

965+
@skip_if_server_version_lt("6.2.0")
966+
def test_hrandfield(self, r):
967+
assert await r.hrandfield("key") is None
968+
await r.hset("key", mapping={"a": 1, "b": 2, "c": 3, "d": 4, "e": 5})
969+
assert await r.hrandfield("key") is not None
970+
assert len(await r.hrandfield("key", 2)) == 2
971+
# with values
972+
assert len(await r.hrandfield("key", 2, True)) == 4
973+
# without duplications
974+
assert len(await r.hrandfield("key", 10)) == 5
975+
# with duplications
976+
assert len(await r.hrandfield("key", -10)) == 10
977+
965978
async def test_randomkey(self, r: aioredis.Redis):
966979
assert await r.randomkey() is None
967980
for key in ("a", "b", "c"):

0 commit comments

Comments
 (0)