SUNION
返回给定集合的并集。不存在的集合 key 被视为空集。
Command
$ redis-cli.exe -h 127.0.0.1 -p 6379
127.0.0.1:6379> sadd screw 1 2
(integer) 2
127.0.0.1:6379> sadd wrench 3 4
(integer) 2
127.0.0.1:6379> sunion screw wrench
1) "1"
2) "2"
3) "3"
4) "4"
127.0.0.1:6379> exists fakeSetKey
(integer) 0
127.0.0.1:6379> sunion screw fakeSetKey
1) "1"
2) "2"
Code
func sunion(c redis.Conn) {
defer c.Do("DEL", "screw")
defer c.Do("DEL", "wrench")
c.Do("SADD", "screw", 1, 2)
c.Do("SADD", "wrench", 3, 4)
// 1. If given sets all are not empty set, return the union.
unionMemberList, err := redis.Ints(c.Do("SUNION", "screw", "wrench"))
if err != nil {
colorlog.Error(err.Error())
return
}
fmt.Println("If given sets all are not empty set, return the union:", unionMemberList)
// 2. If one of given key doesn't exist, it will considered an empty set.
// And will return the union.
isExist, _ := c.Do("EXISTS", "fakeSetKey")
if isExist == 1 {
c.Do("DEL", "fakeSetKey")
}
unionMemberList, err = redis.Ints(c.Do("SUNION", "screw", "fakeSetKey"))
if err != nil {
colorlog.Error(err.Error())
return
}
fmt.Println("If one of given key doesn't exist, it will considered an empty set,"+
" return the union:", unionMemberList)
}
Output
$ go run main.go
If given sets all are not empty set, return the union: [1 2 3 4]
If one of given key doesn't exist, it will considered an empty set, return the union: [1 2]