Skip to content

Commit 8c82e42

Browse files
Zunion (#1522)
* zinter * change options in _zaggregate * skip for previous versions * add client function * validate the aggregate value * change options to get * add more aggregate tests * add weights guidance
1 parent 161774b commit 8c82e42

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

redis/client.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,7 @@ class Redis:
615615
lambda r: r and set(r) or set()
616616
),
617617
**string_keys_to_dict(
618-
'ZPOPMAX ZPOPMIN ZINTER ZDIFF ZRANGE ZRANGEBYSCORE '
618+
'ZPOPMAX ZPOPMIN ZINTER ZDIFF ZUNION ZRANGE ZRANGEBYSCORE '
619619
'ZREVRANGE ZREVRANGEBYSCORE', zset_score_pairs
620620
),
621621
**string_keys_to_dict('BZPOPMIN BZPOPMAX', \
@@ -3416,6 +3416,16 @@ def zscore(self, name, value):
34163416
"Return the score of element ``value`` in sorted set ``name``"
34173417
return self.execute_command('ZSCORE', name, value)
34183418

3419+
def zunion(self, keys, aggregate=None, withscores=False):
3420+
"""
3421+
Return the union of multiple sorted sets specified by ``keys``.
3422+
``keys`` can be provided as dictionary of keys and their weights.
3423+
Scores will be aggregated based on the ``aggregate``, or SUM if
3424+
none is provided.
3425+
"""
3426+
return self._zaggregate('ZUNION', None, keys, aggregate,
3427+
withscores=withscores)
3428+
34193429
def zunionstore(self, dest, keys, aggregate=None):
34203430
"""
34213431
Union multiple sorted sets specified by ``keys`` into

tests/test_commands.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1813,6 +1813,26 @@ def test_zscore(self, r):
18131813
assert r.zscore('a', 'a2') == 2.0
18141814
assert r.zscore('a', 'a4') is None
18151815

1816+
@skip_if_server_version_lt('6.2.0')
1817+
def test_zunion(self, r):
1818+
r.zadd('a', {'a1': 1, 'a2': 1, 'a3': 1})
1819+
r.zadd('b', {'a1': 2, 'a2': 2, 'a3': 2})
1820+
r.zadd('c', {'a1': 6, 'a3': 5, 'a4': 4})
1821+
# sum
1822+
assert r.zunion(['a', 'b', 'c']) == \
1823+
[b'a2', b'a4', b'a3', b'a1']
1824+
assert r.zunion(['a', 'b', 'c'], withscores=True) == \
1825+
[(b'a2', 3), (b'a4', 4), (b'a3', 8), (b'a1', 9)]
1826+
# max
1827+
assert r.zunion(['a', 'b', 'c'], aggregate='MAX', withscores=True)\
1828+
== [(b'a2', 2), (b'a4', 4), (b'a3', 5), (b'a1', 6)]
1829+
# min
1830+
assert r.zunion(['a', 'b', 'c'], aggregate='MIN', withscores=True)\
1831+
== [(b'a1', 1), (b'a2', 1), (b'a3', 1), (b'a4', 4)]
1832+
# with weight
1833+
assert r.zunion({'a': 1, 'b': 2, 'c': 3}, withscores=True)\
1834+
== [(b'a2', 5), (b'a4', 12), (b'a3', 20), (b'a1', 23)]
1835+
18161836
def test_zunionstore_sum(self, r):
18171837
r.zadd('a', {'a1': 1, 'a2': 1, 'a3': 1})
18181838
r.zadd('b', {'a1': 2, 'a2': 2, 'a3': 2})

0 commit comments

Comments
 (0)