Go querying
A simple query can be performed by passing a CQL query to the client using the
ExecuteQuery()
function for standard query execution:
selectQuery := &pb.Query{
Cql: "SELECT firstname, lastname FROM test.users;",
}
response, err := stargateClient.ExecuteQuery(selectQuery)
if err != nil {
fmt.Printf("error executing query %v", err)
return
}
fmt.Printf("select executed\n")
Data definition (DDL) queries are supported in the same manner:
// Create a new keyspace
createKeyspaceQuery := &pb.Query{
Cql: "CREATE KEYSPACE IF NOT EXISTS test WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : 1};",
}
_, err = stargateClient.ExecuteQuery(createKeyspaceQuery)
if err != nil {
fmt.Printf("error creating keyspace %v", err)
return
}
fmt.Printf("made keyspace\n")
// Create a new table
createTableQuery := &pb.Query{
Cql: "CREATE TABLE IF NOT EXISTS test.users (firstname text PRIMARY KEY, lastname text);",
}
_, err = stargateClient.ExecuteQuery(createTableQuery)
if err != nil {
fmt.Printf("error creating table %v", err)
return
}
fmt.Printf("made table \n")
In general, users will create a keyspace and table first.
Parameterized queries are also supported:
any, err := anypb.New(
&pb.Values{
Values: []*pb.Value{
{Inner: &pb.Value_String_{String_: "system"}},
},
},
)
if err != nil {
return err
}
// read from table
query := &pb.Query{
Cql: "SELECT * FROM system_schema.keyspaces WHERE keyspace_name = ?",
Values: &pb.Values{
Values: []*pb.Value{
{Inner: &pb.Value_String_{String_: "system"}},
},
},
Parameters: &pb.QueryParameters{
Tracing: false,
SkipMetadata: false,
},
}
response, err := stargateClient.ExecuteQuery(query)
The ExecuteQuery
function can be used to execute a single query.
If you need to group several commands together as a
batch statement,
the client also provides an ExecuteBatch()
function to execute a batch query:
batch := &pb.Batch{
Type: pb.Batch_LOGGED,
Queries: []*pb.BatchQuery{
{
Cql: "INSERT INTO test.users (firstname, lastname) VALUES ('Lorina', 'Poland');",
},
{
Cql: "INSERT INTO test.users (firstname, lastname) VALUES ('Ronnie', 'Miller');",
},
},
}
_, err = stargateClient.ExecuteBatch(batch)
if err != nil {
fmt.Printf("error creating batch %v", err)
return
}
fmt.Printf("insert data\n")
This example inserts two values into the keyspace table test.users
.
Only INSERT
, UPDATE
, and DELETE
operations can be used in a batch query.