0% found this document useful (0 votes)
2 views

Cassandra_Java

This document provides a step-by-step guide on using the DataStax Java Driver for Apache Cassandra, including setting up Maven dependencies, connecting to a Cassandra cluster, creating keyspaces and tables, altering tables, and inserting data. It includes code snippets for each step, demonstrating how to implement these actions in Java. The document also covers testing the created structures and data to ensure everything is functioning correctly.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Cassandra_Java

This document provides a step-by-step guide on using the DataStax Java Driver for Apache Cassandra, including setting up Maven dependencies, connecting to a Cassandra cluster, creating keyspaces and tables, altering tables, and inserting data. It includes code snippets for each step, demonstrating how to implement these actions in Java. The document also covers testing the created structures and data to ensure everything is functioning correctly.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

How to use the DataStax Java Driver for Apache Cassandra

Step1: Write and set Maven Dependency at pom.xml


<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>java-driver-core</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-query-builder</artifactId>
<version>4.1.0</version>
</dependency>

Unit test:
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit</artifactId>
<version>4.1.0</version>
</dependency>
Step 2:
In order to connect to Cassandra from Java, we need to build a Cluster object.

An address of a node needs to be provided as a contact point. If we don't


provide a port number, the default port (9042) will be used.
These settings allow the driver to discover the current topology
# Cassandra connector
public class CassandraConnector {
private Cluster cluster;
private Session session;
public void connect(String node, Integer port) {
Builder b = Cluster.builder().addContactPoint(node);
if (port != null) {
b.withPort(port);
}
cluster = b.build();
session = cluster.connect();
}
public Session getSession() {
return this.session;
}
public void close() {
session.close();
cluster.close();
}
}
Step3.
Creating the Keyspace: Let's create our “library” keyspace:

public void createKeyspace(


String keyspaceName, String replicationStrategy, int replicationFactor) {
StringBuilder sb =
new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ")
.append(keyspaceName).append(" WITH replication = {")
.append("'class':'").append(replicationStrategy)
.append("','replication_factor':").append(replicationFactor)
.append("};");
String query = sb.toString();
session.execute(query);
}
#Note:
Except from the keyspaceName, we need to define two more parameters,
the replicationFactor and the replicationStrategy. These parameters determine
the number of replicas and how the replicas will be distributed across the ring,
respectively.
With replication Cassandra ensures reliability and fault tolerance by storing
copies of data in multiple nodes.
At this point we may test that our keyspace has successfully been created:
private KeyspaceRepository schemaRepository;
private Session session;
@Before
public void connect() {
CassandraConnector client = new CassandraConnector();
client.connect("127.0.0.1", 9142);
this.session = client.getSession();
schemaRepository = new KeyspaceRepository(session);
}
@Test
public void whenCreatingAKeyspace_thenCreated() {
String keyspaceName = "library";
schemaRepository.createKeyspace(keyspaceName, "SimpleStrategy", 1);
ResultSet result =
session.execute("SELECT * FROM system_schema.keyspaces;");
List<String> matchedKeyspaces = result.all()
.stream()
.filter(r -> r.getString(0).equals(keyspaceName.toLowerCase()))
.map(r -> r.getString(0))
.collect(Collectors.toList());
assertEquals(matchedKeyspaces.size(), 1);
assertTrue(matchedKeyspaces.get(0).equals(keyspaceName.toLowerCase()));
}
Step 4: Creating a Column Family
#Now, we can add the first Column Family “books” to the existing keyspace

private static final String TABLE_NAME = "books";


private Session session;
public void createTable() {
StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ")
.append(TABLE_NAME).append("(")
.append("id uuid PRIMARY KEY, ")
.append("title text,")
.append("subject text);");
String query = sb.toString();
session.execute(query);
}
#The code to test that the Column Family has been created, is provided below
private BookRepository bookRepository;
private Session session;

@Before
public void connect() {
CassandraConnector client = new CassandraConnector();
client.connect("127.0.0.1", 9142);
this.session = client.getSession();
bookRepository = new BookRepository(session);
}
@Test
public void whenCreatingATable_thenCreatedCorrectly() {
bookRepository.createTable();
ResultSet result = session.execute(
"SELECT * FROM " + KEYSPACE_NAME + ".books;");
List<String> columnNames =
result.getColumnDefinitions().asList().stream()
.map(cl -> cl.getName())
.collect(Collectors.toList());
assertEquals(columnNames.size(), 3);
assertTrue(columnNames.contains("id"));
assertTrue(columnNames.contains("title"));
assertTrue(columnNames.contains("subject"));
}
Step. Altering the Column Family
#Note: A book has also a publisher, but no such column can be found in the
created table. We can use the following code to alter the table and add a new
column:
public void alterTablebooks(String columnName, String columnType) {
StringBuilder sb = new StringBuilder("ALTER TABLE ")
.append(TABLE_NAME).append(" ADD ")
.append(columnName).append(" ")
.append(columnType).append(";");
String query = sb.toString();
session.execute(query);
}
#Let's make sure that the new column publisher has been added:
@Test
public void whenAlteringTable_thenAddedColumnExists() {
bookRepository.createTable();
bookRepository.alterTablebooks("publisher", "text");
ResultSet result = session.execute(
"SELECT * FROM " + KEYSPACE_NAME + "." + "books" + ";");
boolean columnExists = result.getColumnDefinitions().asList().stream()
.anyMatch(cl -> cl.getName().equals("publisher"));

assertTrue(columnExists);
}

Step : Inserting Data in the Column Family


#Note:Now that the books table has been created, we are ready to start adding
data to the table:
public void insertbookByTitle(Book book) {
StringBuilder sb = new StringBuilder("INSERT INTO ")
.append(TABLE_NAME_BY_TITLE).append("(id, title) ")
.append("VALUES (").append(book.getId())
.append(", '").append(book.getTitle()).append("');");

String query = sb.toString();


session.execute(query);
}

A new row has been added in the ‘books' table, so we can test if the row exists:
@Test
public void whenAddingANewBook_thenBookExists() {
bookRepository.createTableBooksByTitle();

String title = "Effective Java";


Book book = new Book(UUIDs.timeBased(), title, "Programming");
bookRepository.insertbookByTitle(book);

Book savedBook = bookRepository.selectByTitle(title);


assertEquals(book.getTitle(), savedBook.getTitle());
}

In the test code above we have used a different method to create a table
named booksByTitle:

public void createTableBooksByTitle() {


StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ")
.append("booksByTitle").append("(")
.append("id uuid, ")
.append("title text,")
.append("PRIMARY KEY (title, id));");

String query = sb.toString();


session.execute(query);
}
Step 2: Using Datastax Driver
 Create a Connector session:
Import cqlSession;
public class CassandraConnector {

private CqlSession session;

public void connect(String node, Integer port, String dataCenter) {


CqlSessionBuilder builder = CqlSession.builder();
builder.addContactPoint(new InetSocketAddress(node, port));
builder.withLocalDatacenter(dataCenter);

session = builder.build();
}

public CqlSession getSession() {


return this.session;
}

public void close() {


session.close();
}
}

Step no:3
 Create Keyspace
Use the SimpleStrategy replication strategy with the
number of replicas set to 1:

public class KeyspaceRepository {

public void createKeyspace(String keyspaceName, int


numberOfReplicas) {
CreateKeyspace createKeyspace =
SchemaBuilder.createKeyspace(keyspaceName)
.ifNotExists()
.withSimpleStrategy(numberOfReplicas);

session.execute(createKeyspace.build());
}

// ...
}
//Also, we can start using the keyspace in the current session:

public class KeyspaceRepository {

//...

public void useKeyspace(String keyspace) {


session.execute("USE " + CqlIdentifier.fromCql(keyspace));
}
}

You might also like