Skip to content

Commit 02e7386

Browse files
AvitalFineRedischayim
authored andcommitted
zrandmember (redis#1519)
1 parent 6de60db commit 02e7386

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

redis/client.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2970,6 +2970,28 @@ def zpopmin(self, name, count=None):
29702970
}
29712971
return self.execute_command('ZPOPMIN', name, *args, **options)
29722972

2973+
def zrandmember(self, key, count=None, withscores=False):
2974+
"""
2975+
Return a random element from the sorted set value stored at key.
2976+
2977+
``count`` if the argument is positive, return an array of distinct
2978+
fields. If called with a negative count, the behavior changes and
2979+
the command is allowed to return the same field multiple times.
2980+
In this case, the number of returned fields is the absolute value
2981+
of the specified count.
2982+
2983+
``withscores`` The optional WITHSCORES modifier changes the reply so it
2984+
includes the respective scores of the randomly selected elements from
2985+
the sorted set.
2986+
"""
2987+
params = []
2988+
if count is not None:
2989+
params.append(count)
2990+
if withscores:
2991+
params.append("WITHSCORES")
2992+
2993+
return self.execute_command("ZRANDMEMBER", key, *params)
2994+
29732995
def bzpopmax(self, keys, timeout=0):
29742996
"""
29752997
ZPOPMAX a value off of the first non-empty sorted set

tests/test_commands.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1548,6 +1548,18 @@ def test_zpopmin(self, r):
15481548
assert r.zpopmin('a', count=2) == \
15491549
[(b'a2', 2), (b'a3', 3)]
15501550

1551+
@skip_if_server_version_lt('6.2.0')
1552+
def test_zrandemember(self, r):
1553+
r.zadd('a', {'a1': 1, 'a2': 2, 'a3': 3, 'a4': 4, 'a5': 5})
1554+
assert r.zrandmember('a') is not None
1555+
assert len(r.zrandmember('a', 2)) == 2
1556+
# with scores
1557+
assert len(r.zrandmember('a', 2, True)) == 4
1558+
# without duplications
1559+
assert len(r.zrandmember('a', 10)) == 5
1560+
# with duplications
1561+
assert len(r.zrandmember('a', -10)) == 10
1562+
15511563
@skip_if_server_version_lt('4.9.0')
15521564
def test_bzpopmax(self, r):
15531565
r.zadd('a', {'a1': 1, 'a2': 2})

0 commit comments

Comments
 (0)