Cassandra & Java (Spring Data)

Apache Cassandra เป็น NoSQL Database (Columns Family) ชนิดหนึ่งซึ่งเขาเคลมว่าสามารถ highly scalable, high-performance distributed database ออกแบบมาเพื่อจัดเก็บ large amounts of data ไม่มี single point of failure.
ซึ่ง Data Model ของ Cassandra จะสามารถอธิบายได้ตามรูปครับ

Keyspace
Data Model

ติดตั้ง Cassandra ก่อนเลยครับ อันนี้บน Mac นะ

brew install cassandra

brew services start cassandra

Cassandra Query Language

เราสามารถ access Cassandra โดยผ่าน Cassandra Query Language (CQL). CQL สามารถจัดการกับ database (Keyspace) ซึ่งเป็นที่จัดเก็บของ tables ต่าง ๆ เราจะใช้ ใช้ cqlsh: prompt เพื่อใช้งาน CQL กันครับ

$ cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.10 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.

cqlsh>

ลองมาดูว่า Cassandra เรามี Keyspace อะไรบ้าง

cqlsh> desc keyspaces;

system_schema system_auth system library system_distributed system_traces

เรามาสร้าง keyspaces ที่ชื่อว่า zengcode กันครับ

cqlsh> CREATE KEYSPACE zengcode WITH replication = {‘class’:’SimpleStrategy’, ‘replication_factor’ : 3};

cqlsh> desc keyspaces;

system_schema system system_distributed

zengcode system_auth library system_traces

cqlsh>

และก็สามารถ Alter Keyspace ได้นะครับเช่น

cqlsh.> ALTER KEYSPACE zengcode WITH replication = {‘class’:’NetworkTopologyStrategy’, ‘replication_factor’ : 3};

และก็สามารถ Drop Keyspace ได้เช่น

DROP KEYSPACE “KeySpace name”

การเรียกใช้ Keyspace

cqlsh> use zengcode;
cqlsh:zengcode>

ต่อไปเรามาสร้าง Table users ใน Keyspace ที่ชื่อว่า zengcode กันครับ

cqlsh:zengcode> CREATE TABLE users (
… user_id int PRIMARY KEY,
… user_name text,
… user_email text
… );

cqlsh:zengcode> desc tables;

users

ลองคิวรี่ดูครับ

cqlsh:zengcode> select * from users;

user_id | user_email | user_name

— — — — -+ — — — — — — + — — — — — -

(0 rows)

ซึ่งจะยังไม่มีข้อมูลใช่ไหมครับ เราลองมาเพิ่มข้อมูลกันสัก row นะครับ

cqlsh:zengcode> insert into users (user_id, user_name, user_email) values (1, ‘ZengCode’, ‘zengcode@mail.com’);
cqlsh:zengcode> select * from users;

user_id | user_email | user_name
— — — — -+ — — — — — — — — — -+ — — — — — -
1 | zengcode@mail.com | ZengCode

(1 rows)

จะขอพูดถึง cql คร่าวๆ แค่นี้ก่อนนะคับ ต่อไปเรามาใช้งาน Cassandra ด้วย Java กันคับ

………………..กำลังเขียน………………………..

)

Chiwa Kantawong (Pea)

Written by

Backend Team Lead

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade