0
0
Redisquery~5 mins

Set vs sorted set for membership in Redis

Choose your learning style9 modes available
Introduction
Sets and sorted sets help you keep track of groups of items. You use them to check if something is part of a group quickly.
You want to store a list of unique items and check if an item is in that list.
You need to keep items in order by a score and check if an item is in the list.
You want to count how many items are in a group.
You want to get items sorted by a number like a score or time.
You want to add or remove items from a group easily.
Syntax
Redis
SADD key member [member ...]
SISMEMBER key member
ZADD key [NX|XX] [CH] [INCR] score member [score member ...]
ZRANK key member
Sets store unique members without order.
Sorted sets store unique members with a score to keep them ordered.
Examples
Add fruits to a set and check if 'banana' is in the set.
Redis
SADD myset apple banana cherry
SISMEMBER myset banana
Add people with scores to a sorted set and find the rank of 'bob'.
Redis
ZADD myzset 10 alice 20 bob 15 carol
ZRANK myzset bob
Sample Program
This example adds fruits to a set and checks membership. It also adds players with scores to a sorted set and gets the rank of 'bob'.
Redis
SADD fruits apple banana cherry
SISMEMBER fruits banana
ZADD leaderboard 100 alice 200 bob 150 carol
ZRANK leaderboard bob
OutputSuccess
Important Notes
SISMEMBER returns 1 if the member exists, 0 if not.
ZRANK returns the zero-based rank of the member or nil if not found.
Sets are faster for simple membership checks without order.
Summary
Sets store unique items without order and are good for quick membership checks.
Sorted sets store unique items with scores to keep them ordered.
Use sets when order does not matter, and sorted sets when you need order or ranking.