Set and Sorted Set
Learn how to use the set and sorted set data types.
Set
A Redis set data type is similar to a set data structure that you may have used in programming languages such as Java. The two most important characteristics of a set in Redis are:
They contain unique strings only. In other words, duplicate elements are not allowed.
There are no ordering guarantees. When we retrieve items from a set, they may not be in the same order as when we added them to the set.
Just like the string data type, a set in Redis seems simple, but it includes a rich set of features. Let’s explore a few of them in the following sections.
The SAdd
method
To do anything useful with a set, we first need to add items to it. We can do that with the SAdd
method. In the example below, we add three fruits (apple
, orange
, and banana
) to a set called fruits
:
client.SAdd(ctx, "fruits", "apple", "orange", "banana")
The SMembers
method
To get all the members of a set, we can simply use the SMembers
method. Here, we get all the fruit names from the fruits
set. This returns a string slice that we can iterate over:
fruits := client.SMembers(ctx, "fruits").Val()
The SIsMember
method
If we want to check whether a specific exists in the set, we can use the SIsMember
method. In the example below, we invoke ...