Skip to content

Commit e706445

Browse files
zrandmember (#1519)
1 parent 01b96db commit e706445

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
@@ -2965,6 +2965,28 @@ def zpopmin(self, name, count=None):
29652965
}
29662966
return self.execute_command('ZPOPMIN', name, *args, **options)
29672967

2968+
def zrandmember(self, key, count=None, withscores=False):
2969+
"""
2970+
Return a random element from the sorted set value stored at key.
2971+
2972+
``count`` if the argument is positive, return an array of distinct
2973+
fields. If called with a negative count, the behavior changes and
2974+
the command is allowed to return the same field multiple times.
2975+
In this case, the number of returned fields is the absolute value
2976+
of the specified count.
2977+
2978+
``withscores`` The optional WITHSCORES modifier changes the reply so it
2979+
includes the respective scores of the randomly selected elements from
2980+
the sorted set.
2981+
"""
2982+
params = []
2983+
if count is not None:
2984+
params.append(count)
2985+
if withscores:
2986+
params.append("WITHSCORES")
2987+
2988+
return self.execute_command("ZRANDMEMBER", key, *params)
2989+
29682990
def bzpopmax(self, keys, timeout=0):
29692991
"""
29702992
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
@@ -1537,6 +1537,18 @@ def test_zpopmin(self, r):
15371537
assert r.zpopmin('a', count=2) == \
15381538
[(b'a2', 2), (b'a3', 3)]
15391539

1540+
@skip_if_server_version_lt('6.2.0')
1541+
def test_zrandemember(self, r):
1542+
r.zadd('a', {'a1': 1, 'a2': 2, 'a3': 3, 'a4': 4, 'a5': 5})
1543+
assert r.zrandmember('a') is not None
1544+
assert len(r.zrandmember('a', 2)) == 2
1545+
# with scores
1546+
assert len(r.zrandmember('a', 2, True)) == 4
1547+
# without duplications
1548+
assert len(r.zrandmember('a', 10)) == 5
1549+
# with duplications
1550+
assert len(r.zrandmember('a', -10)) == 10
1551+
15401552
@skip_if_server_version_lt('4.9.0')
15411553
def test_bzpopmax(self, r):
15421554
r.zadd('a', {'a1': 1, 'a2': 2})

0 commit comments

Comments
 (0)