This article will go over how to create and manage SETS in Redis.
Redis Create Set
To create a Redis Set, we use the SADD command followed by the key name and the list members.
The syntax is as shown below:
Take the example command shown below:
(integer) 5
The command will add the specified elements to the list and return the successful adds.
Keep in mind that type matters. For example, adding a set member to a list type returns an error.
An example is as shown:
(integer) 1
127.0.0.1:6379> SADD list_key FaunaDB
(error) WRONGTYPE Operation against a key holding the wrong kind of value
We attempt to add a member to a list in the command above.
As mentioned, a set cannot contain duplicate values. Hence, if you specify the same member multiple times, Redis will select the first occurrence and ignores the others.
An example is as shown:
(integer) 2
You will notice that Redis adds the first two elements only.
Redis Get Set Members
To get the members of a set, use the SMEMBERS command. An example is as shown:
1) "MySQL"
2) "Memcached"
3) "PostgreSQL"
4) "Oracle"
5) "MongoDB"
6) "Redis"
7) "ETCD"
You can check if a specific member is part of the list using the SISMEMBER command.
The command takes the key and the member to check as the arguments. An example is as shown below:
(integer) 1
If the member is part of the set, the command returns 1 and 0 otherwise.
You can also retrieve any random member from a set using the SRANDMEMBER command:
"ETCD"
If not specified, the command will return one random member.
You can specify the number of random members to get as:
1) "MySQL"
2) "Memcached"
3) "PostgreSQL"
4) "Oracle"
5) "Redis"
This should return five random set members.
Redis Remove Set Members
To remove a specific member from a set, use the SREM command. For example:
(integer) 1
Redis also allows you to remove a random member from a set using the SPOP command.
Example usage is as shown:
"Memcached"
The spop command will remove one random member from the specified set unless specified.
You can also specify how many random members to remove as shown:
1) "PostgreSQL"
2) "Oracle"
3) "Redis"
The SPOP command returns the values of the members that it deletes.
Conclusion
In this article, we cover the fundamentals of working with Redis sets. In addition, we cover commands such as SADD, SPOP, SREM, SISMEMBER, and many more.
Stay tuned for more!