创建由 Azure Cosmos DB 触发的函数Create a function triggered by Azure Cosmos DB

了解如何创建在数据添加到 Azure Cosmos DB 或在其中更改数据时触发的函数。Learn how to create a function triggered when data is added to or changed in Azure Cosmos DB.

在日志中查看消息。

先决条件Prerequisites

完成本教程:To complete this tutorial:

  • 如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a Trial before you begin.

Note

Azure Cosmos DB 绑定只能与 SQL API 配合使用。Azure Cosmos DB bindings are only supported for use with the SQL API. 对于所有其他的 Azure Cosmos DB API,应使用适用于 API 的静态客户端通过函数来访问数据库。API 包括 Azure Cosmos DB 的 API for MongoDB 和表 API。For all other Azure Cosmos DB APIs, you should access the database from your function by using the static client for your API, including Azure Cosmos DB's API for MongoDB, and Table API.

创建 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 trigger.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 选择“创建资源” > “数据库” > “Azure Cosmos DB”。Select Create a resource > Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  3. 在“创建 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 DescriptionDescription
    订阅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 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 字符串将追加到所提供的 ID 后面以创建 URI,因此,请使用唯一的 ID。Because documents.azure.cn is appended to the ID that you provide to create your URI, use a unique ID.

    ID 只能包含小写字母、数字和连字符 (-) 字符。The ID can only contain lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3 到 31 个字符之间。It must be between 3-31 characters in length.
    APIAPI Core (SQL)Core (SQL) 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.

    选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询。Select Core (SQL) to create a document database and query by using SQL syntax.

    详细了解 SQL APILearn more about the SQL API.
    位置Location 选择离用户最近的区域Select 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.

    Azure Cosmos DB 的“新建帐户”页

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

  5. 检查帐户设置,然后选择“创建”。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 门户“通知”窗格

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

    Azure Cosmos DB 帐户页

创建 Azure Function AppCreate an Azure Function app

  1. 选择 Azure 门户左上角的“新建资源”按钮,然后选择“计算” > “Function App”。Select the Create a resource button found on the upper left-hand corner of the Azure portal, then select Compute > Function App.

    在 Azure 门户中创建函数应用

  2. 使用图像下面的表格中指定的函数应用设置。Use the function app settings as specified in the table below the image.

    定义新的函数应用设置

    设置Setting 建议的值Suggested value 说明Description
    应用名称App name 全局唯一名称Globally unique name 用于标识新 Function App 的名称。Name that identifies your new function app. 有效的字符是 a-z0-9-Valid characters are a-z, 0-9, and -.
    订阅Subscription 你的订阅Your subscription 要在其下创建此新函数应用的订阅。The subscription under which this new function app is created.
    资源组Resource Group MyResourceGroupmyResourceGroup 要在其中创建 Function App 的新资源组的名称。Name for the new resource group in which to create your function app.
    运行时堆栈Runtime stack 首选语言Preferred language 选择支持你喜欢的函数编程语言的运行时。Choose a runtime that supports your favorite function programming language. 对于 C# 和 F# 函数,选择 .NETChoose .NET for C# and F# functions.
    存储Storage 全局唯一名称Globally unique name 创建函数应用使用的存储帐户。Create a storage account used by your function app. 存储帐户名称必须为 3 到 24 个字符,并且只能包含数字和小写字母。Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only. 也可使用现有帐户,但该帐户必须符合存储帐户要求You can also use an existing account, which must meets the storage account requirements.
    应用服务计划/位置App Service plan/Location 按应用服务计划运行时,必须管理函数应用的缩放When you run in an App Service plan, you must manage the scaling of your function app.
  3. 选择“创建”以预配和部署函数应用。Select Create to provision and deploy the function app.

  4. 选择门户右上角的“通知”图标,留意是否显示“部署成功”消息。Select the Notification icon in the upper-right corner of the portal and watch for the Deployment succeeded message.

    定义新的函数应用设置

  5. 选择“转到资源”,查看新的函数应用。Select Go to resource to view your new function app.

Tip

如果在门户中找不到函数应用,请尝试将 Function App 添加到 Azure 门户中的收藏夹Having trouble finding your function apps in the portal, try adding Function Apps to your favorites in the Azure portal.

接下来,在新的 Function App 中创建一个函数。Next, you create a function in the new function app.

创建 Azure Cosmos DB 触发器Create Azure Cosmos DB trigger

  1. 展开 Function App,单击“Functions”旁边的 + 按钮。Expand your function app and click the + button next to Functions. 如果这是函数应用中的第一个函数,请依次选择“门户中”、“继续”。If this is the first function in your function app, select In-portal then Continue. 否则,请转到第三步。Otherwise, go to step three.

    Azure 门户中的 Functions 快速入门页

  2. 依次选择“更多模板”、“完成并查看模板”。Choose More templates then Finish and view templates.

    Functions 快速入门选择更多模板

  3. 在搜索字段中,键入 cosmos,然后选择“Azure Cosmos DB 触发器”模板。In the search field, type cosmos and then choose the Azure Cosmos DB trigger template.

  4. 如果系统提示,请选择“安装”以在函数应用中安装 Azure Cosmos DB 存储扩展。If prompted, select Install to install the Azure Cosmos DB extension in the function app. 安装成功后,选择“继续”。After installation succeeds, select Continue.

    安装绑定扩展

  5. 使用图像下面的表中指定的设置来配置新的触发器。Configure the new trigger with the settings as specified in the table below the image.

    创建 Azure Cosmos DB 触发函数

    设置Setting 建议的值Suggested value 说明Description
    名称Name 默认Default 使用模板建议的默认函数名称。Use the default function name suggested by the template.
    Azure Cosmos DB 帐户连接Azure Cosmos DB account connection 新设置New setting 选择“新建”,选择你的订阅、你之前创建的数据库帐户,然后选择“选择”。Select New, then choose your Subscription, the Database account you created earlier, and Select. 这将为帐户连接创建应用程序设置。This creates an application setting for your account connection. 此设置由数据库连接的绑定使用。This setting is used by the binding to connection to the database.
    集合名称Collection name ItemsItems 要监视的集合的名称。Name of collection to be monitored.
    创建租赁集合(如果不存在)Create lease collection if it doesn't exist 已选中Checked 集合不存在,因此创建集合。The collection doesn't already exist, so create it.
    数据库名称Database name 任务Tasks 数据库的名称和要监视的集合。Name of database with the collection to be monitored.
  6. 单击“创建”创建你的 Azure Cosmos DB 触发函数。Click Create to create your Azure Cosmos DB triggered function. 创建函数后,将显示基于模板的函数代码。After the function is created, the template-based function code is displayed.

    运用 C# 语言的 Cosmos DB 函数模板

    此函数模板将文档的数量和第一个文档 ID 写入到日志中。This function template writes the number of documents and the first document ID to the logs.

接下来,连接到 Azure Cosmos DB 帐户并在 Tasks 数据库中创建 Items 集合。Next, you connect to your Azure Cosmos DB account and create the Items collection in the Tasks database.

创建项集合Create the Items collection

  1. 在浏览器的新选项卡中打开 Azure 门户的第二个实例。Open a second instance of the Azure portal in a new tab in the browser.

  2. 在门户左侧展开图标栏,在搜索字段中键入 cosmos,然后选择“Azure Cosmos DB”。On the left side of the portal, expand the icon bar, type cosmos in the search field, and select Azure Cosmos DB.

    搜索 Azure Cosmos DB 服务

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

  4. 在“集合”中,选择“taskDatabase”并选择“新集合”。In Collections, choose taskDatabase and select New Collection.

    创建集合

  5. 在“添加集合”中,使用图像下的表中所示的设置。In Add Collection, use the settings shown in the table below the image.

    定义 taskCollection

    设置Setting 建议的值Suggested value 说明Description
    数据库 IDDatabase ID 任务Tasks 新数据库的名称。The name for your new database. 它必须匹配函数绑定中定义的名称。This must match the name defined in your function binding.
    集合 IDCollection ID ItemsItems 新集合的名称。The name for the new collection. 它必须匹配函数绑定中定义的名称。This must match the name defined in your function binding.
    存储容量Storage capacity 固定 (10 GB)Fixed (10 GB) 使用默认值。Use the default value. 此值是数据库的存储容量。This value is the storage capacity of the database.
    吞吐量Throughput 400 RU400 RU 使用默认值。Use the default value. 如果想要减少延迟,以后可以增加吞吐量。If you want to reduce latency, you can scale up the throughput later.
    分区键Partition key /category/category 一个分区键,用于将数据均匀分配到每个分区。A partition key that distributes data evenly to each partition. 选择正确的分区键对于创建高性能集合而言很重要。Selecting the correct partition key is important in creating a performant collection.
  6. 单击“确定”创建项集合。Click OK to create the Items collection. 创建该集合可能需要一点时间。It may take a short time for the collection to get created.

函数绑定中指定的集合存在后,可以通过将文档添加到此新集合来测试函数。After the collection specified in the function binding exists, you can test the function by adding documents to this new collection.

测试函数Test the function

  1. 展开数据资源管理器中的新“taskCollection”集合,选择“文档”,然后选择“新建文档”。Expand the new taskCollection collection in Data Explorer, choose Documents, then select New Document.

    在 taskCollection 创建文档

  2. 将新文档的内容替换为以下内容,然后选择“保存”。Replace the contents of the new document with the following content, then choose Save.

     {
         "id": "task1",
         "category": "general",
         "description": "some task"
     }
    
  3. 切换到包含门户中的函数的第一个浏览器选项卡。Switch to the first browser tab that contains your function in the portal. 展开函数日志并验证新的文档已触发该函数。Expand the function logs and verify that the new document has triggered the function. 会看到 task1 文档 ID 值已写入日志。See that the task1 document ID value is written to the logs.

    在日志中查看消息。

  4. (可选)返回到文档进行更改,然后单击“更新”。(Optional) Go back to your document, make a change, and click Update. 然后,回到函数日志,并验证此更新同样已触发该函数。Then, go back to the function logs and verify that the update has also triggered the function.

清理资源Clean up resources

本教程系列中的其他快速入门教程是在本文的基础上制作的。Other quick starts in this collection build upon this quick start. 如果打算使用后续的快速入门、教程或者在本快速入门中创建的任何服务,请勿清理这些资源。If you plan to work with subsequent quick starts, tutorials, or with any of the services you have created in this quick start, do not clean up the resources.

Azure 中的资源是指函数应用、函数、存储帐户等。Resources in Azure refers to function apps, functions, storage accounts, and so forth. 这些资源可以组合到资源组中,删除该组即可删除组中的所有内容。They are grouped into resource groups, and you can delete everything in a group by deleting the group.

已创建完成这些快速入门所需的资源。You created resources to complete these quickstarts. 这些资源可能需要付费,具体取决于帐户状态服务定价You may be billed for these resources, depending on your account status and service pricing. 如果不再需要这些资源,请参阅下面介绍的资源删除方法:If you don't need the resources anymore, here's how to delete them:

  1. 在 Azure 门户中转到“资源组”页。In the Azure portal, go to the Resource group page.

    若要从函数应用页转到该页,请选择“概览”选项卡,然后选择“资源组”下的链接。To get to that page from the function app page, select the Overview tab and then select the link under Resource group.

    从函数应用页选择要删除的资源组。

    若要从仪表板转到该页,请选择“资源组”,然后选择用于本快速入门的资源组。To get to that page from the dashboard, select Resource groups, and then select the resource group that you used for this quickstart.

  2. 在“资源组”页中查看所包括的资源的列表,然后验证这些资源是否是要删除的。In the Resource group page, review the list of included resources, and verify that they are the ones you want to delete.

  3. 选择“删除资源组”,然后按说明操作。Select Delete resource group, and follow the instructions.

    可能需要数分钟才能删除完毕。Deletion may take a couple of minutes. 完成后会显示一个通知,持续数秒。When it's done, a notification appears for a few seconds. 也可以选择页面顶部的钟形图标来查看通知。You can also select the bell icon at the top of the page to view the notification.

后续步骤Next steps

你已经创建一个函数,当在 Azure Cosmos DB 中添加或修改文档时会运行此函数。You have created a function that runs when a document is added or modified in your Azure Cosmos DB. 有关 Azure Cosmos DB 触发器的详细信息,请参阅适用于 Azure Functions 的 Azure Cosmos DB 绑定For more information about Azure Cosmos DB triggers, see Azure Cosmos DB bindings for Azure Functions.

创建第一个函数以后,即可向这个可以将消息写入存储队列的函数添加输出绑定。Now that you have a created your first function, let's add an output binding to the function that writes a message to a Storage queue.