Redis - Sets
Sets in Redis are unordered, unique collection of strings. The same value can only exist once inside the set. The sets contain some additional commands, like for example to check if the given element exists in the set.
Adding Elements to a Set (SADD)
The SADD command can be used to add item(s) to a set. Learn more
Time Complexity: O(1) for each element added. O(N) if adding multiple elements.
Example usage:
Getting Values of a Set (SSCAN)
SMEMBERS
The SMEMBERS command was used in the past for listing the values. It is no longer recommended to use the SMEMBERS command, as it blocks the whole database operation until it outputs the data and can cause massive problems in production environments with lots of data (it's slow and takes large amount of memory with large dataset). Use SSCAN instead.
The command SSCAN works like the SCAN, thus it can be used to list all values of a set. It can take in the MATCH (filter) and COUNT (how many results to return) parameters for further customization. Learn more
Time Complexity: O(1) for the call. O(N) where N is the number of elements in the specified set collection.
Example usage:
Defaults to 10
By default, when not passing the COUNT parameter, it will list approximately 10 values.
Hint, or requirement
Note that the COUNT parameter can return more or less keys than specified. The COUNT is merely a recommendation for Redis and it can return back different amount of elements that you wanted it to, but it tries to be very close to the specified value.
Removing Elements from a Set (SREM and SPOP)
The SREM and SPOP commands can be used to remove elements from a list.
The SREM command accepts the name of the element to be removed as an parameter.
The SPOP command removes and returns back a random element from the list.
Time Complexity: O(1) for single element removal. O(N) otherwise where N denotes the amount of elements.
Example usage:
Amount of Elements in a Set (SCARD)
The SCARD command can be used to view the amount of elements in a set. Learn more
Time Complexity: O(1)
Example usage:
Checking if Element Exists in a Set (SISMEMBER)
The SISMEMBER command can be used to check if the given element exists in a set. Learn more
Time Complexity: O(1)
Usage Example of Sets
In an example where you would have an online store where products are categorized, you could use this kind of data structure to set products IDs into categories:
And to easily determine if some product ID can be found in the category, the command SISMEMBER can be used:
And to determine all products that belong to category #1 and the amount of products belonging to the category, the commands SMEMBERS and SCARD can be used: