Redis is a popular open-source, Key-value type storage. In this blog, we will learn how to work with set in redis.
Redis set type
Redis set is an unordered collection of unique strings. In Redis, sets also do not allow the repetition of values in a key. In redis, we can perform many operations on sets like creating sets, retrieving data from sets, removing members from sets, etc.
Redis set command
In redis there any many sets of commands which a user can use to perform various operations. Below are the few SET commands present in redis.
SADD
SREM
SISMEMBER
SINTER
SINTER
Redis set examples
In this session, we will understand how to effectively use various set commands in redis.
Creating Sets in redis
Using the SADD command a user can add a new member to the set. The syntax for the SADD command follows below the pattern.
SADD key member [member ...]
Let’s insert the key using the SADD command to insert 3 values in the set key
sadd key_1 value_1_1 value_1_2 value_1_3
Redis set get all members
Using smembers command we can retrieve all members from a set in redis.The syntax for smembers command follows the below pattern.
smembers key
Now let’s retrieve all keys present in key_1 member
smembers key_1
Removes a member from the set in redis
Redis also provides a facility to remove a particular member from a set using the SREM command. The syntax for the SREM command follows the below pattern.
SREM key member [member ...]
Let’s use the above command to remove member value_1_1 from key_1.
SREM key_1 value_1_1
Check the size of a set in redis
Using the redis SCARD command, a user can retrieve the number of elements of a set stored in a key
.Let’s retrieve the elements present in key_1.
SCARD key_1
Comparing Sets in redis
Redis also provides us the facility to compare various sets and return the interaction using the SINTER command. The SINTER command follows the below pattern.
SINTER key [key ...]
Below is a simple illustration of SINTER functionality.
key_1 = {p,q,r}
key_2 = {q}
key_3 = {p,q,s}
SINTER key_1 key_2 key_3 = {q}
Redis set python
A user can also use python to retrieve the sets stored in a redis instance. You can follow my tutorial on Redis python to configure a redis python instance in your environment.
Below is the code snipped to retrieve the members from key_1
import redis
r = redis.StrictRedis(host='localhost',port=6379, db=0)
r.smembers(key_1))
Conclusion
I hope you have liked this small tutorial on how to work with the set in redis. please do let me know if you are facing any issues while following along.