DB/Cassandra

CQL(Cassandra Query Language)

잔망루피 2023. 2. 8. 23:06
반응형

Cassandra는 자동으로 스키마를 생성해주는 기능이 없다.

테이블을 먼저 생성해야 한다.

 

 

데이터 타입

text  
int 32-bit integers
bigint 64-bit integers
float  
double  
boolean true / false
timestamp  
uuid  
blob binary data
varint arbitrarily large integers

list, set, map, tuple과 같은 커스텀 데이터 타입도 등록할 수 있다.

 

 

Primary Keys

Simple Primary Keys entity 클래스에서 하나의 partition key 필드로 구성
Composite Keys
하나 이상의 primary key 필드로 구성

Apache Cassandra Spring Data에서 Composite key를 나타내는 2가지 방법이 있다.
1. 엔티티 안에 임베드하기
2. @PrimaryKeyClass 사용

가장 간단한 composite key의 형태는 한 개의 partition key와 한 개의 clustering key로 구성하는 것이다.
Flat Composite Primary Keys Flat composite primary key는 entity 안에 flat fields로써 임베디드된다.
쿼리에 개별 필드에 대한 predicates가 포함되어 있거나 MapId를 사용해야 한다.

   

 

테이블 생성

@Data
@Builder
@Table("user_feed")
public class UserFeed {
    @PrimaryKeyColumn(name = "user_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
    private String userId;

    @Indexed
    @PrimaryKeyColumn(name = "username", ordinal = 1 )
    private String username;

    @PrimaryKeyColumn(name = "created_at", ordinal = 2, ordering = Ordering.DESCENDING)
    private Instant createdAt;

    @PrimaryKeyColumn(name = "post_id", ordinal = 3)
    private String postId;
}

생성일자 createdAt은 내림차순 정렬

😺 PrimaryKeyType

PARTITIONED  Compound PK에서 가장 첫 번째 컬럼으로 구성되는 컬럼
각 파티션에 대한 데이터 구조를 결정
CLUSTERED Compound PK에서 Partition Key 다음에 구성되는 컬럼
데이터를 정렬할 때 사용

 

 

CREATE TABLE user_feed (
    user_id text,
    username text,
    created_at timestamp,
    post_id text,
    PRIMARY KEY ((user_id), username, created_at, post_id)
) WITH CLUSTERING ORDER BY (username ASC, created_at DESC);

 


데이터 삽입

INSERT INTO user_feed (user_id, username, created_at, post_id) 
VALUES ('user123', 'johndoe', '2023-02-15 15:30:00+0000', 'post456');

 

 

참고 👇

https://docs.spring.io/spring-data/cassandra/docs/current/reference/html/

 

Spring Data for Apache Cassandra - Reference Documentation

Example 10. Repository definitions using domain classes with annotations interface PersonRepository extends Repository { … } @Entity class Person { … } interface UserRepository extends Repository { … } @Document class User { … } PersonRepository re

docs.spring.io

 

cqlsh 기본 사용법 (tistory.com)

 

cqlsh 기본 사용법

cqlsh 기본 사용법 1. bin/cqlsh - Cassandra를 위한 상호 command line interface이다. - 사용자가 CQL(Cassandra Query Language) 문장을 수행하여 Cassandra를 이용할 수 있다. 2. cqlsh 실행하기 - $CASSANDRA_HOME/bin/cqlsh 를 실

tommypagy.tistory.com

 

반응형