/

Using Redis Sets

Using Redis Sets

Redis Sets have two main differences compared to lists: they are not ordered and they only hold each item once.

To create a set, use the command SADD <setkey> <value>. You can use the same command to add more items to the set. For example:

1
2
3
SADD names "Flavio"
SADD names "Roger"
SADD names "Tony" "Mark" "Jane"

To retrieve all the items in a set, use the command SMEMBERS <setkey>. You can also use the command SISMEMBER to check if a value is present in the set. For example:

1
SISMEMBER names "Flavio"

To determine the number of items in a set, use the command SCARD:

1
SCARD names

To get a random item from the set without removing it, use the command SRANDMEMBER. If you want to extract and remove an item from the set in a casual order, use the command SPOP. You can extract multiple items at once by specifying the number of items. For example:

1
2
SPOP names
SPOP names 2

To remove an item from a set by value, use the command SREM:

1
SREM names "Flavio"

To retrieve the items that are present in two different sets, excluding elements that are only included in one set, use the command SINTER. For example:

1
SINTER set1 set2

For a comprehensive list of set commands, refer to the Redis documentation.

tags: [“Redis”, “Sets”]