diff options
| author | Avital Fine <79420960+AvitalFineRedis@users.noreply.github.com> | 2021-07-25 10:19:53 +0300 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-07-25 10:19:53 +0300 |
| commit | e7064450791b1cb20e1ff94f03385b2d02bb9ec7 (patch) | |
| tree | 36106389f52ba0183d774b1b2c416d3ff3ff7c83 | |
| parent | 01b96db203a651ff82598ad66685e487b74b8aac (diff) | |
| download | redis-py-e7064450791b1cb20e1ff94f03385b2d02bb9ec7.tar.gz | |
zrandmember (#1519)
| -rwxr-xr-x | redis/client.py | 22 | ||||
| -rw-r--r-- | tests/test_commands.py | 12 |
2 files changed, 34 insertions, 0 deletions
diff --git a/redis/client.py b/redis/client.py index fe6299f..160f495 100755 --- a/redis/client.py +++ b/redis/client.py @@ -2965,6 +2965,28 @@ class Redis: } return self.execute_command('ZPOPMIN', name, *args, **options) + def zrandmember(self, key, count=None, withscores=False): + """ + Return a random element from the sorted set 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. + + ``withscores`` The optional WITHSCORES modifier changes the reply so it + includes the respective scores of the randomly selected elements from + the sorted set. + """ + params = [] + if count is not None: + params.append(count) + if withscores: + params.append("WITHSCORES") + + return self.execute_command("ZRANDMEMBER", key, *params) + def bzpopmax(self, keys, timeout=0): """ ZPOPMAX a value off of the first non-empty sorted set diff --git a/tests/test_commands.py b/tests/test_commands.py index b83fe8f..3f0a82f 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -1537,6 +1537,18 @@ class TestRedisCommands: assert r.zpopmin('a', count=2) == \ [(b'a2', 2), (b'a3', 3)] + @skip_if_server_version_lt('6.2.0') + def test_zrandemember(self, r): + r.zadd('a', {'a1': 1, 'a2': 2, 'a3': 3, 'a4': 4, 'a5': 5}) + assert r.zrandmember('a') is not None + assert len(r.zrandmember('a', 2)) == 2 + # with scores + assert len(r.zrandmember('a', 2, True)) == 4 + # without duplications + assert len(r.zrandmember('a', 10)) == 5 + # with duplications + assert len(r.zrandmember('a', -10)) == 10 + @skip_if_server_version_lt('4.9.0') def test_bzpopmax(self, r): r.zadd('a', {'a1': 1, 'a2': 2}) |
