Skip to the workspace
Pebellslearn by building
Sets  ›  Lesson

SISMEMBER and SCARD

SISMEMBER 12 minSISMEMBER answers 1 or 0 for whether one value is in a set, SMISMEMBER checks several at once, and SCARD counts members without returning them.

redis / SISMEMBER and SCARD

Explore each scene at your own pace.

01 · The rule

The rule

SISMEMBER and SCARD

Every time a Wordcraft player guesses a word, the game must check "has this word already been guessed today?" and the lobby shows "1,284 players online". Neither needs the full list of members. Sets can answer yes-or-no and how-many directly, however large they grow.

The rule

Ask the set a question; don't fetch the set to answer it.

badges:asha holds first-win, streak-3 and speedster.

127.0.0.1:6379> SISMEMBER badges:asha speedster
(integer) 1
127.0.0.1:6379> SISMEMBER badges:asha night-owl
(integer) 0
127.0.0.1:6379> SMISMEMBER badges:asha first-win night-owl streak-3
1) (integer) 1
2) (integer) 0
3) (integer) 1
127.0.0.1:6379> SCARD badges:asha
(integer) 3
127.0.0.1:6379> SCARD badges:nobody
(integer) 0
  • SISMEMBER key member replies 1 if the member is in the set, 0 if not. A missing key is treated as an empty set, so the answer is 0, not an error.
  • SMISMEMBER key member [member ...] (Redis 6.2+) checks several members at once and replies with one 1 or 0 per member, in the order you asked.
  • SCARD key replies with the number of members (the set's cardinality); 0 for a missing key.

Why not SMEMBERS? Fetching every member just to check one sends the whole set across the network and makes your app search it. SISMEMBER is a direct lookup that takes about the same time whether the set has ten members or ten million, and SCARD reads a count Redis already keeps.

Two more commands pick members at random: SRANDMEMBER key returns one without removing it (a random "word of the hour"), and SPOP key removes and returns one (drawing a prize winner who cannot win twice).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.