快速入门:使用 Node.js 和 Azure Cosmos DB 构建 API for Table 应用

适用对象:

在本快速入门中,我们将创建一个 Azure Cosmos DB for Table 帐户,并使用从 GitHub 克隆的数据资源管理器和 Node.js 应用创建表和条目。 Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。

先决条件

示例应用程序

可以从存储库 https://github.com/Azure-Samples/msdocs-azure-data-tables-sdk-js 克隆或下载本教程的示例应用程序。 入门应用和完整应用都包含在示例存储库中。

git clone https://github.com/Azure-Samples/msdocs-azure-data-tables-sdk-js

示例应用程序使用天气数据作为示例来演示 API for Table 的功能。 表示天气观察值的对象使用 API for Table 进行存储和检索,其中就包括存储具有附加属性的对象以演示 API for Table 的无架构功能。

A screenshot of the finished application showing data stored in an Azure Cosmos DB table using the API for Table.

1 - 创建 Azure Cosmos DB 帐户

首先需要创建一个 Azure Cosmos DB Tables API 帐户,该帐户将包含应用程序中使用的表。 可以使用 Azure 门户、Azure CLI 或 Azure PowerShell 执行此操作。

登录 Azure 门户,并按照以下步骤创建 Azure Cosmos DB 帐户。

说明 屏幕快照
在 Azure 门户中:
  1. 在 Azure 门户顶部的搜索栏中,输入“cosmos db”。
  2. 在搜索栏下方出现的菜单上的“服务”下,选择标有“Azure Cosmos DB”的项。
A screenshot showing how to use the search box in the top tool bar to find Azure Cosmos DB accounts in Azure.
在“Azure Cosmos DB”页上,选择“+创建”。 A screenshot showing the Create button location on the Azure Cosmos DB accounts page in Azure.
在“选择 API 选项”页上,选择“Azure 表”选项。 A screenshot showing the Azure Table option as the correct option to select.
在“创建 Azure Cosmos DB 帐户 - Azure 表”页上填写表单,如下所示。
  1. 通过选择“资源组”下的“新建”链接,为名为 rg-msdocs-tables-sdk-demo 的存储帐户创建一个新资源组。
  2. 为存储帐户指定名称 cosmos-msdocs-tables-sdk-demo-XYZ,其中的 XYZ 是三个任意的随机字符,用于创建独一无二的帐户名称。 Azure Cosmos DB 帐户名称必须为 3 到 44 个字符长,并且只能包含小写字母、数字或连字符 (-)。
  3. 选择存储帐户的区域。
  4. 选择“标准”性能。
  5. 在“容量模式”下,为此示例选择“预配吞吐量”。
  6. 对于此示例,请在“应用免费层折扣”下选择“应用”。
  7. 选择屏幕底部的“查看 + 创建”按钮,然后选择摘要屏幕上的“创建”以创建 Azure Cosmos DB 帐户。 此过程可能需要数分钟。
A screenshot showing how to fill out the fields on the Azure Cosmos DB Account creation page.

2 - 创建表

接下来,需要在 Azure Cosmos DB 帐户中创建表,以供应用程序使用。 与传统数据库不同,只需指定表的名称,无需指定表中的属性(列)。 将数据加载到表中时,属性(列)会根据需要自动创建。

Azure 门户中完成以下步骤,以在 Azure Cosmos DB 帐户中创建表。

说明 屏幕快照
在Azure 门户,导航到 Azure Cosmos DB 帐户的概述页。 可以通过在顶部搜索栏中键入 Azure Cosmos DB 帐户的名称 (cosmos-msdocs-tables-sdk-demo-XYZ) 并在资源标题下进行查看,导航到 Azure Cosmos DB 帐户的概述页。选择 Azure Cosmos DB 帐户的名称以转到概述页。 A screenshot showing how to use the search box in the top tool bar to find your Azure Cosmos DB account.
在概述页面上,选择“+添加表”。 “新建表”对话框将从页面右侧滑出。 A screenshot showing the location of the Add Table button.
在“新建表”对话框中填充表单,如下所示。
  1. 输入名称“WeatherData”作为“表 ID”。 这是表的名称。
  2. 对于此示例,请在“表吞吐量(自动缩放)”下选择“手动”。
  3. 在估计的 RU/秒下,使用默认值 400。
  4. 选择“确定”按钮以创建表。
A screenshot showing how to New Table dialog box for an Azure Cosmos DB table.

3 - 获取 Azure Cosmos DB 连接字符串

若要访问 Azure Cosmos DB 中的表,你的应用需要 CosmosDB 存储帐户的表连接字符串。 可以使用 Azure 门户、Azure CLI 或 Azure PowerShell 检索该连接字符串。

说明 屏幕快照
在 Azure Cosmos DB 帐户页左侧的“设置”标题下找到名为“连接字符串”的菜单项,并将其选中。 此时会转到一个页面,你可以在其中检索 Azure Cosmos DB 帐户的连接字符串。 A screenshot showing the location of the connection strings link on the Azure Cosmos DB page.
复制“主连接字符串”值以在应用程序中使用。 A screenshot showing which connection string to select and use in your application.

4 - 安装适用于 JS 的 Azure 数据表 SDK

若要从 nodejs 应用程序访问 Azure Cosmos DB for Table,请安装 Azure 数据表 SDK 包。

  npm install @azure/data-tables

5 - 在 env.js 文件中配置表客户端

从 Azure 门户复制 Azure Cosmos DB 或存储帐户连接字符串,并使用复制的连接字符串创建 TableServiceClient 对象。 切换到文件夹 1-strater-app2-completed-app。 然后,在 configure/env.js 文件中添加相应环境变量的值。

const env = {
  connectionString:"A connection string to an Azure Storage or Azure Cosmos DB account.",
  tableName: "WeatherData",
};

Azure SDK 使用客户端对象与 Azure 通信,以对 Azure 执行不同的操作。 TableClient 类是用于与 Azure Cosmos DB for Table 通信的类。 应用程序通常会为每个表创建单个 serviceClient 对象,以在整个应用程序中使用。

const { TableClient } = require("@azure/data-tables");
const env = require("../configure/env");
const serviceClient = TableClient.fromConnectionString(
  env.connectionString,
  env.tableName
);

6 - 实现 Azure Cosmos DB 表操作

在“服务”目录下的 tableClient.js 文件的 serviceClient 对象中,实现示例应用的所有 Azure Cosmos DB 表操作。

const { TableClient } = require("@azure/data-tables");
const env = require("../configure/env");
const serviceClient = TableClient.fromConnectionString(
  env.connectionString,
  env.tableName
);

从表中获取行

serviceClient 对象包含名为 listEntities 的方法,可用于从表中选择行。 在此示例中,由于未向该方法传递任何参数,因此会从表中选择所有行。

const allRowsEntities = serviceClient.listEntities();

筛选从表返回的行

若要筛选从表返回的行,可以将 OData 样式筛选器字符串传递到 listEntities 方法。 例如,如果你想要获取 2021 年 7 月 1 日午夜到 2021 年 7 月 2 日午夜(含)的所有上海天气读数,可以传入以下筛选字符串。

PartitionKey eq 'Shanghai' and RowKey ge '2021-07-01 12:00' and RowKey le '2021-07-02 12:00'

可以在筛选器系统查询选项部分中查看 OData 网站上的所有 OData 筛选器运算符。

将 request.args 参数传递到 serviceClient 类中的 listEntities 方法时,它会为每个非 null 属性值创建一个筛选器字符串。 它随后会使用“and”子句将所有值联接在一起,以创建合并筛选器字符串。 此合并筛选器字符串会传递到 serviceClient 对象上的 listEntities 方法,仅返回与筛选器字符串匹配的行。 可以在代码中使用类似方法,根据应用程序的要求构造合适的筛选器字符串。

const filterEntities = async function (option) {
  /*
    You can query data according to existing fields
    option provides some conditions to query,eg partitionKey, rowKeyDateTimeStart, rowKeyDateTimeEnd
    minTemperature, maxTemperature, minPrecipitation, maxPrecipitation
  */
  const filterEntitiesArray = [];
  const filters = [];
  if (option.partitionKey) {
    filters.push(`PartitionKey eq '${option.partitionKey}'`);
  }
  if (option.rowKeyDateTimeStart) {
    filters.push(`RowKey ge '${option.rowKeyDateTimeStart}'`);
  }
  if (option.rowKeyDateTimeEnd) {
    filters.push(`RowKey le '${option.rowKeyDateTimeEnd}'`);
  }
  if (option.minTemperature !== null) {
    filters.push(`Temperature ge ${option.minTemperature}`);
  }
  if (option.maxTemperature !== null) {
    filters.push(`Temperature le ${option.maxTemperature}`);
  }
  if (option.minPrecipitation !== null) {
    filters.push(`Precipitation ge ${option.minPrecipitation}`);
  }
  if (option.maxPrecipitation !== null) {
    filters.push(`Precipitation le ${option.maxPrecipitation}`);
  }
  const res = serviceClient.listEntities({
    queryOptions: {
      filter: filters.join(" and "),
    },
  });
  for await (const entity of res) {
    filterEntitiesArray.push(entity);
  }

  return filterEntitiesArray;
};

使用 TableEntity 对象插入数据

将数据添加到表的最简单方法是使用 TableEntity 对象。 在此示例中,数据会从输入模型对象映射到 TableEntity 对象。 输入对象中表示气象站名称和观察日期/时间的属性分别映射到 PartitionKeyRowKey 属性,这些属性共同构成表中行的唯一键。 输入模型对象上的其他属性随后会映射到 TableEntity 对象上的字典属性。 最后,serviceClient 对象上的 createEntity 方法用于将数据插入表中。

修改示例应用程序中的 insertEntity 函数,以包含以下代码。

const insertEntity = async function (entity) {

  await serviceClient.createEntity(entity);

};

使用 TableEntity 对象更新插入数据

如果尝试向表中插入的行具有该表中已存在的分区键/行键组合,则会收到错误。 因此,在向表添加行时,通常最好使用 upsertEntity 而不是 createEntity 方法。 如果表中已存在给定分区键/行键组合,则 upsertEntity 方法会更新现有行。 否则,行会添加到表中。

const upsertEntity = async function (entity) {

  await serviceClient.upsertEntity(entity, "Merge");

};

使用变量属性插入或更新插入数据

使用 Azure Cosmos DB for Table 的一个好处是,如果要加载到表的对象包含任何新属性,那这些属性会自动添加到表中并且值存储在 Azure Cosmos DB 中。 无需如同传统数据库中一样,运行 ALTER TABLE 等 DDL 语句来添加列。

在处理可能会随着时间推移添加或修改需要捕获的数据的数据源时,或者在不同的输入向应用程序提供不同的数据时,此模型可使应用程序具有灵活性。 在示例应用程序中,我们可以模拟一个不仅发送基本天气数据,而且还发送一些附加值的气象站。 首次将具有这些新属性的对象存储在表中时,对应属性(列)会自动添加到表中。

若要使用 API for Table 插入或更新插入此类对象,请将可扩充对象的属性映射到 TableEntity 对象,并根据需要对 serviceClient 对象使用 upsertEntitycreateEntity 方法。

在示例应用程序中,upsertEntity 函数还可实现使用变量属性插入或更新插入数据的功能

const insertEntity = async function (entity) {
  await serviceClient.createEntity(entity);
};

const upsertEntity = async function (entity) {
  await serviceClient.upsertEntity(entity, "Merge");
};

更新条目

可以通过对 serviceClient 对象调用 updateEntity 方法来更新实体。

在示例应用中,此对象会传递到 serviceClient 对象中的 upsertEntity 方法。 它更新该实体对象,并使用 upsertEntity 方法将更新保存到数据库。

const updateEntity = async function (entity) {
  await serviceClient.updateEntity(entity, "Replace");
};

7 - 运行代码

运行示例应用程序以与 Azure Cosmos DB for Table 交互。 首次运行应用程序时没有数据,因为表为空。 使用应用程序顶部的任何按钮将数据添加到表。

A screenshot of the application showing the location of the buttons used to insert data into Azure Cosmos DB using the Table API.

选择“使用表实体插入”按钮会打开一个对话框,使你可以使用 TableEntity 对象插入或更新插入新行。

A screenshot of the application showing the dialog box used to insert data using a TableEntity object.

选择“使用可扩展数据插入”按钮后,将会打开一个对话框,在其中可以插入具有自定义属性的对象,并演示 Azure Cosmos DB for Table 如何根据需要自动将属性(列)添加到表中。 使用“添加自定义字段”按钮添加一个或多个新属性并演示此功能。

A screenshot of the application showing the dialog box used to insert data using an object with custom fields.

使用“插入示例数据”按钮将一些示例数据加载到 Azure Cosmos DB 表中。

A screenshot of the application showing the location of the sample data insert button.

选择顶部菜单中的“筛选结果”项以进入“筛选结果”页面。 在此页面上,填写筛选条件以演示如何生成筛选子句并传递到 Azure Cosmos DB for Table。

A screenshot of the application showing filter results page and highlighting the menu item used to navigate to the page.

清理资源

完成示例应用程序后,应从你的 Azure 帐户中删除与本文相关的所有 Azure 资源。 可以通过删除资源组来进行这种清理。

可以在 Azure 门户中执行以下操作来删除资源组。

说明 屏幕快照
若要转到资源组,在搜索栏中键入资源组的名称。 然后在“资源组”选项卡上,选择资源组的名称。 A screenshot showing how to search for a resource group.
从“资源组”页顶部的工具栏中选择“删除资源组”。 A screenshot showing the location of the Delete resource group button.
屏幕右侧将弹出一个对话框,要求确认删除资源组。
  1. 按说明在文本框中键入确认删除的资源组的完整名称。
  2. 选择页面底部的“删除”按钮。
A screenshot showing the confirmation dialog for deleting a resource group.

后续步骤

在本快速入门教程中,已了解如何创建 Azure Cosmos DB 帐户、使用数据资源管理器创建表和运行应用。 现在可以使用 API for Table 进行数据查询了。