Redis ZINTERSTORE – How to perform intersection of sorted set values

3 weeks ago Lalit Bhagtani 0

In this tutorial, we will learn about how to perform the intersection operation on two or more sorted sets value stored in redis datastore, by using redis ZINTERSTORE command.

Intersection of Sets:

In set theory, the intersection of two or more sets is the set which contains the elements that are common to all the sets. For example :

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8, 9}

Intersection of A & B :-
A ∩ B = {4, 5}

Python Set Intersection

ZINTERSTORE Command :-

This command perform the intersection operation of two or more specified sorted sets and returns a new sorted set value stored at the specified key. A non existent sorted set is considered as an empty sorted set. Error is returned, if key exist but value stored at the key is not a sorted set. The syntax of redis ZINTERSTORE command is as follows :-

Syntax :-

redis host:post> ZINTERSTORE <destination> numkeys <keyName> [<keyName>] [WEIGHTS weight [weight]] [AGGREGATE SUM|MIN|MAX]

Output :-

- (array) reply, containing elements resulting from the intersection operation.
- Error, if key exist and value stored at the key is not a sorted set.

numkeys are the number of input keys containing sorted set values on which intersection operation is performed. It is mandatory to pass numkeys argument before passing input keys and other arguments. Result is stored in a new sorted set at destination key. If destination key already exists, then it is overwritten.

WEIGHTS option can be used to specify multiplication factor for each input sorted set. This means that the score of every element in all the input sorted set is multiplied by this factor before being passed to the aggregation function. When WEIGHTS is not passed, the multiplication factors is taken as 1.

AGGREGATE option can be used to specify how the results of the intersection are aggregated. Its default value is SUM, which means that the score of an element is summed across all the input sorted sets 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 input sorted sets where it exists.

Example :-

Redis ZINTERSTORE

References :-

  1. ZINTERSTORE Command Docs

That’s all for how to perform the intersection operation on two or more sorted sets value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.