Skip to content
Redis

Sets

Manage unique collections and compute intersections.

By EZ4Code Team
setuniquesetops

Code

# Add and remove members
SADD tags:post:1 "mongo" "db" "nosql"
SADD tags:post:2 "postgres" "db" "sql"
SREM tags:post:1 "nosql"

# Membership and size
SISMEMBER tags:post:1 "db"
SCARD tags:post:1
SMEMBERS tags:post:1

# Set operations
SINTER tags:post:1 tags:post:2     # common tags
SUNION tags:post:1 tags:post:2     # all tags
SDIFF  tags:post:1 tags:post:2     # in 1 but not 2

# Random member and pop
SRANDMEMBER tags:post:1
SPOP tags:post:1

Explanation

Redis sets store unique strings and support fast membership tests and set operations like union, intersection, and difference. SINTER is commonly used for tag or friend-of-friend lookups. SRANDMEMBER and SPOP return or remove random members, useful for sampling and raffles.

More Redis Snippets