본문 바로가기

OSS

[Redis] Redis Set 기초 설명

반응형

 

Redis에서 Set은 데이터 구조 중 하나로, 중복되지 않는 유니크한 요소들의 모음이며 순서가 없는 컬렉션입니다. Set은 해시 테이블로 구현되어 매우 빠른 성능을 자랑합니다. 추가, 삭제, 존재 여부 확인 등의 작업이 평균적으로 O(1) 시간 복잡도를 가집니다.

Redis Set의 주요 특징

언제 사용하는까?

  • 중복 제거가 필요할 때: Set은 유니크한 요소들만을 저장하므로, 자연스럽게 중복을 제거할 수 있습니다.
  • 빠른 집합 연산이 필요할 때: 교집합, 합집합, 차집합 등의 집합 연산을 빠르게 처리할 수 있습니다.
  • 빠른 존재 여부 확인이 필요할 때: 특정 요소가 Set에 존재하는지 빠르게 확인할 수 있습니다.

왜 Set을 사용하면 좋을까?

  • 고성능: Set은 해시 테이블로 구현되어 있어 O(1)의 시간 복잡도로 요소를 추가, 삭제, 조회할 수 있습니다.
  • 유니크한 데이터 관리: 중복된 데이터를 자동으로 제거하여 관리할 수 있습니다.
  • 편리한 집합 연산: 다양한 집합 연산 명령어(SINTER, SUNION, SDIFF 등)를 통해 데이터를 쉽게 조작할 수 있습니다.

Redis Set의 주요 명령어

기본 명령어

SADD: Set에 요소를 추가합니다.

SADD users "alice" "bob"

 

SREM: Set에서 요소를 제거합니다.

SREM users "alice"
SISMEMBER: 요소가 Set에 존재하는지 확인합니다.
SISMEMBER users "bob"

 

SCARD: Set의 요소 개수를 반환합니다.

SCARD users

 

SMEMBERS: Set의 모든 요소를 반환합니다.

SMEMBERS users
 

집합 연산 명령어

SINTER: 두 개 이상의 Set에서 교집합을 반환합니다.

SINTER active_users all_users
 
SUNION: 두 개 이상의 Set에서 합집합을 반환합니다.
 
SUNION developers designers

 

SDIFF: 첫 번째 Set을 기준으로 다른 Set들과의 차집합을 반환합니다.

SDIFF users banned_users

 

SUNIONSTORE: 합집합 결과를 새로운 Set에 저장합니다.

SUNIONSTORE all_staff developers designers

 

SDIFFSTORE: 차집합 결과를 새로운 Set에 저장합니다.

SDIFFSTORE active_not_banned users banned_users

 

SINTERSTORE: 교집합 결과를 새로운 Set에 저장합니다.

SINTERSTORE common_interests user_interests group_interests

 

 

Go 언어로 Redis Set 사용 예제

package main

import (
    "context"
    "fmt"

    "github.com/redis/go-redis/v9"
)

func main() {
    r := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        DB:   0,
    })

    ctx := context.Background()

    // Set에 요소 추가
    r.SAdd(ctx, "users", "alice", "bob", "charlie")
    fmt.Println(r.SIsMember(ctx, "users", "bob").Result())

    // Set에서 요소 제거
    r.SRem(ctx, "users", "alice")

    // Set의 모든 요소 출력
    fmt.Println(r.SMembers(ctx, "users").Result())

    // Set의 요소 개수 출력
    fmt.Println(r.SCard(ctx, "users").Result())

    r.SAdd(ctx, "group1", "alice", "bob")
    r.SAdd(ctx, "group2", "bob", "charlie")

    // 교집합
    intersection := r.SInter(ctx, "group1", "group2").Val()
    fmt.Println("Intersection:", intersection)

    // 합집합
    union := r.SUnion(ctx, "group1", "group2").Val()
    fmt.Println("Union:", union)

    // 차집합
    diff := r.SDiff(ctx, "group1", "group2").Val()
    fmt.Println("Difference:", diff)

    // 합집합 결과를 새로운 Set에 저장
    r.SUnionStore(ctx, "all_users", "group1", "group2")
    fmt.Println("Union Result:", r.SMembers(ctx, "all_users").Val())

    // 차집합 결과를 새로운 Set에 저장
    r.SDiffStore(ctx, "active_users", "group1", "group2")
    fmt.Println("Difference Result:", r.SMembers(ctx, "active_users").Val())

    // 교집합 결과를 새로운 Set에 저장
    r.SInterStore(ctx, "common_members", "group1", "group2")
    fmt.Println("Intersection Result:", r.SMembers(ctx, "common_members").Val())
}
반응형

'OSS' 카테고리의 다른 글

[Apache Kafka] 카프카 토픽이란?  (0) 2024.08.04
[Apache Kafka] 아파치 카프카란?  (0) 2024.08.04
[Redis] Redis Hash Set이란?  (0) 2024.07.20
[Redis] Redis란?  (0) 2024.07.20
Kubernetes에서 Vault Agent Injector로 구성하기(3)  (0) 2023.09.10