快速入门:使用 Node.js 和 Azure Cosmos DB 生成表 API 应用Quickstart: Build a Table API app with Node.js and Azure Cosmos DB

在本快速入门中,我们创建一个 Azure Cosmos DB 表 API 帐户,并使用从 GitHub 克隆的数据资源管理器和 Node.js 应用创建表和条目。In this quickstart, you create an Azure Cosmos DB Table API account, and use Data Explorer and a Node.js app cloned from GitHub to create tables and entities. Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with multiple-region distribution and horizontal scale capabilities.

先决条件Prerequisites

创建数据库帐户Create a database account

重要

必须新建表 API 帐户,才能使用正式发布的表 API SDK。You need to create a new Table API account to work with the generally available Table API SDKs. 正式发布的 SDK 不支持在预览期间创建的表 API 帐户。Table API accounts created during preview are not supported by the generally available SDKs.

  1. 在新浏览器窗口中,登录到 Azure 门户In a new browser window, sign in to the Azure portal.

  2. 在左侧菜单中,选择“创建资源”。In the left menu, select Create a resource.

    在 Azure 门户中创建资源

  3. 在“新建”页上,选择“数据库” > “Azure Cosmos DB”。 On the New page, select Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  4. 在“创建 Azure Cosmos DB 帐户”页中,输入新 Azure Cosmos DB 帐户的设置。On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    设置Setting Value 说明Description
    订阅Subscription 订阅Your subscription 选择要用于此 Azure Cosmos DB 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    资源组Resource Group 选择“新建”,然后选择“帐户名称”Create new, then Account Name 选择“新建”。Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource group name for your account. 为简单起见,请使用与 Azure Cosmos DB 帐户名称相同的名称。For simplicity, use the same name as your Azure Cosmos DB account name.
    帐户名Account Name 唯一的名称A unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account.

    帐户名称只能使用小写字母、数字及连字符 (-),必须为 3 到 31 个字符长。The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    APIAPI Table API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:Core(SQL)(适用于文档数据库)、Gremlin(适用于图数据库)、MongoDB(适用于文档数据库)、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. 必须为每种 API 创建单独的帐户。You must create a separate account for each API.

    选择“Azure 表”,因为在本快速入门中,将创建一个使用表 API 的表。Select Azure Table, because in this quickstart you are creating a table that works with the Table API.

    详细了解表 APILearn more about the Table API.
    位置Location 离用户最近的区域The region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that's closest to your users to give them the fastest access to the data.

    可以将“异地冗余”和“多区域写入”选项保留为“禁用”,避免产生额外的费用,并跳过“网络”和“标记”部分 。 You can leave the Geo-Redundancy and Multi-region Writes options at Disable to avoid additional charges, and skip the Network and Tags sections.

  5. 选择“查看 + 创建”。Select Review+Create. 完成验证后,选择“创建”以创建帐户。After the validation is complete, select Create to create the account.

    Azure Cosmos DB 的“新建帐户”页面

  6. 创建帐户需要几分钟时间。It takes a few minutes to create the account. 你将看到一条说明“部署正在进行”的消息。You'll see a message that states Your deployment is underway. 等待部署完成,然后选择“转到资源”。Wait for the deployment to finish, and then select Go to resource.

    Azure 门户“通知”窗格

添加表Add a table

现在可以在 Azure 门户中使用数据资源管理器工具来创建数据库和表。You can now use the Data Explorer tool in the Azure portal to create a database and table.

  1. 依次选择“数据资源管理器” > “新建表” 。Select Data Explorer > New Table.

    此时,最右侧将显示“添加表” 区域,可能需要向右滚动才能看到。The Add Table area is displayed on the far right, you may need to scroll right to see it.

    Azure 门户中的数据资源管理器

  2. 在“添加表” 页上,输入新表的设置。In the Add Table page, enter the settings for the new table.

    设置Setting 建议的值Suggested value 说明Description
    表 IDTable Id sample-tablesample-table 新表的 ID。The ID for your new table. 表名称与数据库 ID 的字符要求相同。Table names have the same character requirements as database ids. 数据库名称的长度必须为 1 到 255 个字符,不能包含 / \ # ? 或尾随空格。Database names must be between 1 and 255 characters, and cannot contain / \ # ? or a trailing space.
    吞吐量Throughput 400 RU400 RUs 将吞吐量更改为每秒 400 个请求单位 (RU/s)。Change the throughput to 400 request units per second (RU/s). 如果想要减少延迟,以后可以增加吞吐量。If you want to reduce latency, you can scale up the throughput later.
  3. 选择“确定” 。Select OK.

  4. 数据资源管理器将显示新的数据库和表。Data Explorer displays the new database and table.

    显示新的数据库和集合的 Azure 门户数据资源管理器

添加示例数据Add sample data

现在可以使用数据资源管理器将数据添加到新表。You can now add data to your new table using Data Explorer.

  1. 在数据资源管理器中,展开 sample-table,选择“实体”,然后选择“添加实体”。 In Data Explorer, expand sample-table, select Entities, and then select Add Entity.

    在 Azure 门户的数据资源管理器中创建新实体

  2. 现在请将数据添加到 PartitionKey 值框和 RowKey 值框,然后选择“添加实体”。 Now add data to the PartitionKey value box and RowKey value box, and select Add Entity.

    为新实体设置分区键和行键

    现在可以在数据资源管理器中将更多实体添加到表、编辑实体或查询数据。You can now add more entities to your table, edit your entities, or query your data in Data Explorer. 使用数据资源管理器还可以缩放吞吐量,并将存储过程、用户定义的函数和触发器添加到表中。Data Explorer is also where you can scale your throughput and add stored procedures, user-defined functions, and triggers to your table.

克隆示例应用程序Clone the sample application

现在让我们从 GitHub 克隆表应用,设置连接字符串,然后运行该应用。Now let's clone a Table app from GitHub, set the connection string, and run it. 会看到以编程方式处理数据是多么容易。You'll see how easy it is to work with data programmatically.

  1. 打开命令提示符,新建一个名为“git-samples”的文件夹,然后关闭命令提示符。Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
    
  2. 打开诸如 git bash 之类的 git 终端窗口,并使用 cd 命令更改为要安装示例应用的新文件夹。Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. 运行下列命令以克隆示例存储库。Run the following command to clone the sample repository. 此命令在计算机上创建示例应用程序的副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/storage-table-node-getting-started.git
    

提示

有关类似代码的更详细演练,请参阅 Cosmos DB 表 API 示例一文。For a more detailed walkthrough of similar code, see the Cosmos DB Table API sample article.

查看代码Review the code

此步骤是可选的。This step is optional. 如果有意了解如何使用代码创建数据库资源,可以查看以下代码片段。If you're interested in learning how the database resources are created in the code, you can review the following snippets. 否则,可以直接跳转到本文档的更新连接字符串部分。Otherwise, you can skip ahead to update the connection string section of this doc.

  • 下面的代码演示如何在 Azure 存储中创建表:The following code shows how to create a table within the Azure Storage:

    storageClient.createTableIfNotExists(tableName, function (error, createResult) {
        if (error) return callback(error);
    
        if (createResult.isSuccessful) {
          console.log("1. Create Table operation executed successfully for: ", tableName);
        }
    }
    
    
  • 以下代码演示了如何在表中插入数据:The following code shows how to insert data into the table:

    var customer = createCustomerEntityDescriptor("Harp", "Walter", "Walter@contoso.com", "425-555-0101");
    
    storageClient.insertOrMergeEntity(tableName, customer, function (error, result, response) {
        if (error) return callback(error);
    
        console.log("   insertOrMergeEntity succeeded.");
    }
    
  • 以下代码演示了如何查询表中的数据:The following code shows how to query data from the table:

    console.log("6. Retrieving entities with surname of Smith and first names > 1 and <= 75");
    
    var storageTableQuery = storage.TableQuery;
    var segmentSize = 10;
    
    // Demonstrate a partition range query whereby we are searching within a partition for a set of entities that are within a specific range. 
    var tableQuery = new storageTableQuery()
        .top(segmentSize)
        .where('PartitionKey eq ?', lastName)
        .and('RowKey gt ?', "0001").and('RowKey le ?', "0075");
    
    runPageQuery(tableQuery, null, function (error, result) {
    
        if (error) return callback(error);
    
    
  • 以下代码演示了如何删除表中的数据:The following code shows how to delete data from the table:

    storageClient.deleteEntity(tableName, customer, function entitiesQueried(error, result) {
        if (error) return callback(error);
    
        console.log("   deleteEntity succeeded.");
    }
    

更新连接字符串Update your connection string

现在返回到 Azure 门户,获取连接字符串信息,并将其复制到应用。Now go back to the Azure portal to get your connection string information and copy it into the app. 这样,应用程序就可以与托管的数据库进行通信。This enables your app to communicate with your hosted database.

  1. Azure 门户的 Azure Cosmos DB 帐户中,选择“连接字符串”。In your Azure Cosmos DB account in the Azure portal, select Connection String.

    在“连接字符串”窗格中查看并复制所需的连接字符串信息

  2. 使用右侧的复制按钮复制主连接字符串。Copy the PRIMARY CONNECTION STRING using the copy button on the right side.

  3. 打开 app.config 文件,然后将值粘贴到第三行的 connectionString 中。Open the app.config file, and paste the value into the connectionString on line three.

    重要

    如果终结点使用 documents.azure.cn,则意味着帐户为预览版帐户,需创建适用于公开发布版表 API SDK 的新的表 API 帐户If your Endpoint uses documents.azure.cn, that means you have a preview account, and you need to create a new Table API account to work with the generally available Table API SDK.

  4. 保存 app.config 文件。Save the app.config file.

现已使用与 Azure Cosmos DB 进行通信所需的所有信息更新应用。You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

运行应用Run the app

  1. 在 git 终端窗口中,运行 cd 切换到 storage-table-java-getting-started 文件夹。In the git terminal window, cd to the storage-table-java-getting-started folder.

    cd "C:\git-samples\storage-table-node-getting-started"
    
  2. 运行以下命令,在本地安装 [azure]、[node-uuid]、[nconf] 和 [async] 模块,并为它们在 package.json 文件中保存一个条目。Run the following command to install the [azure], [node-uuid], [nconf] and [async] modules locally as well as to save an entry for them to the package.json file.

    npm install azure-storage node-uuid async nconf --save
    
  3. 在 git 终端窗口中运行以下命令,以便运行 Node.js 应用程序。In the git terminal window, run the following commands to run the Node.js application.

    node ./tableSample.js 
    

    控制台窗口显示,正在将表数据添加到 Azure Cosmos DB 中的新表数据库。The console window displays the table data being added to the new table database in Azure Cosmos DB.

    现可返回到数据资源管理器,查看查询、修改和处理此新数据。You can now go back to Data Explorer and see, query, modify, and work with this new data.

在 Azure 门户中查看 SLAReview SLAs in the Azure portal

Azure 门户监视 Cosmos DB 帐户吞吐量、存储、可用性、延迟和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服务级别协议 (SLA) 关联的指标的图表显示与实际性能相比的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此套指标使得监视 SLA 十分透明。This suite of metrics makes monitoring your SLAs transparent.

若要查看指标和 SLA,请执行以下操作:To review metrics and SLAs:

  1. 在 Cosmos DB 帐户的导航菜单中选择“指标” 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 选择一个选项卡,如“延迟” ,然后选择右侧的时间范围。Select a tab such as Latency, and select a timeframe on the right. 比较图表上的“实际” 和“SLA” 线。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 指标套件

  3. 查看其他选项卡上的指标。Review the metrics on the other tabs.

清理资源Clean up resources

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要删除资源,请执行以下操作:To delete the resources:

  1. 在 Azure 门户的“搜索”栏中,搜索并选择“资源组” 。In the Azure portal Search bar, search for and select Resource groups.

  2. 从列表中选择为本快速入门创建的资源组。From the list, select the resource group you created for this quickstart.

    选择要删除的资源组

  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, select Delete resource group.

    删除资源组

  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。In the next window, enter the name of the resource group to delete, and then select Delete.

后续步骤Next steps

在本快速入门中,你了解了如何创建 Azure Cosmos DB 帐户、如何使用数据资源管理器创建表,以及如何运行 Node.js 应用来添加表数据。In this quickstart, you learned how to create an Azure Cosmos DB account, create a table using the Data Explorer, and run a Node.js app to add table data. 现在可以使用表 API 进行数据查询了。Now you can query your data using the Table API.