What are sets in Redis?

A Redis Set is a data structure that is available in Redis and is essentially a collection of strings with the below properties:

  1. each string is unique and occurs only once in a Set
  2. the strings are unordered and Redis can return the elements in any order at every call

Conceptually, it is similar to the HashSet functionality available in Java or C#.

Create a Redis Set

Let’s create a Redis set named Months using the SADD command and store the name of the first four months to it:

> SADD Months January February March April
(integer) 4

View members

Set members can be viewed using the SMEMBERS command:

> SMEMBERS Months
1) "April"
2) "March"
3) "February"
4) "January"
Visual Representation of a Redis Set

Remove a member

To remove a member from the set, we can use the SREM command:

> SREM Months April
1
> SMEMBERS Months
1) "March"
2) "February"
3) "January"

Check membership

The SISMEMBER command can be used to check the membership in the set. Here, January exists in the set, but December does not:

> SISMEMBER Months January
(integer) 1
> SISMEMBER Months December
(integer) 0

More on Redis Set

A Redis Set is a very efficient data structure: operations like adding a member, deleting a member, or checking if a member exists in the Set can be done in constant time or O(1).

Apart from these basic operations, Sets offer very powerful operations like unionsSUNION, intersectionsSINTER, differenceSDIFF, extracting a random elementSPOP, etc.

Redis Sets allow the storage of a maximum of $2^{32} - 1$(more than 4 billion) members per set.

Redis Sets are used to solve various use cases, like counting unique visitors using IP addresses, session caching, and analyzing customer behavior in online stores (to name a few).

Free Resources