Trong bài tutorial này, chúng ta sẽ viết một chương trình Cassandra sử dụng IntelliJ thay vì CQL Shell như trong bài tutorial trước. Ta thêm dependency của Cassandra vào file pom.xml như sau:
1 2 3 4 5 6 |
<!-- https://mvnrepository.com/artifact/com.datastax.cassandra/cassandra-driver-core --> <dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-driver-core</artifactId> <version>3.6.0</version> </dependency> |
Để kết nối với Cassandra, trước hết ta tạo một cluster object với Cluster.builder() và hàm addContactPoint() rồi tạo một phiên làm việc sử dụng hàm connect() như sau:
1 2 3 4 5 |
//creating Cluster object Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); //Creating Session object Session session = cluster.connect(); |
Sau đó ta sử dụng các query tương tự như trong bài Cài đặt và sử dụng Cassandra và thực thi các query này bằng hàm execute(). Ví dụ để xóa một KeySpace, ta sử dụng đoạn code sau (nếu không sử dụng IF EXISTS thì chương trình sẽ báo lỗi nếu KeySpace cần xóa không tồn tại):
1 2 3 4 5 |
//Query to drop the keyspace String query="DROP KEYSPACE IF EXISTS testkeyspace;"; //Executing the query session.execute(query); |
Tương tự vậy, việc tạo một KeySpace, tạo một table, thêm dữ liệu vào table, cập nhật lại dữ liệu và truy suất dữ liệu có thể được thực hiện như sau:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
//Query to create a keyspace query= "CREATE KEYSPACE testkeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor':3};"; //Executing the query session.execute(query); //Connect to the testkeyspace keyspace session=cluster.connect("testkeyspace"); //Create emp table query= "CREATE TABLE emp(\n" + "emp_id int PRIMARY KEY,\n" + "emp_name text,\n" + "emp_city text,\n" + "emp_sal varint,\n" + "emp_phone varint\n" + ");"; //Executing the query session.execute(query); //Insert data into the table query="INSERT INTO emp (emp_id, emp_name, emp_city,emp_phone, emp_sal)\n" + "VALUES(1,'John', 'London', 0786022338, 65000);"; String query2="INSERT INTO emp (emp_id, emp_name, emp_city,emp_phone, emp_sal)\n" + "VALUES(2,'David', 'Hanoi', 0986022576, 40000);"; //Executing the query session.execute(query); session.execute(query2); //Retrieve data from emp table query2="SELECT * FROM emp;"; ResultSet result= session.execute(query2); //Display column definition System.out.println("Column definition: "+result.getColumnDefinitions().toString()); //Display all data System.out.println("\nALl data in the table: "+result.all()); //update query query = "UPDATE emp SET emp_city='HoChiMinh',emp_sal=55000 WHERE emp_id=2"; session.execute(query); //Display the data after updating System.out.println("\nThe data after updating: "+session.execute(query2).all()); //Display a specific column result= session.execute("SELECT * FROM emp;"); System.out.println("\nSelect only emp_name and emp_city in the ResultSet:"); for(Row row:result.all()) { System.out.println("Name: "+row.getString("emp_name") +", City: "+row.getString("emp_city")); } |
Chạy đoạn code trên ta được kết quả:
Ngoài ra để thực thi nhiều modification statements (insert, update, delete) cùng một lúc, chúng ta có thể sử dụng tính năng BATCH của Cassandra với syntax như sau:
1 2 3 |
BEGIN BATCH <insert-stmt>/ <update-stmt>/ <delete-stmt> APPLY BATCH |
Ta sử dụng BATCH để tiến hành một số thao tác trên emp table như sau:
1 2 3 4 5 6 7 8 9 10 11 |
//Using batch to execute multiple modification statements StringBuilder sb = new StringBuilder("BEGIN BATCH ") .append("INSERT INTO emp (emp_id, emp_name, emp_city,emp_phone, emp_sal)\n" + "VALUES(3,'Bob', 'NewYork', 0726022689, 58000);") .append("UPDATE emp SET emp_sal = 69000 WHERE emp_id =1;") .append("DELETE emp_city, emp_phone FROM emp WHERE emp_id = 2;") .append("APPLY BATCH"); //Executing the query session.execute(sb.toString()); //Display all data System.out.println("\nALl data in the table: "+session.execute(query2).all()); |
Như vậy chúng ta đã hoàn thành việc viết một chương trình đơn giản sử dụng Cassandra trong IntelliJ. Các bạn có thể tham khảo full code của chương trình dưới đây.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; public class BasicProgramJava { public static void main(String args[]){ //creating Cluster object Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); //Creating Session object Session session = cluster.connect(); //Query to drop the keyspace String query="DROP KEYSPACE IF EXISTS testkeyspace;"; //Executing the query session.execute(query); //Query to create a keyspace query= "CREATE KEYSPACE testkeyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor':3};"; //Executing the query session.execute(query); //Connect to the testkeyspace keyspace session=cluster.connect("testkeyspace"); //Create emp table query= "CREATE TABLE emp(\n" + "emp_id int PRIMARY KEY,\n" + "emp_name text,\n" + "emp_city text,\n" + "emp_sal varint,\n" + "emp_phone varint\n" + ");"; //Executing the query session.execute(query); //Insert data into the table query="INSERT INTO emp (emp_id, emp_name, emp_city,emp_phone, emp_sal)\n" + "VALUES(1,'John', 'London', 0786022338, 65000);"; String query2="INSERT INTO emp (emp_id, emp_name, emp_city,emp_phone, emp_sal)\n" + "VALUES(2,'David', 'Hanoi', 0986022576, 40000);"; //Executing the query session.execute(query); session.execute(query2); //Retrieve data from emp table query2="SELECT * FROM emp;"; ResultSet result= session.execute(query2); //Display column definition System.out.println("Column definition: "+result.getColumnDefinitions().toString()); //Display all data System.out.println("\nALl data in the table: "+result.all()); //update query query = "UPDATE emp SET emp_city='HoChiMinh',emp_sal=55000 WHERE emp_id=2"; session.execute(query); //Display the data after updating System.out.println("\nThe data after updating: "+session.execute(query2).all()); //Display a specific column result= session.execute("SELECT * FROM emp;"); System.out.println("\nSelect only emp_name and emp_city in the ResultSet:"); for(Row row:result.all()) { System.out.println("Name: "+row.getString("emp_name") +", City: "+row.getString("emp_city")); } //Using batch to execute multiple modification statements StringBuilder sb = new StringBuilder("BEGIN BATCH ") .append("INSERT INTO emp (emp_id, emp_name, emp_city,emp_phone, emp_sal)\n" + "VALUES(3,'Bob', 'NewYork', 0726022689, 58000);") .append("UPDATE emp SET emp_sal = 69000 WHERE emp_id =1;") .append("DELETE emp_city, emp_phone FROM emp WHERE emp_id = 2;") .append("APPLY BATCH"); //Executing the query session.execute(sb.toString()); //Display all data System.out.println("\nALl data in the table: "+session.execute(query2).all()); } } |
Lưu ý: chương trình trên được viết bằng Java nhưng các bạn hoàn toàn có thể viết bằng scala với syntax tương tự. Hoặc các bạn có thể copy trực tiếp đoạn code trên vào một Scala Object, IntelliJ sẽ tự động chuyển code từ Java sang Scala.
Ví dụ như sau:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import com.datastax.driver.core._ object BasicProgram { def main(args: Array[String]): Unit = { val cluster = Cluster.builder().addContactPoint("127.0.0.1").build() val session = cluster.connect("testkeyspace") var query="SELECT * FROM emp;" val set = session.execute(query); System.out.println(set.all()); } } |