Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hrandfield #1513

Merged
merged 6 commits into from
Jul 22, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1820,6 +1820,26 @@ def pttl(self, name):
"Returns the number of milliseconds until the key ``name`` will expire"
return self.execute_command('PTTL', name)

def hrandfield(self, key, count=None, withvalues=False):
"""
Return a random field from the hash value stored at key.

count: if the argument is positive, return an array of distinct fields.
If called with a negative count, the behavior changes and the command
is allowed to return the same field multiple times. In this case,
the number of returned fields is the absolute value of the
specified count.
withvalues: The optional WITHVALUES modifier changes the reply so it
includes the respective values of the randomly selected hash fields.
"""
params = []
if count is not None:
params.append(count)
if withvalues:
params.append("WITHVALUES")

return self.execute_command("HRANDFIELD", key, *params)

def randomkey(self):
"Returns the name of a random key"
return self.execute_command('RANDOMKEY')
Expand Down
10 changes: 10 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,16 @@ def test_pttl_no_key(self, r):
"PTTL on servers 2.8 and after return -2 when the key doesn't exist"
assert r.pttl('a') == -2

@skip_if_server_version_lt('6.2.0')
def test_hrandfield(self, r):
assert r.hrandfield('key') is None
r.hset('key', mapping={'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5})
assert r.hrandfield('key') is not None
AvitalFineRedis marked this conversation as resolved.
Show resolved Hide resolved
assert len(r.hrandfield('key', 2)) == 2
assert len(r.hrandfield('key', 2, True)) == 4 # with values
assert len(r.hrandfield('key', 10)) == 5 # without duplications
assert len(r.hrandfield('key', -10)) == 10 # with duplications

def test_randomkey(self, r):
assert r.randomkey() is None
for key in ('a', 'b', 'c'):
Expand Down