SUNION

Introduction and Use Case(s)

The SUNION command in Redis is used to compute the union of multiple sets. This command is particularly useful when you need to combine elements from several sets into one, eliminating duplicates. Typical scenarios include aggregating user permissions from different roles or merging tags from various categories.

Syntax

  1. SUNION key [key ...]

Parameter Explanations

  • key: The keys of the sets you want to unite. You can specify two or more keys.

Return Values

The SUNION command returns a set of elements that are present in at least one of the specified sets. The result is provided as an array of strings.

Example Outputs:

  • If the sets have overlapping elements:

    1. dragonfly> SUNION set1 set2
    2. 1) "a"
    3. 2) "b"
    4. 3) "c"
    5. 4) "d"
  • If the sets do not overlap:

    1. dragonfly> SUNION set1 set3
    2. 1) "a"
    3. 2) "e"
    4. 3) "f"

Code Examples

Using the CLI:

  1. dragonfly> SADD set1 "a" "b" "c"
  2. (integer) 3
  3. dragonfly> SADD set2 "b" "c" "d"
  4. (integer) 3
  5. dragonfly> SADD set3 "e" "f"
  6. (integer) 2
  7. dragonfly> SUNION set1 set2
  8. 1) "a"
  9. 2) "b"
  10. 3) "c"
  11. 4) "d"
  12. dragonfly> SUNION set1 set3
  13. 1) "a"
  14. 2) "c"
  15. 3) "b"
  16. 4) "e"
  17. 5) "f"
  18. dragonfly> SUNION set2 set3
  19. 1) "b"
  20. 2) "c"
  21. 3) "d"
  22. 4) "e"
  23. 5) "f"

Best Practices

  • Ensure the sets exist before performing the SUNION operation.
  • Consider using the SUNIONSTORE command if you need to store the union result for future use, which avoids recomputation.

Common Mistakes

  • Using non-set data types with SUNION will result in errors. Always ensure the keys refer to sets.
  • Forgetting that SUNION does not modify any of the input sets but only returns the union.

FAQs

What happens if one or more keys do not exist?

If a key does not exist, SUNION treats it as an empty set. The command still returns the union of the existing sets.

Can I use SUNION with just one set?

Yes, SUNION with a single set will return all elements of that set.