1.2. The Set type

Introduction of 1.2.1.

  • Redis’ Set is an unordered collection of type String. Collection members are unique, which means that no duplicate data can occur in the collection.
  • The collection in Redis is realized by hash table, so the complexity of adding, deleting and searching is O(1).
  • The largest number of members in the set is 32 to 1 (4294967295, each set can store more than 4 billion members). Similar to a Hashtable collection in JAVA
  • The underlying storage structure of redis set object is particularly magical. The underlying storage structure uses two data structures: intset and hashtable. Intset can be understood as an array, and hashtable is a common hashtable (key is the value of set, value is null).
  • Intset is actually an array (int8_t coentents[] array), and the data is stored in order because binary lookups are used to find data.

1.2.2. Command

Assignment syntax:

  • SADD key member1 [member2] Adds one or more members to the collection

Value syntax:

  • SCARD key gets the number of members of the collection

  • SMEMBERS Key returns all members of the collection

  • SISMEMBER key member Checks whether the member element is a member of the set key.

  • SRANDMEMBER Key [count] returns one or more random numbers in the collection

Delete syntax:

  • SREM key member1 [member2] Removes one or more members of the collection

  • SPOP key [count] removes and returns a random element from the collection

  • SMOVE Source Destination member Moves the member element from the source collection to the Destination collection

Difference set syntax:

  • SDIFF key1 [key2] returns the difference set of all sets given (left), and gets the difference set in the set (elements present in set 1, not present in set 2)

  • SDIFFSTORE Destination key1 [key2] returns the difference set of all the given collections and stores it in destination

Intersection syntax:

  • SINTER key1 [key2] returns the intersection of a given set (shared data) and gets the intersection (elements present in both sets)

  • SINTERSTORE Destination Key1 [key2] returns the intersection of all the given collections stored in destination

Union syntax:

  • SUNION key1 [key2] returns the union of all the given sets.

  • SUNIONSTORE Destination KEY1 [KEY2] The union of all given sets is stored in the Destination set

1.2.3. Application Scenarios

It is often used to perform intersection, union, and difference operations on data between two sets

  1. With very convenient implementation such as common concerns, common preferences, two degrees of friends and other functions. For all of the above collection operations, you can also use different commands to choose whether to return the results to the client or store them in a new collection.
  2. Using uniqueness, you can count all the individual IP addresses that visit your site