[Avg. reading time: 7 minutes]

Set

A Redis set is an unordered collection of unique strings (members). You can use Redis sets to efficiently:

Key Characteristics of Redis Sets

Uniqueness: Each element in a set is unique. Attempting to add duplicate elements has no effect.

Unordered: Sets do not maintain the order of elements, making them ideal for operations where order does not matter.

  • Track unique items (e.g., track all unique IP addresses accessing a given blog post).

  • Represent relations (e.g., the set of all users with a given role).

  • Perform common set operations such as intersection, unions, and differences.

  • SADD adds a new member to a set.

  • SREM removes the specified member from the set.

  • SISMEMBER tests a string for set membership.

  • SINTER returns the set of members that two or more sets have in common (i.e., the intersection).

  • SCARD returns the size (a.k.a. cardinality) of a set.

Tags

SADD post:101:tags "Redis" "Databases" "NoSQL"
SADD post:102:tags "Programming" "Python" "NoSQL"

-- Output the values

SMEMBERS post:101:tags

-- Insection

SINTER post:101:tags post:102:tags

-- Union

SUNION post:101:tags post:102:tags

-- Move

SMOVE post:102:tags post:101:tags "Python"

-- Remove tag

SREM post:101:tags "NoSQL"

User Active Sessions

-- add users

SADD active_users "user:123"
SADD active_users "user:456"
SADD active_users "user:789"

-- checking whether is member

SISMEMBER active_users "user:456"

-- remove user

SREM active_users "user:456"

-- returns total number of items

SCARD active_users

Social Media Example

SADD "user:userID1:followers" followerID1
SADD "user:userID1:followers" followerID2

SADD "user:userID2:followers" followerID1
SADD "user:userID2:followers" followerID3

-- Find the common followers between two users
SINTER "user:userID1:followers" "user:userID2:followers"

-- Get the SET values
SMEMBERS "user:userID1:followers"

-- Gets the size of the set.
SCARD "user:userID1:followers"

-- Find out whether followerID1 is part of this set
SISMEMBER user:userID1:followers followerID1

Use Cases

Real-time Analytics: Track and display unique events or items, like products viewed in a session.

ACLs (Access Control List): Manage user access to certain features or commands.

#SADD #SMEMBERS #ACL #NoSQL #Redis Ver 5.5.3

Last change: 2025-10-15