Using Java to Operate Apache Cassandra

Apache Cassandra is a highly scalable and distributed NoSQL database system. It provides high performance, high availability, and fault tolerance, suitable for processing large-scale structured and unstructured data. To operate Apache Cassandra using Java, the following steps are required: 1. Install and start Cassandra server: Download and install Cassandra on the official website, and then start the Cassandra server. 2. Add Maven dependency: Add the Maven dependency for the Apache Cassandra driver in the pom.xml file of the project. <dependency> <groupId>com.datastax.oss</groupId> <artifactId>java-driver-core</artifactId> <version>4.13.0</version> </dependency> 3. Create a Cassandra cluster instance: Use the driver to create a Cassandra cluster instance, specifying the host and port of the Cassandra server. import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.CqlIdentifier; CqlSession session = CqlSession.builder() .addContactPoint(new InetSocketAddress("localhost", 9042)) .withLocalDatacenter("datacenter1") .withKeyspace(CqlIdentifier.fromCql("my_keyspace")) .build(); 4. Create Keyspace and Table: Use CQL statements to create Keyspace and Table. String createKeyspaceCql = "CREATE KEYSPACE IF NOT EXISTS my_keyspace " + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"; String createTableCql = "CREATE TABLE IF NOT EXISTS my_keyspace.my_table (" + "id INT PRIMARY KEY, column1 TEXT, column2 INT)"; session.execute(createKeyspaceCql); session.execute(createTableCql); 5. Insert Data: Use CQL statements to insert data. String insertCql = "INSERT INTO my_keyspace.my_table (id, column1, column2) VALUES (?, ?, ?)"; PreparedStatement insertStatement = session.prepare(insertCql); session.execute(insertStatement.bind(1, "value1", 100)); 6. Modify data: Use CQL statements to update data. String updateCql = "UPDATE my_keyspace.my_table SET column1 = ? WHERE id = ?"; PreparedStatement updateStatement = session.prepare(updateCql); session.execute(updateStatement.bind("new value", 1)); 7. Query data: Use CQL statements to query data. String selectCql = "SELECT * FROM my_keyspace.my_table WHERE id = ?"; PreparedStatement selectStatement = session.prepare(selectCql); ResultSet resultSet = session.execute(selectStatement.bind(1)); Row row = resultSet.one(); String column1Value = row.getString("column1"); int column2Value = row.getInt("column2"); 8. Delete data: Use CQL statements to delete data. String deleteCql = "DELETE FROM my_keyspace.my_table WHERE id = ?"; PreparedStatement deleteStatement = session.prepare(deleteCql); session.execute(deleteStatement.bind(1)); 9. Close Cassandra Session: Close the Cassandra session at the end of the program. session.close(); This is a simple example of using Java to operate Apache Cassandra. Please adjust the code according to your own needs.