Redis ZINTERCARD in Python (Detailed Guide w/ Code Examples)

Use Case(s)

The ZINTERCARD command in Redis is used to compute the cardinality of the intersection of multiple sorted sets without actually returning the elements. This is particularly useful when you need to know how many common elements exist between different sorted sets, for instance, in scenarios involving recommendation systems or social networks where you want to find overlaps in user interests or connections.

Code Examples

In this section, we will look at how to use the ZINTERCARD command with Python's redis-py client.

Example 1: Basic Usage of ZINTERCARD

Here, we'll calculate the cardinality of the intersection of two sorted sets.

import redis # Connect to a local Redis instance r = redis.Redis(host='localhost', port=6379, db=0) # Adding some elements to two sorted sets r.zadd('sorted_set_1', {'a': 1, 'b': 2, 'c': 3}) r.zadd('sorted_set_2', {'b': 2, 'c': 4, 'd': 5}) # Using ZINTERCARD to find the intersection cardinality intersection_cardinality = r.execute_command('ZINTERCARD', 2, 'sorted_set_1', 'sorted_set_2') print(f"The cardinality of the intersection is: {intersection_cardinality}")

In this example, the intersection includes the elements 'b' and 'c' which are common to both sorted sets, so the output should be 2.

Example 2: Specifying Weights and Aggregates

You can also specify weights for each set to influence the score of elements during intersection calculation, and define an aggregation method.

# Using weights and aggregate option with ZINTERCARD intersection_cardinality = r.execute_command('ZINTERCARD', 2, 'sorted_set_1', 'sorted_set_2', 'WEIGHTS', 1, 2, 'AGGREGATE', 'SUM') print(f"The cardinality of the weighted intersection is: {intersection_cardinality}")

This example calculates the intersection size considering weights for scores and summing them up. The actual elements still don't change, so the cardinality remains 2.

Best Practices

  • Use wisely in production: Frequent use of ZINTERCARD on large sorted sets can be resource-intensive. Always evaluate performance impacts.
  • Combine with other commands: Sometimes combining ZINTERCARD with other commands like ZINTERSTORE might be necessary if you need the resulting set after knowing its cardinality.

Common Mistakes

  • Overlooking return value: Users sometimes confuse ZINTERCARD with ZINTER, expecting it to return the intersected set elements rather than just their cardinality.


Q: What version of Redis supports ZINTERCARD? A: ZINTERCARD is a relatively new command introduced in Redis 6.2. Ensure your Redis server is updated to this version or newer to use ZINTERCARD.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.