cassandra에서 counter 테이블로 딱 사용하기 좋다. 


cassandra에서는 default 값으로 null을 사용하지만, counter는 예외다. 0이 디폴트 값이다. 



간단한 컬럼패밀리로 테스트를 진행해보면, null이 저장됨을 볼 수 있다. 



cqlsh> create table test.test(test int, x int, primary key(test));

cqlsh> insert into test.test(test) values(1);

cqlsh> select * from test.test;


 test | x

------+------

    1 | null




그러나, counter 필드는 초기값이 0이 되기 때문에 null + 1로 되어 에러가 발생하지 않는다. 




cqlsh> DROP TABLE IF EXISTS googleplus.user_followee_recent_relation


cqlsh> CREATE TABLE googleplus.user_followee_recent_relation(

   ...   followee_id int,

   ...   profile_id int,

   ...   counter_value counter,

   ...   PRIMARY KEY (followee_id, profile_id)

   ... );



cqlsh> update googleplus.user_followee_recent_relation set counter_value = counter_value + 1 where followee_id = 1 and profile_id = 1;



cqlsh> select * from googleplus.user_followee_recent_relation;


 followee_id | profile_id | counter_value

-------------+------------+---------------

           1 |          1 |             1





하지만, 제약사항이 있다.


1. insert를 사용할 수 없다.


 cqlsh> insert into googleplus.user_followee_recent_relation(followee_id, profile_id, counter_value) values (1,1,0) using ttl 2;

InvalidRequest: code=2200 [Invalid query] message="INSERT statement are not allowed on counter tables, use UPDATE instead"




2. TTL 레코드에서 적용할 수 없다. 



cqlsh> update googleplus.user_followee_recent_relation set counter_value = counter_value + 1 where followee_id = 2 and profile_id = 2 using ttl 3 ;

SyntaxException: <ErrorMessage code=2000 [Syntax error in CQL query] message="line 1:122 missing EOF at 'using' (...2 and profile_id = 2 [using] ttl...)">



cqlsh> update using ttl 10 googleplus.user_followee_recent_relation set counter_value = counter_value + 1 where followee_id = 2 and profile_id = 2;

SyntaxException: <ErrorMessage code=2000 [Syntax error in CQL query] message="line 1:25 no viable alternative at input '.' (update using ttl 10 googleplus[.]...)">




스펙에 따르면, TIMESTAMP와 TTL을 카운터 필드가 포함된 테이블에서는 쓸 수 없도록 명시되어 있다.


https://docs.datastax.com/en/cql/3.1/cql/cql_using/use_counter_t.html


To load data into a counter column, or to increase or decrease the value of the counter, use the UPDATE command. Cassandra rejects USING TIMESTAMP or USING TTL in the command to update a counter column.


 


count 테이블과 TTL을 동시에 사용할 수 없는 속성이다. 따라서 다른 구조체를 고민해봐야 한다.

만약 count가 아주 작은 값으로만 쓴다면, 필드를 여러 개를 만드는 것도 괜찮을 것 같다. 


(key1, key2, counter1, counter2, counter3) 



'cassandra' 카테고리의 다른 글

[cassadra] compaction 전략  (0) 2016.12.09
[cassandra] select count(*) 구하기  (0) 2016.12.07
[cassandra] read repair  (0) 2016.11.23
[cassandra] cqlsh 팁  (0) 2016.11.21
[cassandra] insert는 update와 같다.  (0) 2016.11.16
Posted by '김용환'
,