0
0
RedisHow-ToBeginner · 3 min read

How to Use SISMEMBER Command in Redis for Set Membership Check

Use the SISMEMBER command in Redis to check if a specific element exists in a set. The command syntax is SISMEMBER key member, and it returns 1 if the member is in the set or 0 if it is not.
📐

Syntax

The SISMEMBER command checks if a given member exists in a set stored at a specified key.

  • key: The name of the set in Redis.
  • member: The element you want to check for membership.

The command returns 1 if the member exists in the set, otherwise 0.

redis
SISMEMBER key member
💻

Example

This example shows how to add members to a set and then check if a specific member exists using SISMEMBER.

redis
127.0.0.1:6379> SADD fruits apple banana orange
(integer) 3
127.0.0.1:6379> SISMEMBER fruits banana
(integer) 1
127.0.0.1:6379> SISMEMBER fruits grape
(integer) 0
⚠️

Common Pitfalls

Common mistakes when using SISMEMBER include:

  • Checking membership on a key that does not exist returns 0, which means the member is not present.
  • Using SISMEMBER on a key that is not a set will cause an error.
  • Confusing the return values: 1 means member exists, 0 means it does not.
redis
127.0.0.1:6379> SET mykey "hello"
OK
127.0.0.1:6379> SISMEMBER mykey hello
(error) WRONGTYPE Operation against a key holding the wrong kind of value

-- Correct usage --
127.0.0.1:6379> SADD myset hello
(integer) 1
127.0.0.1:6379> SISMEMBER myset hello
(integer) 1
📊

Quick Reference

CommandDescriptionReturn Value
SISMEMBER key memberCheck if member is in set at key1 if exists, 0 if not
SADD key member [member ...]Add one or more members to a setNumber of elements added
SMEMBERS keyGet all members of the setArray of members

Key Takeaways

Use SISMEMBER to check if an element is part of a Redis set with a simple 1 or 0 response.
SISMEMBER returns 0 if the key does not exist or the member is not in the set.
Avoid using SISMEMBER on keys that are not sets to prevent errors.
Remember to add members to the set first using SADD before checking membership.
SISMEMBER is a fast way to test membership without retrieving the entire set.