共用方式為


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

開始使用 Azure Cosmos DB 適用於 Apache Cassandra 的用戶端庫,來儲存、管理及查詢 Node.js 非結構化資料。 請依照本指南中的步驟建立新帳戶、安裝 Node.js 客戶端連結庫、連線到帳戶、執行一般作業,以及查詢最終範例數據。

API 參考文件 | 程式庫原始程式碼 | 套件 (npm)

先決條件

  • Azure 訂用帳戶

    • 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶
  • Node.js 22 或更新

設定

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

建立帳戶

首先,建立適用於 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. 將新的模組初始化。

    npm init es6 --yes
    
  3. 從 Node Package Manager npm 安裝 cassandra-driver 套件。

    npm install --save cassandra-driver
    
  4. 建立 index.js 檔案。

  1. 從空白目錄開始。

  2. 將新的模組初始化。

    npm init es6 --yes
    
  3. 從 Node Package Manager npm 安裝 typescript 套件。

    npm install --save-dev typescript
    
  4. 從 npm 安裝tsx套件。

    npm install --save-dev tsx
    
  5. 從 npm 安裝cassandra-driver套件。

    npm install --save cassandra-driver
    
  6. 使用編譯程式 (tsc) 初始化 TypeScript 專案。

    npx tsc --init --target es2017 --module es2022 --moduleResolution nodenext
    
  7. 建立 index.ts 檔案。

物件模型

說明
Client 表示叢集的特定連線
Mapper 用於執行查詢的 Cassandra 查詢語言 (CQL) 用戶端

程式碼範例

驗證用戶端

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

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

  2. 從模組匯入 cassandra-driver 下列型態:

    • cassandra
    • cassandra.Client
    • cassandra.mapping.Mapper
    • cassandra.auth.PlainTextAuthProvider
    import cassandra from 'cassandra-driver';
    
    const { Client } = cassandra;
    const { Mapper } = cassandra.mapping;
    const { PlainTextAuthProvider } = cassandra.auth;
    
  3. 為本指南稍早收集的認證建立字串常數變數。 將變數 username命名為 、 passwordcontactPoint

    const username = '<username>';
    const password = '<password>';
    const contactPoint = '<contact-point>';
    
  4. 針對您建立 Azure Cosmos DB for Apache Cassandra 帳戶所在的區域建立另一個字串變數。 將此變數 region命名為 。

    const region = '<azure-region>';
    
  5. 使用先前步驟中指定的認證建立新的 PlainTextAuthProvider 物件。

    let authProvider = new PlainTextAuthProvider(
        username,
        password
    );
    
  6. Client使用在先前步驟中建立的認證和組態變數來建立 物件。

    let client = new Client({
        contactPoints: [`${contactPoint}:10350`],
        authProvider: authProvider,
        localDataCenter: region,
        sslOptions: {
            secureProtocol: 'TLSv1_2_method'
        },
    });
    
  7. 以異步方式連線到叢集。

    await client.connect();
    
  8. 建立以cosmicworks keyspace和product數據表為目標的新映射器。 將對應程式命名為 Product

    const mapper = new Mapper(client, {
        models: {
            'Product': {
                tables: ['product'],
                keyspace: 'cosmicworks'
            }
        }
    });
    
  9. 使用forModel 函數和Product 映射器名稱生成映射器實例。

    const productMapper = mapper.forModel('Product');
    
  1. 在整合開發環境中開啟 index.ts 檔案(IDE)。

  2. 從模組匯入 cassandra-driver 下列型態:

    • cassandra.auth
    • cassandra.mapping
    • cassandra.types
    • cassandra.Client
    • cassandra.ClientOptions
    • cassandra.mapping.Mapper
    • cassandra.auth.PlainTextAuthProvider
    import { auth, mapping, types, Client, ClientOptions } from 'cassandra-driver';
    
    const { Mapper } = mapping;
    const { PlainTextAuthProvider } = auth;
    
  3. 為本指南稍早收集的認證建立字串常數變數。 將變數 username命名為 、 passwordcontactPoint

    const username: string = '<username>';
    const password: string = '<password>';
    const contactPoint: string = '<contact-point>';
    
  4. 針對您建立 Azure Cosmos DB for Apache Cassandra 帳戶所在的區域建立另一個字串變數。 將此變數 region命名為 。

    const region: string = '<azure-region>';
    
  5. 使用先前步驟中指定的認證建立新的 PlainTextAuthProvider 物件。

    let authProvider = new PlainTextAuthProvider(
        username,
        password
    );
    
  6. 使用選項建立匿名物件,以確保您使用傳輸層安全性 (TLS) 1.2 通訊協定。

    let sslOptions = {
        secureProtocol: 'TLSv1_2_method'
    };
    
  7. ClientOptions使用在先前步驟中建立的認證和組態變數來建立 物件。

    let clientOptions: ClientOptions = {
        contactPoints: [`${contactPoint}:10350`],
        authProvider: authProvider,
        localDataCenter: region,
        sslOptions: sslOptions
    };
    
  8. Client 建構函式中使用 clientOptions 變數建立物件。

    let client = new Client(clientOptions);
    
  9. 以異步方式連線到叢集。

    await client.connect();
    
  10. 建立以cosmicworks keyspace和product數據表為目標的新映射器。 將對應程式命名為 Product

    const mapper = new Mapper( client, {
        models: {
            'Product': {
                tables: ['product'],
                keyspace: 'cosmicworks'
            }
        }
    });
    
  11. 使用forModel 函數和Product 映射器名稱生成映射器實例。

    const productMapper = mapper.forModel('Product');
    

警告

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

更新插入資料

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

  1. 在名為 product的變數中建立新的物件。

    const product = {
        id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
        name: 'Yamba Surfboard',
        category: 'gear-surf-surfboards',
        quantity: 12,
        price: 850.00,
        clearance: false
    };
    
  2. 以異步方式調用函式 insert,並傳入於前一步中創建的變數 product

    await productMapper.insert(product);
    
  1. 定義名為 Product 的新介面,其中包含與本指南稍早建立之數據表對應的欄位。

    類型
    Id string
    Name string
    Category string
    Quantity int
    Price decimal
    Clearance bool
    interface Product {
        id: string;
        name: string;
        category: string;
        quantity: number;
        price: number;
        clearance: boolean;
    }
    

    小提示

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

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

    const product: Product = {
        id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
        name: 'Yamba Surfboard',
        category: 'gear-surf-surfboards',
        quantity: 12,
        price: 850.00,
        clearance: false
    };
    
  3. 以異步方式調用函式 insert,並傳入於前一步中創建的變數 product

    await productMapper.insert(product);
    

讀取資料

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

  1. 建立名為 的 filter匿名物件。 在此物件中,包含名為 id 的屬性,其值與本指南稍早建立的產品相同。

    const filter = {
        id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb'
    };
    
  2. 呼叫地圖器的get函式並傳入filter變數。 將結果儲存在名為 matchedProduct 的變數中。

    let matchedProduct = await productMapper.get(filter);
    
  1. 建立名為 的 filter匿名物件。 在此物件中,包含名為 id 的屬性,其值與本指南稍早建立的產品相同。

    const filter = {
        id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb'
    };
    
  2. 呼叫地圖器的get函式並傳入filter變數。 將結果儲存在名為 matchedProductProduct類型的變數中。

    let matchedProduct: Product = await productMapper.get(filter);
    

查詢數據

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

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

    const query = `
    SELECT
        *
    FROM
        cosmicworks.product
    WHERE
        category = :category
    ALLOW FILTERING
    `;
    
  2. 建立名為 的 params匿名物件。 在此物件中,包含名為 category 的屬性,其值與本指南稍早建立的產品相同。

    const params = {
        category: 'gear-surf-surfboards'
    };
    
  3. 以異步方式調用 execute 函式,並將 queryparams 變數作為參數傳入。 將結果的屬性 rows 儲存為名為的 matchedProducts變數。

    let { rows: matchedProducts } = await client.execute(query, params);
    
  4. 藉由調用產品陣列中的 foreach 方法,迭代查詢結果。

    matchedProducts.forEach(product => {
        // Do something here with each result
    });
    
  1. 建立一個名為 CQL 查詢的新 query 字串變數,以匹配具有相同 category 欄位的項目。

    const query: string = `
    SELECT
        *
    FROM
        cosmicworks.product
    WHERE
        category = :category
    ALLOW FILTERING
    `;
    
  2. 建立名為 的 params匿名物件。 在此物件中,包含名為 category 的屬性,其值與本指南稍早建立的產品相同。

    const params = {
        category: 'gear-surf-surfboards'
    };
    
  3. 以異步方式調用 execute 函式,並將 queryparams 變數作為參數傳入。 將結果儲存在名為 resulttypes.ResultSet類型的變數中。

    let result: types.ResultSet = await client.execute(query, params);
    
  4. 將結果的 rows 屬性儲存為 名為 matchedProductsProduct[]的變數。

    let matchedProducts: Product[] = result.rows;
    
  5. 藉由調用產品陣列中的 foreach 方法,迭代查詢結果。

    matchedProducts.forEach((product: Product) => {
        // Do something here with each result
    });
    

執行程式碼

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

node index.js
npx tsx index.ts

清理資源

當您不再需要帳戶時,請從 Azure 訂用帳戶中移除帳戶,方法是 刪除 該資源。

az cosmosdb delete \
    --resource-group "<resource-group-name>" \
    --name "<account-name>"

後續步驟