共用方式為


快速入門:適用於 Go 的 Azure Cosmos DB for Apache Cassandra 用戶端程式庫

開始使用 適用於 Apache Cassandra 的 Azure Cosmos DB 用戶端程式庫 Go,以儲存、管理和查詢非結構化資料。 依照本指南中的步驟建立新帳戶、安裝 Go 用戶端程式庫、連線到帳戶、執行常見操作,以及查詢最終範例資料。

API 參考檔 | 連結庫原始程式碼 | 套件 (Go)

先決條件

  • Azure 訂用帳戶

    • 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶
  • Go 1.24 或更新版本

設定

首先,設定本指南的帳號和開發環境。 本節將引導您進行創建帳戶、獲取其憑證,然後準備開發環境。

建立帳戶

首先,建立適用於 Apache Cassandra 帳戶的 API。 建立帳戶之後,請建立金鑰空間和資料表資源。

  1. 如果您還沒有目標資源群組,請使用命令 az group create 在訂用帳戶中建立新的資源群組。

    az group create \
        --name "<resource-group-name>" \
        --location "<location>"
    
  2. 使用 az cosmosdb create 命令,新建具有預設設定的 Azure Cosmos DB Apache Cassandra 帳戶。

    az cosmosdb create \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --locations "regionName=<location>" \
        --capabilities "EnableCassandra"
    
  3. 使用 az cosmosdb cassandra keyspace create 名為 cosmicworks建立新的keyspace。

    az cosmosdb cassandra keyspace create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --name "cosmicworks"
    
  4. 建立新的 JSON 物件,以使用多行 Bash 命令來代表您的結構描述。 然後,使用 az cosmosdb cassandra table create 命令來建立名為 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"
    

取得認證

現在,取得客戶端程式庫所需的密碼,以建立與最近創建的帳戶的連接。

  1. 使用 az cosmosdb show 來取得帳戶的聯絡點和使用者名稱。

    az cosmosdb show \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --query "{username:name,contactPoint:documentEndpoint}"
    
  2. 記錄先前命令輸出中contactPointusername屬性的值。 這些屬性的值是您在本指南稍後用來連線至資料庫帳戶的 聯絡點使用者名稱

  3. 使用 az cosmosdb keys list 可獲得帳戶的 金鑰

    az cosmosdb keys list \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --type "keys"
    
  4. 記錄先前命令輸出中屬性 primaryMasterKey 的值。 此屬性的值是您在本指南稍後用來連線至程式庫帳戶的 密碼

準備開發環境

然後,使用新專案和用戶端程式庫來設定您的開發環境。 此步驟是繼續本指南其餘部分之前的最後一個必要先決條件。

  1. 從空白目錄開始。

  2. 建立新的 Go 模組。

    go mod init quickstart
    
  3. 從 Go 匯入 github.com/apache/cassandra-gocql-driver/v2 套件。

    go get github.com/apache/cassandra-gocql-driver/v2
    
  4. 建立 main.go 檔案。

  5. 新增 Go 應用程式樣板。

    package main
    
    func main() {    
    }
    

    這很重要

    本指南中的其餘步驟假設您要在函式中 main 新增程式碼。

物件模型

說明
Cluster 表示叢集的特定連線
Session 保持與叢集專屬連線的實體

程式碼範例

驗證用戶端

首先,使用本指南稍早收集的認證來驗證用戶端。

  1. 在整合開發環境 (IDE) 中開啟 main.go 檔案。

  2. main 函式中,匯入下列套件以及 github.com/apache/cassandra-gocql-driver/v2 套件:

    • context
    • crypto/tls
    import (
        "context"
        "crypto/tls"
        "github.com/apache/cassandra-gocql-driver/v2"
    )
    
  3. 為本指南稍早收集的認證建立字串變數。 將變數 username命名為 、 passwordcontactPoint

    username := "<username>"
    password := "<password>"
    contactPoint := "<contact-point>"
    
  4. 設定PasswordAuthenticator類型的執行個體,使用先前步驟中指定的認證。 將結果儲存在名為 authentication 的變數中。

    authentication := gocql.PasswordAuthenticator{
        Username: username,
        Password: password,
    }
    
  5. 使用最低版本的傳輸層安全性 (TLS) 1.2 配置 的 SslOptions 實例,並將 contactPoint 變數作為目標伺服器名稱。 將結果儲存在名為 sslOptions 的變數中。

    sslOptions := &gocql.SslOptions{
        Config: &tls.Config{
            MinVersion: tls.VersionTLS12,
            ServerName: contactPoint,
        },
    }
    
  6. 使用 NewClustercontactPoint 變數建立新的叢集規格。

    cluster := gocql.NewCluster(contactPoint)
    
  7. 使用先前步驟中建立的認證和組態變數來設定叢集規格物件。

    cluster.SslOpts = sslOptions
    cluster.Authenticator = authentication
    
  8. 使用這些靜態值設定叢集規格物件的其餘部分。

    cluster.Keyspace = "cosmicworks"
    cluster.Port = 10350
    cluster.ProtoVersion = 4    
    
  9. 使用 CreateSession 建立連線到叢集的新工作階段。

    session, _ := cluster.CreateSession()
    
  10. 設定工作階段以在 Close 函式傳回之後叫用 main 函式。

    defer session.Close()
    
  11. 建立新的 Background 上下文物件並將其儲存在變數中 ctx

    ctx := context.Background()
    

警告

本指南已停用完整的傳輸層安全性 (TLS) 驗證,以簡化驗證。 針對生產環境部署,請完全啟用驗證。

更新插入資料

接下來,將新資料「更新或插入」到資料表中。 更新插入可確保根據資料表中是否已存在相同的資料,適當地建立或取代資料。

  1. 定義一個名為 Product 的新型別,其欄位對應到本指引中先前建立的資料表。

    type Product struct {
        id        string
        name      string
        category  string
        quantity  int
        clearance bool
    }
    

    小提示

    在 Go 中,您可以在另一個檔案中建立此類型,或在現有檔案的結尾建立它。

  2. 建立類型的 Product新物件。 將物件儲存在名為 product的變數中。

    product := Product {
        id:        "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
        name:      "Yamba Surfboard",
        category:  "gear-surf-surfboards",
        quantity:  12,
        clearance: false,
    }
    
  3. 建立以 Cassandra 查詢語言 (CQL) 查詢命名 insertQuery 的新字串變數,以插入新資料列。

    insertQuery := `
        INSERT INTO
            product (id, name, category, quantity, clearance)
        VALUES
            (?, ?, ?, ?, ?)
    `
    
  4. 使用 and QueryExecContext 函數來執行查詢。 將變數的 product 各種屬性作為查詢參數傳入。

    _ = session.Query(
        insertQuery,
        product.id, 
        product.name, 
        product.category, 
        product.quantity, 
        product.clearance,
    ).ExecContext(ctx)
    

讀取資料

然後,讀取先前更新插入資料表的資料。

  1. 建立一個名為 CQL 查詢的新 readQuery 字串變數,以匹配具有相同 id 欄位的項目。

    readQuery := `
        SELECT
            id,
            name,
            category,
            quantity,
            clearance
        FROM
            product
        WHERE id = ?
        LIMIT 1
    `
    
  2. 建立一個字串變數,其值 id 與本指南稍早建立的產品具有相同的值。

    id := "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb" 
    
  3. 建立另一個名為 matchedProduct 的變數,以儲存此作業的結果。

    var matchedProduct Product
    
  4. 結合使用QueryConsistencyIterContextScan函數來尋找符合查詢的單一項目,並將其屬性指定給matchedProduct變數。

    session.Query(
        readQuery,
        &id,
    ).Consistency(gocql.One).IterContext(ctx).Scan(
        &matchedProduct.id,
        &matchedProduct.name,
        &matchedProduct.category,
        &matchedProduct.quantity,
        &matchedProduct.clearance,
    )
    

查詢數據

最後,使用查詢來尋找與表中特定篩選器相符的所有資料。

  1. 建立名為findQuerycategory的字串變數,並搭配 CQL 查詢和必要參數。

    findQuery := `
        SELECT
            id,
            name,
            category,
            quantity,
            clearance
        FROM
            product
        WHERE
            category = ?
        ALLOW FILTERING
    `
    
    category := "gear-surf-surfboards"
    
  2. 一起使用 QueryConsistencyIterContextScanner 函式建立掃描程式,以逐一查看符合查詢的多個項目。

    queriedProducts := session.Query(
        findQuery, 
        &category,
    ).Consistency(gocql.All).IterContext(ctx).Scanner()
    
  3. 使用NextScan函數來迭代查詢結果,並將每個結果的屬性指派至queriedProduct變數。

    for queriedProducts.Next() {
        var queriedProduct Product
        queriedProducts.Scan(
            &queriedProduct.id,
            &queriedProduct.name,
            &queriedProduct.category,
            &queriedProduct.quantity,
            &queriedProduct.clearance,
        )
        // Do something here with each result
    }
    

執行程式碼

使用應用程式目錄中的終端機執行新建立的應用程式。

go run .

清理資源

現在,取得客戶端程式庫所需的密碼,以建立與最近創建的帳戶的連接。

  1. 使用 az cosmosdb show 來取得帳戶的聯絡點和使用者名稱。

    az cosmosdb show \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --query "{username:name,contactPoint:documentEndpoint}"
    
  2. 記錄先前命令輸出中contactPointusername屬性的值。 這些屬性的值是您在本指南稍後用來連線至資料庫帳戶的 聯絡點使用者名稱

  3. 使用 az cosmosdb keys list 可獲得帳戶的 金鑰

    az cosmosdb keys list \
        --resource-group "<resource-group-name>" \
        --name "<account-name>" \
        --type "keys"
    
  4. 記錄先前命令輸出中屬性 primaryMasterKey 的值。 此屬性的值是您在本指南稍後用來連線至程式庫帳戶的 密碼

後續步驟