Java querying
A simple query can be performed by passing a CQL query to the client using the
ExecuteQuery()
function for standard query execution:
QueryOuterClass.Response queryString = blockingStub.executeQuery(QueryOuterClass
.Query.newBuilder()
.setCql("SELECT firstname, lastname FROM test.users")
.build());
Data definition (DDL) queries are supported in the same manner:
blockingStub.executeQuery(
QueryOuterClass.Query.newBuilder()
.setCql(""
+ "CREATE KEYSPACE IF NOT EXISTS test "
+ "WITH REPLICATION = {"
+ " 'class' : 'SimpleStrategy', "
+ " 'replication_factor' : 1"
+ "};")
.build());
System.out.println("Keyspace 'test' has been created.");
blockingStub.executeQuery(
QueryOuterClass.Query.newBuilder()
.setCql("CREATE TABLE IF NOT EXISTS test.users (firstname text PRIMARY KEY, lastname text);")
.build());
System.out.println("Table 'users' has been created.");
In general, users will create a keyspace and table first.
If you would like to use a
batch statement,
the client also provides an ExecuteBatch()
function to execute a batch query:
blockingStub.executeBatch(
QueryOuterClass.Batch.newBuilder()
.addQueries(
QueryOuterClass.BatchQuery.newBuilder()
.setCql("INSERT INTO test.users (firstname, lastname) VALUES('Jane', 'Doe')")
.build())
.addQueries(
QueryOuterClass.BatchQuery.newBuilder()
.setCql("INSERT INTO test.users (firstname, lastname) VALUES('Serge', 'Provencio')")
.build())
.build());
System.out.println("2 rows have been inserted in table users.");
The ExecuteQuery
function can be used to execute a single query.
This example inserts two values into the keyspace table test.users
.
Only INSERT
, UPDATE
, and DELETE
operations can be used in a batch query.