0
0
Redisquery~5 mins

Unique visitor tracking with sets in Redis

Choose your learning style9 modes available
Introduction
We use sets in Redis to count unique visitors because sets automatically ignore duplicates, making it easy to track who visited without counting anyone twice.
Counting how many different people visited your website today.
Tracking unique users who clicked on a special offer.
Finding out how many unique devices accessed your app in a week.
Checking unique visitors to a blog post or article.
Measuring unique participants in an online event or webinar.
Syntax
Redis
SADD key member [member ...]
SCARD key
SMEMBERS key
SADD adds one or more members to a set stored at key.
SCARD returns the number of unique members in the set.
SMEMBERS lists all unique members in the set.
Examples
Add visitor with ID 12345 to the visitors set.
Redis
SADD visitors 12345
Add two visitors with IDs 12345 and 67890 to the visitors set.
Redis
SADD visitors 12345 67890
Get the count of unique visitors.
Redis
SCARD visitors
Get the list of all unique visitor IDs.
Redis
SMEMBERS visitors
Sample Program
We add visitor IDs 101 and 102. Adding 101 again does not increase the count because sets ignore duplicates. Then we count unique visitors and list them.
Redis
SADD visitors 101
SADD visitors 102
SADD visitors 101
SCARD visitors
SMEMBERS visitors
OutputSuccess
Important Notes
Sets in Redis automatically ignore duplicate entries, so you don't have to check if a visitor ID is already added.
Use SCARD to quickly get the number of unique visitors without retrieving all members.
SMEMBERS can be slow if the set is very large; use it only when you need the full list.
Summary
Redis sets help track unique visitors by storing visitor IDs without duplicates.
Use SADD to add visitor IDs, SCARD to count unique visitors, and SMEMBERS to list them.
This method is simple and efficient for counting unique users in real time.