Set
One of the key characteristics of a set is that it does not allow duplicate values. When you add a new element to a set, if the element already exists, it won't be added again.
Sets are commonly used for storing unique values, such as user IDs, IP addresses, or any other data where duplicates must be avoided.
Practical Use of Sets in Redis
- , opens subtitles settings dialogsubtitles settings
- subtitles off
- , selectedEnglish Captions
- 2x
- 1.5x
- , selected1x
- 0.5x
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Basic Commands for Working with Sets
Redis sets come with several commands that make it easy to add, remove, and check elements
Adding and Removing Elements
The SADD
command adds elements to a set, ignoring duplicates, and the SREM
command removes elements from a set.
912SADD users "user1" "user2" # adds "user1" and "user2" to the users setSREM users "user1" # removes "user1" from the users set
Checking for an Element and Retrieving All Elements
To check if a specific element is in a set, use the SISMEMBER
command, which returns 1 if the element is present and 0 if it's not. To get all elements of the set, use the SMEMBERS
command.
912SISMEMBER users "user2" # checks if "user2" is in the users set (returns 1 or 0)SMEMBERS users # returns all elements of the users set
Getting Information About the Set
To get the number of elements in a set, use the SCARD
command, which returns the number of elements in the set.
SCARD users # returns the number of elements in the users set
Operations with Multiple Sets
When working with multiple sets, you can use the commands SDIFF
, SINTER
, and SUNION
— SDIFF
returns elements that are in one set but not in the others, SINTER
finds common elements across all specified sets, and SUNION
returns the union of all elements from multiple sets.
9123SDIFF set1 set2 # returns elements that are in `set1` but not in `set2`SINTER set1 set2 # returns common elements between `set1` and `set2`SUNION set1 set2 # returns the union of elements from `set1` and `set2`
1. What does the SADD
command do in Redis?
2. Which command should you use to retrieve all elements from a set?
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.