适用于 Azure Functions 2.x 的 Azure Cosmos DB 输出绑定Azure Cosmos DB output binding for Azure Functions 2.x

Azure Cosmos DB 输出绑定允许使用 SQL API 将新文档写入 Azure Cosmos DB 数据库。The Azure Cosmos DB output binding lets you write a new document to an Azure Cosmos DB database using the SQL API.

有关设置和配置详细信息,请参阅概述For information on setup and configuration details, see the overview.

本部分包含以下示例:This section contains the following examples:

这些示例引用简单的 ToDoItem 类型:The examples refer to a simple ToDoItem type:

namespace CosmosDBSamplesV2
{
    public class ToDoItem
    {
        public string Id { get; set; }
        public string Description { get; set; }
    }
}

队列触发器,写入一个文档Queue trigger, write one doc

以下示例演示一个使用队列存储消息中提供的数据,将文档添加到数据库的 C# 函数The following example shows a C# function that adds a document to a database, using data provided in message from Queue storage.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using System;

namespace CosmosDBSamplesV2
{
    public static class WriteOneDoc
    {
        [FunctionName("WriteOneDoc")]
        public static void Run(
            [QueueTrigger("todoqueueforwrite")] string queueMessage,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")]out dynamic document,
            ILogger log)
        {
            document = new { Description = queueMessage, id = Guid.NewGuid() };

            log.LogInformation($"C# Queue trigger function inserted one row");
            log.LogInformation($"Description={queueMessage}");
        }
    }
}

队列触发器,使用 IAsyncCollector 来写入文档Queue trigger, write docs using IAsyncCollector

以下示例演示了一个 C# 函数,该函数使用以队列消息 JSON 格式提供的数据将文档集添加到数据库。The following example shows a C# function that adds a collection of documents to a database, using data provided in a queue message JSON.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class WriteDocsIAsyncCollector
    {
        [FunctionName("WriteDocsIAsyncCollector")]
        public static async Task Run(
            [QueueTrigger("todoqueueforwritemulti")] ToDoItem[] toDoItemsIn,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")]
                IAsyncCollector<ToDoItem> toDoItemsOut,
            ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed {toDoItemsIn?.Length} items");

            foreach (ToDoItem toDoItem in toDoItemsIn)
            {
                log.LogInformation($"Description={toDoItem.Description}");
                await toDoItemsOut.AddAsync(toDoItem);
            }
        }
    }
}

特性和注释Attributes and annotations

C# 类库中,使用 CosmosDB 特性。In C# class libraries, use the CosmosDB attribute.

该特性的构造函数采用数据库名称和集合名称。The attribute's constructor takes the database name and collection name. 有关这些设置以及可以配置的其他属性的信息,请参阅输出 - 配置For information about those settings and other properties that you can configure, see Output - configuration. 下面是某个方法签名中的 CosmosDB 特性示例:Here's a CosmosDB attribute example in a method signature:

    [FunctionName("QueueToDocDB")]
    public static void Run(
        [QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] string myQueueItem,
        [CosmosDB("ToDoList", "Items", Id = "id", ConnectionStringSetting = "myCosmosDB")] out dynamic document)
    {
        ...
    }

配置Configuration

下表解释了在 function.json 文件和 CosmosDB 特性中设置的绑定配置属性。The following table explains the binding configuration properties that you set in the function.json file and the CosmosDB attribute.

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 cosmosDBMust be set to cosmosDB.
directiondirection 不适用n/a 必须设置为 outMust be set to out.
namename 不适用n/a 表示函数中的文档的绑定参数的名称。Name of the binding parameter that represents the document in the function.
databaseNamedatabaseName DatabaseNameDatabaseName 包含在其中创建文档的集合的数据库。The database containing the collection where the document is created.
collectionNamecollectionName CollectionNameCollectionName 包含在其中创建文档的集合的名称。The name of the collection where the document is created.
createIfNotExistscreateIfNotExists CreateIfNotExistsCreateIfNotExists 一个用于指示是否创建集合(如果不存在)的布尔值。A boolean value to indicate whether the collection is created when it doesn't exist. 默认值为 false,因为新集合是使用保留的吞吐量创建的,具有成本方面的隐含意义。The default is false because new collections are created with reserved throughput, which has cost implications. 有关详细信息,请参阅定价页For more information, see the pricing page.
partitionKeypartitionKey PartitionKeyPartitionKey CreateIfNotExists 为 true 时,将定义所创建集合的分区键路径。When CreateIfNotExists is true, it defines the partition key path for the created collection.
collectionThroughputcollectionThroughput CollectionThroughputCollectionThroughput CreateIfNotExists 为 true 时,将定义所创建集合的吞吐量When CreateIfNotExists is true, it defines the throughput of the created collection.
connectionStringSettingconnectionStringSetting ConnectionStringSettingConnectionStringSetting 内含 Azure Cosmos DB 连接字符串的应用设置的名称。The name of the app setting containing your Azure Cosmos DB connection string.
preferredLocationspreferredLocations PreferredLocationsPreferredLocations (可选)为 Azure Cosmos DB 服务中的异地复制数据库帐户定义首选位置(区域)。(Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. 值应以逗号分隔。Values should be comma-separated.
useMultipleWriteLocationsuseMultipleWriteLocations UseMultipleWriteLocationsUseMultipleWriteLocations (可选)与 PreferredLocations 一起设置为 true 时,它可以利用 Azure Cosmos DB 服务中的多区域写入(Optional) When set to true along with PreferredLocations, it can leverage multi-region writes in the Azure Cosmos DB service.

在本地进行开发时,应用设置将取 local.settings.json 文件的值。When you're developing locally, app settings go into the local.settings.json file.

使用情况Usage

默认情况下,当写入函数中的输出参数时,将在数据库中创建一个文档。By default, when you write to the output parameter in your function, a document is created in your database. 本文档将自动生成的 GUID 作为文档 ID。This document has an automatically generated GUID as the document ID. 可以通过在传递给输出参数的 JSON 对象中指定 id 属性来指定输出文档的文档 ID。You can specify the document ID of the output document by specifying the id property in the JSON object passed to the output parameter.

备注

如果指定现有文档的 ID,它会被新的输出文档覆盖。When you specify the ID of an existing document, it gets overwritten by the new output document.

异常和返回代码Exceptions and return codes

绑定Binding 参考Reference
CosmosDBCosmosDB CosmosDB 错误代码CosmosDB Error Codes

host.json 设置host.json settings

本部分介绍版本 2.x 中可用于此绑定的全局配置设置。This section describes the global configuration settings available for this binding in version 2.x. 有关版本 2.x 中的全局配置设置的详细信息,请参阅 Azure Functions 版本 2.x 的 host.json 参考For more information about global configuration settings in version 2.x, see host.json reference for Azure Functions version 2.x.

{
    "version": "2.0",
    "extensions": {
        "cosmosDB": {
            "connectionMode": "Gateway",
            "protocol": "Https",
            "leaseOptions": {
                "leasePrefix": "prefix1"
            }
        }
    }
}
属性Property 默认Default 说明Description
GatewayModeGatewayMode 网关Gateway 连接到 Azure Cosmos DB 服务时该函数使用的连接模式。The connection mode used by the function when connecting to the Azure Cosmos DB service. 选项为 DirectGatewayOptions are Direct and Gateway
协议Protocol HttpsHttps 连接到 Azure Cosmos DB 服务时该函数使用的连接协议。The connection protocol used by the function when connection to the Azure Cosmos DB service. 参阅此处,了解两种模式的说明Read here for an explanation of both modes
leasePrefixleasePrefix 不适用n/a 应用中所有函数要使用的租用前缀。Lease prefix to use across all functions in an app.

后续步骤Next steps