Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Get started with the Azure Cosmos DB for Apache Cassandra client library for Go to store, manage, and query unstructured data. Follow the steps in this guide to create a new account, install a Go client library, connect to the account, perform common operations, and query your final sample data.
API reference documentation | Library source code | Package (Go)
Prerequisites
An Azure subscription
- If you don't have an Azure subscription, create a free account before you begin.
The latest version of the Azure CLI in Azure Cloud Shell.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
az login
command.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
Go
1.24 or newer
Setting up
First, set up the account and development environment for this guide. This section walks you through the process of creating an account, getting its credentials, and then preparing your development environment.
Create an account
Start by creating an API for Apache Cassandra account. Once the account is created, create the keyspace and table resources.
If you don't already have a target resource group, use the
az group create
command to create a new resource group in your subscription.az group create \ --name "<resource-group-name>" \ --location "<location>"
Use the
az cosmosdb create
command to create a new Azure Cosmos DB for Apache Cassandra account with default settings.az cosmosdb create \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --locations "regionName=<location>" \ --capabilities "EnableCassandra"
Create a new keyspace using
az cosmosdb cassandra keyspace create
namedcosmicworks
.az cosmosdb cassandra keyspace create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --name "cosmicworks"
Create a new JSON object to represent your schema using a multi-line Bash command. Then, use the
az cosmosdb cassandra table create
command to create a new table namedproducts
.schemaJson=$(cat <<EOF { "columns": [ { "name": "id", "type": "text" }, { "name": "name", "type": "text" }, { "name": "category", "type": "text" }, { "name": "quantity", "type": "int" }, { "name": "price", "type": "decimal" }, { "name": "clearance", "type": "boolean" } ], "partitionKeys": [ { "name": "id" } ] } EOF )
az cosmosdb cassandra table create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --keyspace-name "cosmicworks" \ --name "product" \ --schema "$schemaJson"
Get credentials
Now, get the password for the client library to use to create a connection to the recently created account.
Use
az cosmosdb show
to get the contact point and username for the account.az cosmosdb show \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --query "{username:name,contactPoint:documentEndpoint}"
Record the value of the
contactPoint
andusername
properties from the previous commands' output. These properties' values are the contact point and username you use later in this guide to connect to the account with the library.Use
az cosmosdb keys list
to get the keys for the account.az cosmosdb keys list \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --type "keys"
Record the value of the
primaryMasterKey
property from the previous commands' output. This property's value is the password you use later in this guide to connect to the account with the library.
Prepare development environment
Then, configure your development environment with a new project and the client library. This step is the last required prerequisite before moving on to the rest of this guide.
Start in an empty directory.
Create a new Go module.
go mod init quickstart
Import the
github.com/apache/cassandra-gocql-driver/v2
package from Go.go get github.com/apache/cassandra-gocql-driver/v2
Create the main.go file.
Add the Go application boilerplate.
package main func main() { }
Important
The remaining steps within this guide assume that you're adding your code within the
main
function.
Object model
Description | |
---|---|
Cluster |
Represents a specific connection to a cluster |
Session |
Entities that hold a specific connection to a cluster |
Code examples
Authenticate client
Start by authenticating the client using the credentials gathered earlier in this guide.
Open the main.go file in your integrated development environment (IDE).
Within the
main
function, import the following packages along with thegithub.com/apache/cassandra-gocql-driver/v2
package:context
crypto/tls
import ( "context" "crypto/tls" "github.com/apache/cassandra-gocql-driver/v2" )
Create string variables for the credentials collected earlier in this guide. Name the variables
username
,password
, andcontactPoint
.username := "<username>" password := "<password>" contactPoint := "<contact-point>"
Configure an instance of the
PasswordAuthenticator
type with the credentials specified in the previous steps. Store the result in a variable namedauthentication
.authentication := gocql.PasswordAuthenticator{ Username: username, Password: password, }
Configure an instance of
SslOptions
with a minimum version of Transport Layer Security (TLS) 1.2 and thecontactPoint
variable as the target server name. Store the result in a variable namedsslOptions
.sslOptions := &gocql.SslOptions{ Config: &tls.Config{ MinVersion: tls.VersionTLS12, ServerName: contactPoint, }, }
Create a new cluster specification using
NewCluster
and thecontactPoint
variable.cluster := gocql.NewCluster(contactPoint)
Configure the cluster specification object by using the credential and configuration variables created in the previous steps.
cluster.SslOpts = sslOptions cluster.Authenticator = authentication
Configure the remainder of the cluster specification object with these static values.
cluster.Keyspace = "cosmicworks" cluster.Port = 10350 cluster.ProtoVersion = 4
Create a new session that connects to the cluster using
CreateSession
.session, _ := cluster.CreateSession()
Configure the session to invoke the
Close
function after themain
function returns.defer session.Close()
Create a new
Background
context object and store it in thectx
variable.ctx := context.Background()
Warning
Complete transport layer security (TLS) validation is disabled in this guide to simplify authentication. For production deployments, fully enable validation.
Upsert data
Next, upsert new data into a table. Upserting ensures that the data is created or replaced appropriately depending on whether the same data already exists in the table.
Define a new type named
Product
with fields corresponding to the table created earlier in this guide.type Product struct { id string name string category string quantity int clearance bool }
Tip
In Go, you can create this type in another file or create it at the end of the existing file.
Create a new object of type
Product
. Store the object in a variable namedproduct
.product := Product { id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", name: "Yamba Surfboard", category: "gear-surf-surfboards", quantity: 12, clearance: false, }
Create a new string variable named
insertQuery
with the Cassandra Query Language (CQL) query for inserting a new row.insertQuery := ` INSERT INTO product (id, name, category, quantity, clearance) VALUES (?, ?, ?, ?, ?) `
Use the
Query
andExecContext
functions to run the query. Pass in various properties of theproduct
variable as query parameters._ = session.Query( insertQuery, product.id, product.name, product.category, product.quantity, product.clearance, ).ExecContext(ctx)
Read data
Then, read data that was previously upserted into the table.
Create a new string variable named
readQuery
with a CQL query that matches items with the sameid
field.readQuery := ` SELECT id, name, category, quantity, clearance FROM product WHERE id = ? LIMIT 1 `
Create a string variable named
id
with the same value as the product created earlier in this guide.id := "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"
Create another variable named
matchedProduct
to store the result of this operation in.var matchedProduct Product
Use the
Query
,Consistency
,IterContext
, andScan
functions together to find the single item that matches the query and assign its properties to thematchedProduct
variable.session.Query( readQuery, &id, ).Consistency(gocql.One).IterContext(ctx).Scan( &matchedProduct.id, &matchedProduct.name, &matchedProduct.category, &matchedProduct.quantity, &matchedProduct.clearance, )
Query data
Finally, use a query to find all data that matches a specific filter in the table.
Create string variables named
findQuery
andcategory
with the CQL query and required parameter.findQuery := ` SELECT id, name, category, quantity, clearance FROM product WHERE category = ? ALLOW FILTERING ` category := "gear-surf-surfboards"
Use the
Query
,Consistency
,IterContext
, andScanner
functions together to create a scanner that can iterate over multiple items that matches the query.queriedProducts := session.Query( findQuery, &category, ).Consistency(gocql.All).IterContext(ctx).Scanner()
Use the
Next
andScan
functions to iterate over the query results and assign the properties of each result to the innerqueriedProduct
variable.for queriedProducts.Next() { var queriedProduct Product queriedProducts.Scan( &queriedProduct.id, &queriedProduct.name, &queriedProduct.category, &queriedProduct.quantity, &queriedProduct.clearance, ) // Do something here with each result }
Run the code
Run the newly created application using a terminal in your application directory.
go run .
Clean up resources
Now, get the password for the client library to use to create a connection to the recently created account.
Use
az cosmosdb show
to get the contact point and username for the account.az cosmosdb show \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --query "{username:name,contactPoint:documentEndpoint}"
Record the value of the
contactPoint
andusername
properties from the previous commands' output. These properties' values are the contact point and username you use later in this guide to connect to the account with the library.Use
az cosmosdb keys list
to get the keys for the account.az cosmosdb keys list \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --type "keys"
Record the value of the
primaryMasterKey
property from the previous commands' output. This property's value is the password you use later in this guide to connect to the account with the library.