Skip to content

Zunion #1522

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

Merged
merged 21 commits into from
Aug 15, 2021
Merged

Zunion #1522

Show file tree
Hide file tree
Changes from all 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
12 changes: 11 additions & 1 deletion redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,7 +595,7 @@ class Redis:
lambda r: r and set(r) or set()
),
**string_keys_to_dict(
'ZPOPMAX ZPOPMIN ZINTER ZDIFF ZRANGE ZRANGEBYSCORE '
'ZPOPMAX ZPOPMIN ZINTER ZDIFF ZUNION ZRANGE ZRANGEBYSCORE '
'ZREVRANGE ZREVRANGEBYSCORE', zset_score_pairs
),
**string_keys_to_dict('BZPOPMIN BZPOPMAX', \
Expand Down Expand Up @@ -3262,6 +3262,16 @@ def zscore(self, name, value):
"Return the score of element ``value`` in sorted set ``name``"
return self.execute_command('ZSCORE', name, value)

def zunion(self, keys, aggregate=None, withscores=False):
"""
Return the union of multiple sorted sets specified by ``keys``.
``keys`` can be provided as dictionary of keys and their weights.
Scores will be aggregated based on the ``aggregate``, or SUM if
none is provided.
"""
return self._zaggregate('ZUNION', None, keys, aggregate,
withscores=withscores)

def zunionstore(self, dest, keys, aggregate=None):
"""
Union multiple sorted sets specified by ``keys`` into
Expand Down
20 changes: 20 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -1775,6 +1775,26 @@ def test_zscore(self, r):
assert r.zscore('a', 'a2') == 2.0
assert r.zscore('a', 'a4') is None

@skip_if_server_version_lt('6.2.0')
def test_zunion(self, r):
r.zadd('a', {'a1': 1, 'a2': 1, 'a3': 1})
r.zadd('b', {'a1': 2, 'a2': 2, 'a3': 2})
r.zadd('c', {'a1': 6, 'a3': 5, 'a4': 4})
# sum
assert r.zunion(['a', 'b', 'c']) == \
[b'a2', b'a4', b'a3', b'a1']
assert r.zunion(['a', 'b', 'c'], withscores=True) == \
[(b'a2', 3), (b'a4', 4), (b'a3', 8), (b'a1', 9)]
# max
assert r.zunion(['a', 'b', 'c'], aggregate='MAX', withscores=True)\
== [(b'a2', 2), (b'a4', 4), (b'a3', 5), (b'a1', 6)]
# min
assert r.zunion(['a', 'b', 'c'], aggregate='MIN', withscores=True)\
== [(b'a1', 1), (b'a2', 1), (b'a3', 1), (b'a4', 4)]
# with weight
assert r.zunion({'a': 1, 'b': 2, 'c': 3}, withscores=True)\
== [(b'a2', 5), (b'a4', 12), (b'a3', 20), (b'a1', 23)]

def test_zunionstore_sum(self, r):
r.zadd('a', {'a1': 1, 'a2': 1, 'a3': 1})
r.zadd('b', {'a1': 2, 'a2': 2, 'a3': 2})
Expand Down