Skip to content

zinter #1520

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 10 commits into from
Aug 1, 2021
Merged

zinter #1520

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
46 changes: 36 additions & 10 deletions redis/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,8 +595,8 @@ class Redis:
lambda r: r and set(r) or set()
),
**string_keys_to_dict(
'ZPOPMAX ZPOPMIN ZDIFF ZRANGE ZRANGEBYSCORE ZREVRANGE '
'ZREVRANGEBYSCORE', zset_score_pairs
'ZPOPMAX ZPOPMIN ZINTER ZDIFF ZRANGE ZRANGEBYSCORE '
'ZREVRANGE ZREVRANGEBYSCORE', zset_score_pairs
),
**string_keys_to_dict('BZPOPMIN BZPOPMAX', \
lambda r:
Expand Down Expand Up @@ -2954,11 +2954,28 @@ def zincrby(self, name, amount, value):
"Increment the score of ``value`` in sorted set ``name`` by ``amount``"
return self.execute_command('ZINCRBY', name, amount, value)

def zinter(self, keys, aggregate=None, withscores=False):
"""
Return the intersect of multiple sorted sets specified by ``keys``.
With the ``aggregate`` option, it is possible to specify how the
results of the union are aggregated. This option defaults to SUM,
where the score of an element is summed across the inputs where it
exists. When this option is set to either MIN or MAX, the resulting
set will contain the minimum or maximum score of an element across
the inputs where it exists.
"""
return self._zaggregate('ZINTER', None, keys, aggregate,
withscores=withscores)

def zinterstore(self, dest, keys, aggregate=None):
"""
Intersect multiple sorted sets specified by ``keys`` into
a new sorted set, ``dest``. Scores in the destination will be
aggregated based on the ``aggregate``, or SUM if none is provided.
Intersect multiple sorted sets specified by ``keys`` into a new
sorted set, ``dest``. Scores in the destination will be aggregated
based on the ``aggregate``. This option defaults to SUM, where the
score of an element is summed across the inputs where it exists.
When this option is set to either MIN or MAX, the resulting set will
contain the minimum or maximum score of an element across the inputs
where it exists.
"""
return self._zaggregate('ZINTERSTORE', dest, keys, aggregate)

Expand Down Expand Up @@ -3248,8 +3265,12 @@ def zunionstore(self, dest, keys, aggregate=None):
"""
return self._zaggregate('ZUNIONSTORE', dest, keys, aggregate)

def _zaggregate(self, command, dest, keys, aggregate=None):
pieces = [command, dest, len(keys)]
def _zaggregate(self, command, dest, keys, aggregate=None,
**options):
pieces = [command]
if dest is not None:
pieces.append(dest)
pieces.append(len(keys))
if isinstance(keys, dict):
keys, weights = keys.keys(), keys.values()
else:
Expand All @@ -3259,9 +3280,14 @@ def _zaggregate(self, command, dest, keys, aggregate=None):
pieces.append(b'WEIGHTS')
pieces.extend(weights)
if aggregate:
pieces.append(b'AGGREGATE')
pieces.append(aggregate)
return self.execute_command(*pieces)
if aggregate.upper() in ['SUM', 'MIN', 'MAX']:
pieces.append(b'AGGREGATE')
pieces.append(aggregate)
else:
raise DataError("aggregate can be sum, min or max.")
if options.get('withscores', False):
pieces.append(b'WITHSCORES')
return self.execute_command(*pieces, **options)

# HYPERLOGLOG COMMANDS
def pfadd(self, name, *values):
Expand Down
22 changes: 22 additions & 0 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -1519,6 +1519,28 @@ def test_zlexcount(self, r):
assert r.zlexcount('a', '-', '+') == 7
assert r.zlexcount('a', '[b', '[f') == 5

@skip_if_server_version_lt('6.2.0')
def test_zinter(self, r):
r.zadd('a', {'a1': 1, 'a2': 2, 'a3': 1})
r.zadd('b', {'a1': 2, 'a2': 2, 'a3': 2})
r.zadd('c', {'a1': 6, 'a3': 5, 'a4': 4})
assert r.zinter(['a', 'b', 'c']) == [b'a3', b'a1']
# invalid aggregation
with pytest.raises(exceptions.DataError):
r.zinter(['a', 'b', 'c'], aggregate='foo', withscores=True)
# aggregate with SUM
assert r.zinter(['a', 'b', 'c'], withscores=True) \
== [(b'a3', 8), (b'a1', 9)]
# aggregate with MAX
assert r.zinter(['a', 'b', 'c'], aggregate='MAX', withscores=True) \
== [(b'a3', 5), (b'a1', 6)]
# aggregate with MIN
assert r.zinter(['a', 'b', 'c'], aggregate='MIN', withscores=True) \
== [(b'a1', 1), (b'a3', 1)]
# with weights
assert r.zinter({'a': 1, 'b': 2, 'c': 3}, withscores=True) \
== [(b'a3', 20), (b'a1', 23)]

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