The new version of cassandra driver, using SchemaBuilder for table operations

Before cassanda's official driver, cassandra-driver-core-2.1.3.jar, creating tables, modifying tables, and creating indexes could only be done by spelling CQL statements and then executing them through sessions. May often result in grammatical formatting errors.

In the latest version of the driver cassandra-driver-core-2.1.3.jar, a more convenient way to modify the table is provided. Similar to the com.datastax.driver.core.querybuilder.QueryBuilder class used for CRUD operations, it provides a com.datastax.driver.core.schemabuilder.SchemaBuilder class for table operations.

This class can construct almost all operations on the table. Here are examples of common operations:
first introduce the jar package:

<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.3</version>
</dependency>

 Then you can use SchemaBuilder fluently just like writing cql statements. It omits the generation of session, you can refer to "Java implements additions, deletions and changes in cassandra"

//create table
Create createTbale
         = SchemaBuilder.createTable("mykeyspace", "mytable")
			.addPartitionKey("pk1", DataType.cint())
			.addColumn("col1", DataType.text())
			.addColumn("col2", DataType.bigint());
 
session.execute(createTbale);
 
//add a column
Schema statement addColumn
	= SchemaBuilder.alterTable("mykeyspace", "mytable")
		       .addColumn("col3")
		       .type(DataType.cdouble());
session.execute(addColumn);
 
// delete a column
Schema Statement dropColumn
		= SchemaBuilder.alterTable("mykeyspace", "mytable")
			       .dropColumn("col2");
session.execute(dropColumn);
 
//modify a column
SchemaStatement alterColumn
		= SchemaBuilder.alterTable("mykeyspace", "mytable")
			       .alterColumn("col1")
			       .type(DataType.cdouble());
session.execute(alterColumn);
 
//column name change
SchemaStatement renameColumn
		= SchemaBuilder.alterTable("mykeyspace", "mytable")
			       .renameColumn("col1")
			       .to("col4");
session.execute(alterColumn);
 
// Muscle gain index
SchemaStatement createIndex
		= SchemaBuilder.createIndex("idx_col4")
			       .onTable("mykeyspace", "mytable")
			       .andColumn("col4");
session.execute(createIndex);
 
// delete index
Drop dropIndex
		= SchemaBuilder.dropIndex("mykeyspace", "idx_col4")
                               .ifExists();
session.execute(dropIndex);
 
// delete table
Drop dropTable
		= SchemaBuilder.dropTable("mykeyspace", "mytable")
                               .ifExists();
session.execute(dropTable);

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326831695&siteId=291194637