How to perform difference of set values- Redis SDIFF | SDIFFSTORE

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to perform the difference operation on two or more sets value stored in redis datastore, by using redis SDIFF and SDIFFSTORE command.

Difference of Sets:

In set theory, the difference of two sets A and B, written as A – B is a set which contains all elements of set A that are not in set B. For example :

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

Difference of A & B  :-
A - B = {1, 2, 3}

Python Set Difference

SDIFF Command :-

This command perform the difference 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 SDIFF command is as follows :-

Syntax :-

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

Output :-

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

Example :-

Redis SDIFF

SDIFFSTORE Command :-

This command perform the difference 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 SDIFFSTORE command is as follows :-

Syntax :-

redis host:post> SDIFFSTORE <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 SDIFFSTORE

References :-

  1. SDIFF Command Docs
  2. SDIFFSTORE Command Docs

That’s all for how to perform the difference 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.