SADD, SREM and SMEMBERS
Wordcraft awards badges: first win, a three-game streak, a speedy round. A player either has a badge or does not, earning it twice changes nothing, and the order they were earned in does not matter on the badge shelf. That is a set.
The rule
A set holds each member once, in no particular order.
A set is an unordered collection of unique strings. Adding a member that is already there does nothing.
127.0.0.1:6379> SADD badges:asha first-win streak-3
(integer) 2
127.0.0.1:6379> SADD badges:asha streak-3 speedster
(integer) 1
127.0.0.1:6379> SMEMBERS badges:asha
1) "streak-3"
2) "first-win"
3) "speedster"
127.0.0.1:6379> SREM badges:asha speedster night-owl
(integer) 1
127.0.0.1:6379> SMEMBERS badges:nobody
(empty array)SADD key member [member ...]creates the set if needed and replies with how many members were new. Above,streak-3was already there, so onlyspeedstercounted.SREM key member [member ...]replies with how many members were really removed.night-owlwas never there.SMEMBERS keyreturns every member. The order is not guaranteed and can differ from the order you added them; sort in your app if you need a fixed order.- Like hashes and lists, an empty set is deleted automatically.
Typical uses:
- Tags and categories:
tags:word:orbitholdsspace,science. - Unique visitors:
SADD visitors:2026-09-25 ashaon every visit; duplicates collapse, so the set size is the number of distinct visitors. - Relationships:
friends:asha,blocked:ravi, the members of a chat room. - Deduplication: "has this email already been sent?"
SMEMBERS returns the whole set in one reply. That is fine for a handful of badges, but for a set with millions of members use SSCAN, which walks through it in small batches.
The shortcut
For SADD and SREM replies, tick only the members that change the set: an SADD of something already present, or an SREM of something absent, scores zero.
SADD badges:ravi first-win
Empty set, so first-win is new. Reply
(integer) 1.
Drills
Answer fast — trust the rule.
tags:word:orbit does not exist. What does SADD tags:word:orbit space science space reply?
badges:asha holds first-win and streak-3. What does SREM badges:asha streak-3 speedster reply?
You add a, then b, then c to a set. What can you say about the order SMEMBERS returns?
Asha visits 5 times, Ravi 2 times and Tom once, each doing SADD visitors:today <name>. How many members does the set have?
Remember
- A set holds each member once, in no particular order.
- Count only the members that change the set: repeats and absentees score zero.
- Sets fit tags, unique visitors, relationships and deduplication.
