0
0
Redisquery~5 mins

SADD and SREM for membership in Redis

Choose your learning style9 modes available
Introduction
SADD adds items to a group without duplicates. SREM removes items from that group. This helps keep track of unique members easily.
When you want to keep a list of unique users who liked a post.
When you need to add or remove tags from a set of tags for an article.
When tracking online users joining or leaving a chat room.
When managing a list of unique product IDs in a shopping cart.
Syntax
Redis
SADD key member [member ...]
SREM key member [member ...]
SADD adds one or more members to the set stored at key.
SREM removes one or more members from the set stored at key.
Examples
Adds 'apple', 'banana', and 'cherry' to the set named 'myset'.
Redis
SADD myset apple banana cherry
Removes 'banana' from the set named 'myset'.
Redis
SREM myset banana
Adds two users to the 'users' set.
Redis
SADD users online_user1 online_user2
Removes 'online_user1' from the 'users' set.
Redis
SREM users online_user1
Sample Program
First, add three fruits to the set 'fruits'. Then remove 'banana'. Finally, get all members of 'fruits'.
Redis
SADD fruits apple banana cherry
SREM fruits banana
SMEMBERS fruits
OutputSuccess
Important Notes
SADD returns the number of elements actually added (ignores duplicates).
SREM returns the number of elements actually removed (ignores missing members).
Sets in Redis do not allow duplicate members.
Summary
Use SADD to add unique members to a set.
Use SREM to remove members from a set.
Sets help manage collections of unique items efficiently.