summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAvital Fine <79420960+AvitalFineRedis@users.noreply.github.com>2021-07-22 18:51:24 +0300
committerGitHub <noreply@github.com>2021-07-22 18:51:24 +0300
commit627db540acd1f1f36db88290d74cbcd75f6bda0c (patch)
treecefd359cf225baead43a7beaca78a5c8f84d4c33
parentad4779eb8200e47a7786f78ca915a246038602c3 (diff)
downloadredis-py-627db540acd1f1f36db88290d74cbcd75f6bda0c.tar.gz
hrandfield (#1513)
* hrandfield * use mapping in hset * skip if version not fit * remove empty line * flake8 comments * new line for each comment
-rwxr-xr-xredis/client.py20
-rw-r--r--tests/test_commands.py13
2 files changed, 33 insertions, 0 deletions
diff --git a/redis/client.py b/redis/client.py
index a838d87..57932b9 100755
--- a/redis/client.py
+++ b/redis/client.py
@@ -1879,6 +1879,26 @@ class Redis:
"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')
diff --git a/tests/test_commands.py b/tests/test_commands.py
index 9884035..27117e3 100644
--- a/tests/test_commands.py
+++ b/tests/test_commands.py
@@ -895,6 +895,19 @@ class TestRedisCommands:
"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
+ assert len(r.hrandfield('key', 2)) == 2
+ # with values
+ assert len(r.hrandfield('key', 2, True)) == 4
+ # without duplications
+ assert len(r.hrandfield('key', 10)) == 5
+ # with duplications
+ assert len(r.hrandfield('key', -10)) == 10
+
def test_randomkey(self, r):
assert r.randomkey() is None
for key in ('a', 'b', 'c'):