Redis Research (6)-set type, redis research set type
I. Introduction
A set key can store up to 2 ^ 32-1 strings.
In Redis, the set type is implemented using an empty hash table, so the operation complexity is O (1 ). The Union, intersection, and difference set operations can also be performed between multiple set type keys.
Ii. Commands
1. Add/delete Elements
sadd key membersrem key member
Sadd is used to add one or more elements to the set. If the key does not exist, it is automatically created. A collection cannot have the same element. Therefore, if the element to be added already exists in the collection, the element is ignored. The return value of this command is the number of successfully added elements.
The second sadd command returns 2. Because a already exists, only two elements are actually added.
Srem is used to delete one or more elements from the set and return the number of successfully deleted elements,
Because d does not exist in the set, only one element is deleted and the returned value is 1.
2. Obtain all elements in the Set
smembers key
Returns all elements of the set.
3. Determine whether the element is in the collection
sismember key member
Time complexity O (1), regardless of the number of elements.
4. calculation between Sets
sdiff keysinter keysunion key
(1) sdiff difference set operation, A-B, belongs to A but not belongs to B
Sdiff supports multiple keys at the same time
SetA-setB is calculated sequentially, and then the difference set between the calculation result and setC is calculated.
(2) sinter intersection operation
Sinter also supports multiple keys at the same time.
(3) sunion union operation.
Sunion also supports multiple keys at the same time.
Iii. Command collection
1. Get the number of elements in the Set
scard key
2. Perform set operations and store results
sdiffstore destination keysinterstore destination keysunionstore destination key
Like the sdiff function, the only difference is that the former does not directly return the calculation result, but stores the result in the destination key.
3. Random acquisition of elements in the Set
srandmember key [count]
The count parameter randomly obtains multiple elements at a time.
(1) count is a positive number to obtain count non-repeating elements. If it is greater than the number of elements in the Set, all elements in the set are returned.
(2) Negative count, absolute value element, which may be the same.
4. An element pops up from the collection.
spop key
Select an element randomly from the set.