Databases 4 min read

Understanding Redis Sets and Their Use Cases

Redis Sets are unordered collections of unique strings backed by hash tables that provide O(1) add, delete, and lookup operations, automatically switch to a compact integer array (intset) for small integer-only sets, and are ideal for deduplicated data and fast set operations such as intersection, union, and difference, exemplified by computing common friends in social applications.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Understanding Redis Sets and Their Use Cases

Redis Sets are unordered collections of strings, similar to Java's HashSet . They are implemented with hash tables, giving O(1) time complexity for add, delete, and lookup operations.

Elements in a Set are unique, so duplicate data cannot appear.

Internally, the hash table stores each element as a key with a NULL value. When all elements are 64‑bit integers and the number of elements does not exceed the set-max-intset-entries limit (default 512), Redis switches to an intset (integer array) for lower memory usage.

Typical scenarios include storing multiple items without duplicates and without caring about order, as well as performing set operations such as intersection, union, and difference. Examples: finding common followers, calculating daily new followers, or tagging articles.

Practical example – a social app needs a “common friends” feature. First, create Sets for each user:

SADD user:刘备 赵子龙 张飞 关羽 貂蝉
SADD user:曹操 貂蝉 夏侯惇 典韦 张辽

Then compute the intersection with:

SINTERSTORE user:曹刘好友 user:刘备 user:曹操

Retrieve the result using:

SMEMBERS user:曹刘好友

The command returns the common friend “貂蝉”.

backendDatabaseRedisCode Exampleset operationssets
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.