In this tutorial, we will learn about how to perform the union operation on two or more sorted sets value stored in redis datastore, by using redis ZUNIONSTORE command.
Union of Sets:
In set theory, the union of two or more sets is the set which contains all the elements ( distinct ) present in all the sets. For example :
A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8, 9} Union of A & B :- A U B = {1, 2, 3, 4, 5, 6, 7, 8, 9}
ZUNIONSTORE Command :-
This command perform the union 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 ZUNIONSTORE command is as follows :-
Syntax :-
redis host:post> ZUNIONSTORE <destination> numkeys <keyName> [<keyName>] [WEIGHTS weight [weight]] [AGGREGATE SUM|MIN|MAX]
Output :-
- (array) reply, containing elements resulting from the union 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 union 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 union 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 :-
References :-
- ZUNIONSTORE Command Docs
That’s all for how to perform the union 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.