Modifica

Condividi tramite


Quickstart: Azure Cosmos DB for Apache Cassandra client library for Go

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.
  • 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.

  1. 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>"
    
  2. 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"
    
  3. Create a new keyspace using az cosmosdb cassandra keyspace create named cosmicworks.

    az cosmosdb cassandra keyspace create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --name "cosmicworks"
    
  4. 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 named products.

    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.

  1. 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}"
    
  2. Record the value of the contactPoint and username 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.

  3. 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"
    
  4. 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.

  1. Start in an empty directory.

  2. Create a new Go module.

    go mod init quickstart
    
  3. Import the github.com/apache/cassandra-gocql-driver/v2 package from Go.

    go get github.com/apache/cassandra-gocql-driver/v2
    
  4. Create the main.go file.

  5. 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.

  1. Open the main.go file in your integrated development environment (IDE).

  2. Within the main function, import the following packages along with the github.com/apache/cassandra-gocql-driver/v2 package:

    • context
    • crypto/tls
    import (
        "context"
        "crypto/tls"
        "github.com/apache/cassandra-gocql-driver/v2"
    )
    
  3. Create string variables for the credentials collected earlier in this guide. Name the variables username, password, and contactPoint.

    username := "<username>"
    password := "<password>"
    contactPoint := "<contact-point>"
    
  4. Configure an instance of the PasswordAuthenticator type with the credentials specified in the previous steps. Store the result in a variable named authentication.

    authentication := gocql.PasswordAuthenticator{
        Username: username,
        Password: password,
    }
    
  5. Configure an instance of SslOptions with a minimum version of Transport Layer Security (TLS) 1.2 and the contactPoint variable as the target server name. Store the result in a variable named sslOptions.

    sslOptions := &gocql.SslOptions{
        Config: &tls.Config{
            MinVersion: tls.VersionTLS12,
            ServerName: contactPoint,
        },
    }
    
  6. Create a new cluster specification using NewCluster and the contactPoint variable.

    cluster := gocql.NewCluster(contactPoint)
    
  7. Configure the cluster specification object by using the credential and configuration variables created in the previous steps.

    cluster.SslOpts = sslOptions
    cluster.Authenticator = authentication
    
  8. Configure the remainder of the cluster specification object with these static values.

    cluster.Keyspace = "cosmicworks"
    cluster.Port = 10350
    cluster.ProtoVersion = 4    
    
  9. Create a new session that connects to the cluster using CreateSession.

    session, _ := cluster.CreateSession()
    
  10. Configure the session to invoke the Close function after the main function returns.

    defer session.Close()
    
  11. Create a new Background context object and store it in the ctx 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.

  1. 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.

  2. Create a new object of type Product. Store the object in a variable named product.

    product := Product {
        id:        "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
        name:      "Yamba Surfboard",
        category:  "gear-surf-surfboards",
        quantity:  12,
        clearance: false,
    }
    
  3. 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
            (?, ?, ?, ?, ?)
    `
    
  4. Use the Query and ExecContext functions to run the query. Pass in various properties of the product 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.

  1. Create a new string variable named readQuery with a CQL query that matches items with the same id field.

    readQuery := `
        SELECT
            id,
            name,
            category,
            quantity,
            clearance
        FROM
            product
        WHERE id = ?
        LIMIT 1
    `
    
  2. Create a string variable named id with the same value as the product created earlier in this guide.

    id := "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb" 
    
  3. Create another variable named matchedProduct to store the result of this operation in.

    var matchedProduct Product
    
  4. Use the Query, Consistency, IterContext, and Scan functions together to find the single item that matches the query and assign its properties to the matchedProduct 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.

  1. Create string variables named findQuery and category with the CQL query and required parameter.

    findQuery := `
        SELECT
            id,
            name,
            category,
            quantity,
            clearance
        FROM
            product
        WHERE
            category = ?
        ALLOW FILTERING
    `
    
    category := "gear-surf-surfboards"
    
  2. Use the Query, Consistency, IterContext, and Scanner 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()
    
  3. Use the Next and Scan functions to iterate over the query results and assign the properties of each result to the inner queriedProduct 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.

  1. 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}"
    
  2. Record the value of the contactPoint and username 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.

  3. 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"
    
  4. 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.

Next step