Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Sets in Redis

Introduction

In Redis, a set is an unordered collection of unique strings. It is a powerful data structure that allows you to store multiple values in a single key without any duplicates. Sets provide a range of operations like adding, removing, and testing for the existence of members, as well as performing set operations such as union, intersection, and difference.

Creating and Adding Members to a Set

The SADD command is used to add one or more members to a set. If a specified member already exists, it is ignored.

SADD myset "apple" "banana" "cherry"
(integer) 3

Retrieving Members of a Set

The SMEMBERS command is used to get all the members in a set.

SMEMBERS myset
1) "apple"
2) "banana"
3) "cherry"

Checking Existence of a Member

The SISMEMBER command checks if a given value is a member of a set. It returns 1 if the value is a member, and 0 if it is not.

SISMEMBER myset "banana"
(integer) 1

Removing Members from a Set

The SREM command is used to remove one or more members from a set. Non-existing members are ignored.

SREM myset "banana"
(integer) 1

After removing "banana":

SMEMBERS myset
1) "apple"
2) "cherry"

Set Operations

Union

The SUNION command returns the union of the given sets.

SADD set1 "a" "b" "c"
SADD set2 "c" "d" "e"
SUNION set1 set2
1) "a"
2) "b"
3) "c"
4) "d"
5) "e"

Intersection

The SINTER command returns the intersection of the given sets.

SINTER set1 set2
1) "c"

Difference

The SDIFF command returns the difference between the first set and all the successive sets.

SDIFF set1 set2
1) "a"
2) "b"

Conclusion

Sets in Redis are a versatile and efficient data structure used to store unique elements. They provide various operations such as adding, removing, and checking for the existence of elements, as well as performing complex set operations like union, intersection, and difference. Understanding how to use sets can significantly enhance the performance and scalability of your Redis-based applications.