開始使用 Azure Cosmos DB 適用於 Apache Cassandra 的用戶端庫,來儲存、管理及查詢 Node.js 非結構化資料。 請依照本指南中的步驟建立新帳戶、安裝 Node.js 客戶端連結庫、連線到帳戶、執行一般作業,以及查詢最終範例數據。
API 參考文件 | 程式庫原始程式碼 | 套件 (npm)
先決條件
Azure 訂用帳戶
- 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶。
Azure Cloud Shell 中最新版的 Azure CLI。
- 如果您想要在本機執行 CLI 參考命令,請使用
az login命令登入 Azure CLI。
- 如果您想要在本機執行 CLI 參考命令,請使用
- Node.js 22 或更新
設定
首先,設定本指南的帳號和開發環境。 本節將引導您進行創建帳戶、獲取其憑證,然後準備開發環境。
建立帳戶
首先,建立適用於 Apache Cassandra 帳戶的 API。 建立帳戶之後,請建立金鑰空間和資料表資源。
如果您還沒有目標資源群組,請使用命令
az group create在訂用帳戶中建立新的資源群組。az group create \ --name "<resource-group-name>" \ --location "<location>"使用
az cosmosdb create命令,新建具有預設設定的 Azure Cosmos DB Apache Cassandra 帳戶。az cosmosdb create \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --locations "regionName=<location>" \ --capabilities "EnableCassandra"使用
az cosmosdb cassandra keyspace create名為cosmicworks建立新的keyspace。az cosmosdb cassandra keyspace create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --name "cosmicworks"建立新的 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"
取得認證
現在,取得客戶端程式庫所需的密碼,以建立與最近創建的帳戶的連接。
使用
az cosmosdb show來取得帳戶的聯絡點和使用者名稱。az cosmosdb show \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --query "{username:name,contactPoint:documentEndpoint}"記錄先前命令輸出中
contactPoint和username屬性的值。 這些屬性的值是您在本指南稍後用來連線至資料庫帳戶的 聯絡點 和 使用者名稱 。使用
az cosmosdb keys list可獲得帳戶的 金鑰 。az cosmosdb keys list \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --type "keys"記錄先前命令輸出中屬性
primaryMasterKey的值。 此屬性的值是您在本指南稍後用來連線至程式庫帳戶的 密碼 。
準備開發環境
然後,使用新專案和用戶端程式庫來設定您的開發環境。 此步驟是繼續本指南其餘部分之前的最後一個必要先決條件。
從空白資料夾中開始。
將新的模組初始化。
npm init es6 --yes從 Node Package Manager npm 安裝
cassandra-driver套件。npm install --save cassandra-driver建立 index.js 檔案。
從空白目錄開始。
將新的模組初始化。
npm init es6 --yes從 Node Package Manager npm 安裝
typescript套件。npm install --save-dev typescript從 npm 安裝
tsx套件。npm install --save-dev tsx從 npm 安裝
cassandra-driver套件。npm install --save cassandra-driver使用編譯程式 (
tsc) 初始化 TypeScript 專案。npx tsc --init --target es2017 --module es2022 --moduleResolution nodenext建立 index.ts 檔案。
物件模型
| 說明 | |
|---|---|
Client |
表示叢集的特定連線 |
Mapper |
用於執行查詢的 Cassandra 查詢語言 (CQL) 用戶端 |
程式碼範例
驗證用戶端
首先,使用本指南稍早收集的認證來驗證用戶端。
在整合開發環境中開啟 index.js 檔案(IDE)。
從模組匯入
cassandra-driver下列型態:cassandracassandra.Clientcassandra.mapping.Mappercassandra.auth.PlainTextAuthProvider
import cassandra from 'cassandra-driver'; const { Client } = cassandra; const { Mapper } = cassandra.mapping; const { PlainTextAuthProvider } = cassandra.auth;為本指南稍早收集的認證建立字串常數變數。 將變數
username命名為 、password和contactPoint。const username = '<username>'; const password = '<password>'; const contactPoint = '<contact-point>';針對您建立 Azure Cosmos DB for Apache Cassandra 帳戶所在的區域建立另一個字串變數。 將此變數
region命名為 。const region = '<azure-region>';使用先前步驟中指定的認證建立新的
PlainTextAuthProvider物件。let authProvider = new PlainTextAuthProvider( username, password );Client使用在先前步驟中建立的認證和組態變數來建立 物件。let client = new Client({ contactPoints: [`${contactPoint}:10350`], authProvider: authProvider, localDataCenter: region, sslOptions: { secureProtocol: 'TLSv1_2_method' }, });以異步方式連線到叢集。
await client.connect();建立以
cosmicworkskeyspace和product數據表為目標的新映射器。 將對應程式命名為Product。const mapper = new Mapper(client, { models: { 'Product': { tables: ['product'], keyspace: 'cosmicworks' } } });使用
forModel函數和Product映射器名稱生成映射器實例。const productMapper = mapper.forModel('Product');
在整合開發環境中開啟 index.ts 檔案(IDE)。
從模組匯入
cassandra-driver下列型態:cassandra.authcassandra.mappingcassandra.typescassandra.Clientcassandra.ClientOptionscassandra.mapping.Mappercassandra.auth.PlainTextAuthProvider
import { auth, mapping, types, Client, ClientOptions } from 'cassandra-driver'; const { Mapper } = mapping; const { PlainTextAuthProvider } = auth;為本指南稍早收集的認證建立字串常數變數。 將變數
username命名為 、password和contactPoint。const username: string = '<username>'; const password: string = '<password>'; const contactPoint: string = '<contact-point>';針對您建立 Azure Cosmos DB for Apache Cassandra 帳戶所在的區域建立另一個字串變數。 將此變數
region命名為 。const region: string = '<azure-region>';使用先前步驟中指定的認證建立新的
PlainTextAuthProvider物件。let authProvider = new PlainTextAuthProvider( username, password );使用選項建立匿名物件,以確保您使用傳輸層安全性 (TLS) 1.2 通訊協定。
let sslOptions = { secureProtocol: 'TLSv1_2_method' };ClientOptions使用在先前步驟中建立的認證和組態變數來建立 物件。let clientOptions: ClientOptions = { contactPoints: [`${contactPoint}:10350`], authProvider: authProvider, localDataCenter: region, sslOptions: sslOptions };在
Client建構函式中使用clientOptions變數建立物件。let client = new Client(clientOptions);以異步方式連線到叢集。
await client.connect();建立以
cosmicworkskeyspace和product數據表為目標的新映射器。 將對應程式命名為Product。const mapper = new Mapper( client, { models: { 'Product': { tables: ['product'], keyspace: 'cosmicworks' } } });使用
forModel函數和Product映射器名稱生成映射器實例。const productMapper = mapper.forModel('Product');
警告
本指南已停用完整的傳輸層安全性 (TLS) 驗證,以簡化驗證。 針對生產環境部署,請完全啟用驗證。
更新插入資料
接下來,將新資料「更新或插入」到資料表中。 更新插入可確保根據資料表中是否已存在相同的資料,適當地建立或取代資料。
在名為
product的變數中建立新的物件。const product = { id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', name: 'Yamba Surfboard', category: 'gear-surf-surfboards', quantity: 12, price: 850.00, clearance: false };以異步方式調用函式
insert,並傳入於前一步中創建的變數product。await productMapper.insert(product);
定義名為
Product的新介面,其中包含與本指南稍早建立之數據表對應的欄位。類型 IdstringNamestringCategorystringQuantityintPricedecimalClearanceboolinterface Product { id: string; name: string; category: string; quantity: number; price: number; clearance: boolean; }小提示
在 Node.js中,您可以在另一個檔案中建立此類型,或在現有檔案結尾建立它。
建立類型的
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 };以異步方式調用函式
insert,並傳入於前一步中創建的變數product。await productMapper.insert(product);
讀取資料
然後,讀取先前更新插入資料表的資料。
建立名為 的
filter匿名物件。 在此物件中,包含名為id的屬性,其值與本指南稍早建立的產品相同。const filter = { id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb' };呼叫地圖器的
get函式並傳入filter變數。 將結果儲存在名為matchedProduct的變數中。let matchedProduct = await productMapper.get(filter);
建立名為 的
filter匿名物件。 在此物件中,包含名為id的屬性,其值與本指南稍早建立的產品相同。const filter = { id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb' };呼叫地圖器的
get函式並傳入filter變數。 將結果儲存在名為matchedProductProduct類型的變數中。let matchedProduct: Product = await productMapper.get(filter);
查詢數據
最後,使用查詢來尋找與表中特定篩選器相符的所有資料。
建立一個名為 CQL 查詢的新
query字串變數,以匹配具有相同category欄位的項目。const query = ` SELECT * FROM cosmicworks.product WHERE category = :category ALLOW FILTERING `;建立名為 的
params匿名物件。 在此物件中,包含名為category的屬性,其值與本指南稍早建立的產品相同。const params = { category: 'gear-surf-surfboards' };以異步方式調用
execute函式,並將query和params變數作為參數傳入。 將結果的屬性rows儲存為名為的matchedProducts變數。let { rows: matchedProducts } = await client.execute(query, params);藉由調用產品陣列中的
foreach方法,迭代查詢結果。matchedProducts.forEach(product => { // Do something here with each result });
建立一個名為 CQL 查詢的新
query字串變數,以匹配具有相同category欄位的項目。const query: string = ` SELECT * FROM cosmicworks.product WHERE category = :category ALLOW FILTERING `;建立名為 的
params匿名物件。 在此物件中,包含名為category的屬性,其值與本指南稍早建立的產品相同。const params = { category: 'gear-surf-surfboards' };以異步方式調用
execute函式,並將query和params變數作為參數傳入。 將結果儲存在名為resulttypes.ResultSet類型的變數中。let result: types.ResultSet = await client.execute(query, params);將結果的
rows屬性儲存為 名為matchedProductsProduct[]的變數。let matchedProducts: Product[] = result.rows;藉由調用產品陣列中的
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>"