使用 Azure Functions 和 Azure Cosmos DB 存储非结构化数据Store unstructured data using Azure Functions and Azure Cosmos DB

Azure Cosmos DB 是存储非结构化数据和 JSON 数据的良好方式。Azure Cosmos DB is a great way to store unstructured and JSON data. 将 Cosmos DB 与 Azure Functions 结合使用,可以快速、轻松地存储数据,并且所需的代码也比在关系数据库中存储数据时所需的代码少得多。Combined with Azure Functions, Cosmos DB makes storing data quick and easy with much less code than required for storing data in a relational database.

备注

此时,Azure Cosmos DB 触发器、输入绑定和输出绑定仅可与 SQL API 和图形 API 帐户一起使用。At this time, the Azure Cosmos DB trigger, input bindings, and output bindings work with SQL API and Graph API accounts only.

在 Azure Functions 中,输入和输出绑定提供从函数连接到外部服务数据的声明性方式。In Azure Functions, input and output bindings provide a declarative way to connect to external service data from your function. 本文介绍了如何更新现有的函数,以便添加输出绑定,在 Azure Cosmos DB 文档中存储非结构化数据。In this article, learn how to update an existing function to add an output binding that stores unstructured data in an Azure Cosmos DB document.

先决条件Prerequisites

为完成此教程:To complete this tutorial:

本主题以在从 Azure 门户创建第一个函数主题中创建的资源为基础。This topic uses as its starting point the resources created in Create your first function from the Azure portal. 请现在就完成以下步骤,以便创建函数应用(如果尚未这样做)。If you haven't already done so, please complete these steps now to create your function app.

创建 Azure Cosmos DB 帐户Create an Azure Cosmos DB account

在创建输出绑定之前,必须已具有使用 SQL API 的 Azure Cosmos DB 帐户。You must have an Azure Cosmos DB account that uses the SQL API before you create the output binding.

  1. 在 Azure 门户菜单或主页中,选择“创建资源” 。From the Azure portal menu or the Home page , select Create a resource.

  2. 在“新建”页面中搜索“Azure Cosmos DB”,然后选择它。 On the New page, search for and select Azure Cosmos DB.

  3. 在“Azure Cosmos DB”页上,选择“创建”。On the Azure Cosmos DB page, select Create.

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

    设置Setting Value 说明Description
    订阅Subscription 订阅名称Subscription name 选择要用于此 Azure Cosmos 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos account.
    资源组Resource Group 资源组名称Resource group name 选择一个资源组,或者选择“新建”,然后输入新资源组的唯一名称。Select a resource group, or select Create new , then enter a unique name for the new resource group.
    帐户名Account Name 唯一的名称A unique name 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 将追加到所提供的名称以创建 URI,因此,请使用唯一的名称。Because documents.azure.cn is appended to the name that you provide to create your URI, use a unique name.

    名称只能包含小写字母、数字和连字符 (-)。The name can only contain lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3-44 个字符之间。It must be between 3-44 characters in length.
    APIAPI 要创建的帐户的类型The type of account to create 选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询。Select Core (SQL) to create a document database and query by using SQL syntax.

    API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据的 Core (SQL) 和 MongoDB、适用于图形数据的 Gremlin、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.
    容量模式Capacity mode 预配吞吐量或无服务器Provisioned throughput or Serverless 选择“预配吞吐量”以在预配吞吐量模式下创建帐户。Select Provisioned throughput to create an account in provisioned throughput mode. 选择“无服务器”以在无服务器模式下创建帐户。Select Serverless to create an account in serverless mode.

    注意 :无服务器当前仅适用于核心 (SQL) API 帐户。Note : Serverless is currently available for Core (SQL) API accounts only.
    应用免费层折扣Apply Free Tier Discount 应用或不应用Apply or Do not apply 使用 Azure Cosmos DB 免费层,你将在帐户中获得每秒的前 400 RU 免费的吞吐量和 5 GB 的免费存储。With Azure Cosmos DB free tier, you will get the first 400 RU/s and 5 GB of storage for free in an account. 了解免费层的详细信息。Learn more about free tier.
    位置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 is closest to your users to give them the fastest access to the data.
    帐户类型Account Type 生产或非生产Production or Non-Production 如果帐户将用于生产工作负荷,请选择“生产”。Select Production if the account will be used for a production workload. 如果帐户将用于非生产环境(例如开发、测试、QA 或过渡),请选择“非生产”。Select Non-Production if the account will be used for non-production, e.g. development, testing, QA, or staging. 这是一个 Azure 资源标记设置,用于调整门户体验,但不会影响基础 Azure Cosmos DB 帐户。This is an Azure resource tag setting that tunes the Portal experience but does not affect the underlying Azure Cosmos DB account. 可以随时更改此值。You can change this value anytime.

    备注

    每个 Azure 订阅最多可以有一个免费层 Azure Cosmos DB 帐户,并且你必须在创建帐户时选择加入使用。You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. 如果看不到用于应用免费层折扣的选项,这意味着订阅中的另一个帐户已启用免费层。If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    备注

    如果选择“无服务器”作为“容量模式” ,则以下选项不可用:The following options are not available if you select Serverless as the Capacity mode :

    • 应用免费层折扣Apply Free Tier Discount
    • 异地冗余Geo-redundancy
    • 多区域写入Multi-region Writes

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

  5. 选择“查看 + 创建”。Select Review + create. 可以跳过“网络”和“标记”部分 。You can skip the Network and Tags sections.

  6. 检查帐户设置,然后选择“创建”。Review the account settings, and then select Create. 创建帐户需要几分钟时间。It takes a few minutes to create the account. 等待门户页显示“你的部署已完成”消息。Wait for the portal page to display Your deployment is complete.

    Azure 门户“通知”窗格

  7. 选择“转到资源”,转到 Azure Cosmos DB 帐户页。Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帐户页面

添加输出绑定Add an output binding

  1. 在 Azure 门户中,导航到之前创建的函数应用并选择它。In the Azure portal, navigate to and select the function app you created previously.

  2. 选择“函数”,然后选择 HttpTrigger 函数。Select Functions , and then select the HttpTrigger function.

    在 Azure 门户中选择 Http 函数。

  3. 选择“集成”和“+ 添加输出”。Select Integration and + Add output .

    添加 Azure Cosmos DB 输出绑定。

  4. 根据表中的指定使用“创建输出”设置:Use the Create Output settings as specified in the table:

    配置 Azure Cosmos DB 输出绑定。

    设置Setting 建议的值Suggested value 说明Description
    绑定类型Binding Type Azure Cosmos DBAzure Cosmos DB 要选择的绑定类型的名称,用于创建到 Azure Cosmos DB 的输出绑定。Name of the binding type to select to create the output binding to Azure Cosmos DB.
    文档参数名称Document parameter name taskDocumenttaskDocument 引用代码中的 Cosmos DB 对象的名称。Name that refers to the Cosmos DB object in code.
    数据库名称Database name taskDatabasetaskDatabase 用于保存文档的数据库的名称。Name of database to save documents.
    集合名称Collection name taskCollectiontaskCollection 数据库集合的名称。Name of the database collection.
    如果为 true,则创建 Cosmos DB 数据库和集合If true, creates the Cosmos DB database and collection Yes 集合不存在,因此创建集合。The collection doesn't already exist, so create it.
    Cosmos DB 帐户连接Cosmos DB account connection 新设置New setting 选择“新建”,然后选择前面创建的 Azure Cosmos DB 帐户和数据库帐户,然后选择“确定”。Select New , then choose Azure Cosmos DB Account and the Database account you created earlier, and then select OK . 为帐户连接创建应用程序设置。Creates an application setting for your account connection. 此设置由数据库连接的绑定使用。This setting is used by the binding to connection to the database.
  5. 选择“确定”以创建绑定。Select OK to create the binding.

更新函数代码Update the function code

根据你选择的语言将现有函数代码替换为以下代码:Replace the existing function code with the following code, in your chosen language:

将现有 C# 函数替换为以下代码:Replace the existing C# function with the following code:

#r "Newtonsoft.Json"

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

public static IActionResult Run(HttpRequest req, out object taskDocument, ILogger log)
{
    string name = req.Query["name"];
    string task = req.Query["task"];
    string duedate = req.Query["duedate"];

    // We need both name and task parameters.
    if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(task))
    {
        taskDocument = new
        {
            name,
            duedate,
            task
        };

        return (ActionResult)new OkResult();
    }
    else
    {
        taskDocument = null;
        return (ActionResult)new BadRequestResult();
    }
}

此代码示例读取 HTTP 请求查询字符串,并将其分配到 taskDocument 对象中的字段。This code sample reads the HTTP Request query strings and assigns them to fields in the taskDocument object. taskDocument 绑定从此绑定参数发送对象数据,该参数将存储在已绑定文档数据库中。The taskDocument binding sends the object data from this binding parameter to be stored in the bound document database. 该数据库在首次运行函数时创建。The database is created the first time the function runs.

测试函数和数据库Test the function and database

  1. 选择“测试/运行”。Select Test/Run . 在“查询”下选择“+ 添加参数”,然后将以下参数添加到查询字符串: Under Query , select + Add parameter and add the following parameters to the query string:

    • name
    • task
    • duedate

    测试函数。

  2. 选择“运行”并验证是否返回了 200 状态。Select Run and verify that a 200 status is returned.

    屏幕截图显示选择“运行”后突出显示的 HTTP 响应代码 200 状态。

  3. 在 Azure 门户中,搜索并选择“Azure Cosmos DB”。In the Azure portal, search for and select Azure Cosmos DB .

    搜索 Cosmos DB 服务。

  4. 选择 Azure Cosmos DB 帐户,然后选择“数据资源管理器”。Choose your Azure Cosmos DB account, then select Data Explorer .

  5. 展开“TaskCollection”节点,选择新的文档,确认该文档包含查询字符串值以及一些其他的元数据。Expand the TaskCollection nodes, select the new document, and confirm that the document contains your query string values, along with some additional metadata.

    验证文档中的字符串值。

你已成功地将绑定添加到 HTTP 触发器,用以在 Azure Cosmos DB 中存储非结构化数据。You've successfully added a binding to your HTTP trigger to store unstructured data in an Azure Cosmos DB.

清理资源Clean up resources

在前面的步骤中,你在资源组中创建了 Azure 资源。In the preceding steps, you created Azure resources in a resource group. 如果将来不再需要这些资源,可以通过删除资源组来删除它们。If you don't expect to need these resources in the future, you can delete them by deleting the resource group.

从 Azure 门户菜单或“主页”页上,选择“资源组” 。From the Azure portal menu or Home page, select Resource groups . 然后,在“资源组”页上,选择“myResourceGroup” 。Then, on the Resource groups page, select myResourceGroup .

在“myResourceGroup”页中,确保列出的资源是要删除的资源。 On the myResourceGroup page, make sure that the listed resources are the ones you want to delete.

选择“删除资源组” ,在文本框中键入“myResourceGroup” 以确认,然后选择“删除” 。Select Delete resource group , type myResourceGroup in the text box to confirm, and then select Delete .

后续步骤Next steps

若要详细了解如何绑定到 Cosmos DB 数据库,请参阅 Azure Functions Cosmos DB 绑定For more information about binding to a Cosmos DB database, see Azure Functions Cosmos DB bindings.