Skip to content

Commit 627db54

Browse files
hrandfield (#1513)
* hrandfield * use mapping in hset * skip if version not fit * remove empty line * flake8 comments * new line for each comment
1 parent ad4779e commit 627db54

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

redis/client.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1879,6 +1879,26 @@ def pttl(self, name):
18791879
"Returns the number of milliseconds until the key ``name`` will expire"
18801880
return self.execute_command('PTTL', name)
18811881

1882+
def hrandfield(self, key, count=None, withvalues=False):
1883+
"""
1884+
Return a random field from the hash value stored at key.
1885+
1886+
count: if the argument is positive, return an array of distinct fields.
1887+
If called with a negative count, the behavior changes and the command
1888+
is allowed to return the same field multiple times. In this case,
1889+
the number of returned fields is the absolute value of the
1890+
specified count.
1891+
withvalues: The optional WITHVALUES modifier changes the reply so it
1892+
includes the respective values of the randomly selected hash fields.
1893+
"""
1894+
params = []
1895+
if count is not None:
1896+
params.append(count)
1897+
if withvalues:
1898+
params.append("WITHVALUES")
1899+
1900+
return self.execute_command("HRANDFIELD", key, *params)
1901+
18821902
def randomkey(self):
18831903
"Returns the name of a random key"
18841904
return self.execute_command('RANDOMKEY')

tests/test_commands.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,19 @@ def test_pttl_no_key(self, r):
895895
"PTTL on servers 2.8 and after return -2 when the key doesn't exist"
896896
assert r.pttl('a') == -2
897897

898+
@skip_if_server_version_lt('6.2.0')
899+
def test_hrandfield(self, r):
900+
assert r.hrandfield('key') is None
901+
r.hset('key', mapping={'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5})
902+
assert r.hrandfield('key') is not None
903+
assert len(r.hrandfield('key', 2)) == 2
904+
# with values
905+
assert len(r.hrandfield('key', 2, True)) == 4
906+
# without duplications
907+
assert len(r.hrandfield('key', 10)) == 5
908+
# with duplications
909+
assert len(r.hrandfield('key', -10)) == 10
910+
898911
def test_randomkey(self, r):
899912
assert r.randomkey() is None
900913
for key in ('a', 'b', 'c'):

0 commit comments

Comments
 (0)