How to perform union of set values – Redis SUNION | SUNIONSTORE

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to perform the union operation on two or more sets value stored in redis datastore, by using redis SUNION and SUNIONSTORE 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}

Python Set Union

SUNION Command :-

This command perform the union operation on two or more specified sets and returns the result as an array. If any of the specified key doesn’t exist, then it will considered as an empty set. Error will be returned, if key exist but value stored at the key is not a set. The syntax of redis SUNION command is as follows :-

Syntax :-

redis host:post> SUNION <keyName 1> <keyName 2> <keyName 3>

Output :-

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

Example :-

Redis SUNION

SUNIONSTORE Command :-

This command perform the union operation on two or more specified sets and returns a new set value stored at the specified key. If any of the specified key doesn’t exist, then it will considered as an empty set. Error will be returned, if key exist but value stored at the key is not a set. The syntax of redis SUNIONSTORE command is as follows :-

Syntax :-

redis host:post> SUNIONSTORE <destination keyName> <keyName 1> <keyName 2> <keyName 3>

Output :-

- (integer) representing number of elements in the destination set.
- Error, if key exist and value stored at the key is not a set.

Example :-

Redis SUNIONSTORE

References :-

  1. SUNION Command Docs
  2. SUNIONSTORE Command Docs

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