你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
开始使用适用于 Node.js 的 Azure Cosmos DB for Apache Cassandra 客户端库,以存储、管理和查询非结构化数据。 按照本指南中的步骤创建新帐户、安装 Node.js 客户端库、连接到帐户、执行常见作以及查询最终示例数据。
先决条件
Azure 订阅服务
- 如果没有 Azure 订阅,请在开始之前创建一个免费帐户。
Azure Cloud Shell 中最新版本的 Azure CLI。
- 如果想要在本地运行 CLI 引用命令,请使用
az login
该命令登录到 Azure CLI。
- 如果想要在本地运行 CLI 引用命令,请使用
- Node.js 22 或更高版本
设置
首先,为本指南设置帐户和开发环境。 本部分将指导你完成创建帐户、获取其凭据以及准备开发环境的过程。
创建帐户
首先,创建用于 Apache Cassandra 帐户的 API。 创建帐户后,创建密钥空间和表资源。
- Azure CLI
- Azure 门户
如果还没有目标资源组,请使用
az group create
命令在订阅中创建新的资源组。az group create \ --name "<resource-group-name>" \ --location "<location>"
使用
az cosmosdb create
命令来创建一个具有默认设置的适用于Apache Cassandra的新Azure Cosmos DB帐户。az cosmosdb create \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --locations "regionName=<location>" \ --capabilities "EnableCassandra"
使用
az cosmosdb cassandra keyspace create
命名的cosmicworks
创建新的密钥空间。az cosmosdb cassandra keyspace create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --name "cosmicworks"
使用多行 Bash 命令创建新的 JSON 对象来表示架构。 然后,使用
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"
获取凭据
现在,获取用于创建与最近创建的帐户的连接的客户端库的密码。
- Azure CLI
- Azure 门户
使用
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
从节点包管理器 (npm) 安装
cassandra-driver
包。npm install --save cassandra-driver
创建 index.js 文件。
从空目录中开始。
初始化新模块。
npm init es6 --yes
从节点包管理器 (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 文件。
对象模型
DESCRIPTION | |
---|---|
Client |
表示与群集的特定连接 |
Mapper |
用于运行查询的 Cassandra 查询语言 (CQL) 客户端 |
代码示例
对客户端进行身份验证
首先,使用本指南前面收集的凭据对客户端进行身份验证。
在集成开发环境中打开 index.js 文件(IDE)。
从
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;
为本指南前面收集的凭据创建字符串常量变量。 为变量
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();
创建面向
cosmicworks
键空间和product
表的新映射器。 将映射器Product
命名为 。const mapper = new Mapper(client, { models: { 'Product': { tables: ['product'], keyspace: 'cosmicworks' } } });
使用
forModel
函数和Product
映射器名称生成映射器实例。const productMapper = mapper.forModel('Product');
在集成开发环境(IDE)中打开 index.ts 文件。
从
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;
为本指南前面收集的凭据创建字符串常量变量。 为变量
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();
创建面向
cosmicworks
键空间和product
表的新映射器。 将映射器Product
命名为 。const mapper = new Mapper( client, { models: { 'Product': { tables: ['product'], keyspace: 'cosmicworks' } } });
使用
forModel
函数和Product
映射器名称生成映射器实例。const productMapper = mapper.forModel('Product');
警告
本指南中禁用了完整的传输层安全性(TLS)验证,以简化身份验证。 对于生产部署,请完全启用验证。
更新插入数据
接下来,将新数据插入或更新到表中。 Upserting 可确保根据表中是否已存在相同的数据,适当地创建或替换数据。
在名为
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
的新接口,其字段与本指南前面创建的表对应。类型 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中,可以在另一个文件中创建此类型,也可以在现有文件的末尾创建它。
创建一个
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' };
调用传入
filter
变量的映射器的get
函数。 将结果存储在一个名为matchedProduct
类型的Product
变量中。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
作为参数。 将结果存储在一个名为result
类型的types.ResultSet
变量中。let result: types.ResultSet = await client.execute(query, params);
将结果
rows
的属性存储为一个名为matchedProducts
类型的Product[]
变量。let matchedProducts: Product[] = result.rows;
通过对产品数组调用
foreach
方法来循环访问查询结果。matchedProducts.forEach((product: Product) => { // Do something here with each result });
运行代码
使用应用程序目录中的终端运行新创建的应用程序。
node index.js
npx tsx index.ts
清理资源
如果不再需要此帐户,请通过删除资源来从 Azure 订阅中删除该帐户。
- Azure CLI
- Azure 门户
az cosmosdb delete \
--resource-group "<resource-group-name>" \
--name "<account-name>"