Skip to content
This repository has been archived by the owner on Feb 21, 2023. It is now read-only.

Commit

Permalink
Browse files Browse the repository at this point in the history
Zunion (redis/redis-py#1512)

Signed-off-by: Andrew-Chen-Wang <acwangpython@gmail.com>
  • Loading branch information
Andrew-Chen-Wang committed Oct 5, 2021
1 parent 3bef54d commit b6c8416
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
17 changes: 16 additions & 1 deletion aioredis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ class Redis:
"SDIFF SINTER SMEMBERS SUNION", lambda r: r and set(r) or set()
),
**string_keys_to_dict(
"ZPOPMAX ZPOPMIN ZINTER ZDIFF ZRANGE ZRANGEBYSCORE ZREVRANGE "
"ZPOPMAX ZPOPMIN ZINTER ZDIFF ZUNION ZRANGE ZRANGEBYSCORE ZREVRANGE "
"ZREVRANGEBYSCORE",
zset_score_pairs,
),
Expand Down Expand Up @@ -3786,6 +3786,21 @@ def zscore(self, name: str, value: EncodableT) -> Awaitable:
"""Return the score of element ``value`` in sorted set ``name``"""
return self.execute_command("ZSCORE", name, value)

def zunion(
self,
keys: Union[Sequence[KeyT], Mapping[AnyKeyT, float]],
aggregate: Optional[str] = None,
withscores: bool = False
) -> Awaitable:
"""
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: KeyT,
Expand Down
20 changes: 20 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -1898,6 +1898,26 @@ async def test_zscore(self, r: aioredis.Redis):
assert await r.zscore("a", "a2") == 2.0
assert await r.zscore("a", "a4") is None

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

async def test_zunionstore_sum(self, r: aioredis.Redis):
await r.zadd("a", {"a1": 1, "a2": 1, "a3": 1})
await r.zadd("b", {"a1": 2, "a2": 2, "a3": 2})
Expand Down

0 comments on commit b6c8416

Please sign in to comment.