您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

适用于 Azure Functions 1.x 的 Azure Cosmos DB 绑定Azure Cosmos DB bindings for Azure Functions 1.x

本文介绍如何在 Azure Functions 中使用 Azure Cosmos DB 绑定。This article explains how to work with Azure Cosmos DB bindings in Azure Functions. Azure Functions 支持 Azure Cosmos DB 的触发器、输入和输出绑定。Azure Functions supports trigger, input, and output bindings for Azure Cosmos DB.

备注

本文适用于 Azure Functions 1.x。This article is for Azure Functions 1.x. 若要了解如何在 Functions 2.x 中使用这些绑定,请参阅适用于 Azure Functions 2.x 的 Azure Cosmos DB 绑定For information about how to use these bindings in Functions 2.x, see Azure Cosmos DB bindings for Azure Functions 2.x.

此绑定最初名为 DocumentDB。This binding was originally named DocumentDB. 在 Functions 版本 1.x 中,仅触发器已重命名为 Cosmos DB;输入绑定、输出绑定和 NuGet 包保留 DocumentDB 名称。In Functions version 1.x, only the trigger was renamed Cosmos DB; the input binding, output binding, and NuGet package retain the DocumentDB name.

此参考信息面向 Azure Functions 开发人员。This is reference information for Azure Functions developers. Azure Functions 的新手请从以下资源入手:If you're new to Azure Functions, start with the following resources:

备注

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 MongoDBCassandra APIGremlin API表 APIFor 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, Cassandra API, Gremlin API, and Table API.

包 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.DocumentDB NuGet 包 1.x 版中提供了适用于 Functions 1.x 版的 Azure Cosmos DB 绑定。The Azure Cosmos DB bindings for Functions version 1.x are provided in the Microsoft.Azure.WebJobs.Extensions.DocumentDB NuGet package, version 1.x. azure-webjobs-sdk-extensions GitHub 存储库中提供了此绑定的源代码。Source code for the bindings is in the azure-webjobs-sdk-extensions GitHub repository.

下表说明了如何在每个开发环境中添加对此绑定的支持。The following table tells how to add support for this binding in each development environment.

开发环境Development environment 添加支持To add support in
Functions 1.xFunctions 1.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#Local development - C# script, JavaScript, F# 自动Automatic
门户开发Portal development 自动Automatic

触发器Trigger

Azure Cosmos DB 触发器使用 Azure Cosmos DB 更改源来侦听跨分区的插入和更新。The Azure Cosmos DB Trigger uses the Azure Cosmos DB Change Feed to listen for inserts and updates across partitions. 更改源发布插入和更新,不发布删除。The change feed publishes inserts and updates, not deletions.

触发器 - 示例Trigger - example

参阅语言特定的示例:See the language-specific example:

跳过触发器示例Skip trigger examples

触发器 - C# 示例Trigger - C# example

以下示例演示了一个 C# 函数。当指定数据库和集合中存在插入或更新操作时,会调用该函数。The following example shows a C# function that is invoked when there are inserts or updates in the specified database and collection.

using Microsoft.Azure.Documents;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;

namespace CosmosDBSamplesV1
{
    public static class CosmosTrigger
    {
        [FunctionName("CosmosTrigger")]
        public static void Run([CosmosDBTrigger(
            databaseName: "ToDoItems",
            collectionName: "Items",
            ConnectionStringSetting = "CosmosDBConnection",
            LeaseCollectionName = "leases",
            CreateLeaseCollectionIfNotExists = true)]IReadOnlyList<Document> documents,
            TraceWriter log)
        {
            if (documents != null && documents.Count > 0)
            {
                log.Info($"Documents modified: {documents.Count}");
                log.Info($"First document Id: {documents[0].Id}");
            }
        }
    }
}

跳过触发器示例Skip trigger examples

触发器 - C# 脚本示例Trigger - C# script example

以下示例演示 function.json 文件中的一个 Cosmos DB 触发器绑定以及使用该绑定的 C# 脚本函数The following example shows a Cosmos DB trigger binding in a function.json file and a C# script function that uses the binding. 修改 Cosmos DB 记录时,该函数会写入日志消息。The function writes log messages when Cosmos DB records are modified.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "type": "cosmosDBTrigger",
    "name": "documents",
    "direction": "in",
    "leaseCollectionName": "leases",
    "connectionStringSetting": "<connection-app-setting>",
    "databaseName": "Tasks",
    "collectionName": "Items",
    "createLeaseCollectionIfNotExists": true
}

C# 脚本代码如下所示:Here's the C# script code:

    #r "Microsoft.Azure.Documents.Client"
    
    using System;
    using Microsoft.Azure.Documents;
    using System.Collections.Generic;
    

    public static void Run(IReadOnlyList<Document> documents, TraceWriter log)
    {
        log.Info("Documents modified " + documents.Count);
        log.Info("First document Id " + documents[0].Id);
    }

跳过触发器示例Skip trigger examples

触发器 - JavaScript 示例Trigger - JavaScript example

以下示例演示 function.json 文件中的一个 Cosmos DB 触发器绑定以及使用该绑定的 JavaScript 脚本函数The following example shows a Cosmos DB trigger binding in a function.json file and a JavaScript function that uses the binding. 修改 Cosmos DB 记录时,该函数会写入日志消息。The function writes log messages when Cosmos DB records are modified.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "type": "cosmosDBTrigger",
    "name": "documents",
    "direction": "in",
    "leaseCollectionName": "leases",
    "connectionStringSetting": "<connection-app-setting>",
    "databaseName": "Tasks",
    "collectionName": "Items",
    "createLeaseCollectionIfNotExists": true
}

JavaScript 代码如下所示:Here's the JavaScript code:

    module.exports = function (context, documents) {
        context.log('First document Id modified : ', documents[0].id);

        context.done();
    }

触发器 - 特性Trigger - attributes

C# 类库中,使用 CosmosDBTrigger 特性。In C# class libraries, use the CosmosDBTrigger 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 Trigger - configuration. 下面是某个方法签名中的 CosmosDBTrigger 特性示例:Here's a CosmosDBTrigger attribute example in a method signature:

    [FunctionName("DocumentUpdates")]
    public static void Run(
        [CosmosDBTrigger("database", "collection", ConnectionStringSetting = "myCosmosDB")]
    IReadOnlyList<Document> documents,
        TraceWriter log)
    {
        ...
    }

有关完整示例,请参阅触发器 - C# 示例For a complete example, see Trigger - C# example.

触发器 - 配置Trigger - configuration

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

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 必须设置为 cosmosDBTriggerMust be set to cosmosDBTrigger.
directiondirection 必须设置为 inMust be set to in. 在 Azure 门户中创建触发器时,会自动设置该参数。This parameter is set automatically when you create the trigger in the Azure portal.
name name 函数代码中使用的变量名称,表示发生更改的文档列表。The variable name used in function code that represents the list of documents with changes.
connectionStringSettingconnectionStringSetting ConnectionStringSettingConnectionStringSetting 应用设置的名称,该应用设置包含用于连接到受监视的 Azure Cosmos DB 帐户的连接字符串。The name of an app setting that contains the connection string used to connect to the Azure Cosmos DB account being monitored.
databaseNamedatabaseName DatabaseNameDatabaseName 带有受监视的集合的 Azure Cosmos DB 数据库的名称。The name of the Azure Cosmos DB database with the collection being monitored.
collectionNamecollectionName CollectionNameCollectionName 受监视的集合的名称。The name of the collection being monitored.
leaseConnectionStringSettingleaseConnectionStringSetting LeaseConnectionStringSettingLeaseConnectionStringSetting (可选)应用设置的名称,该应用设置包含指向保留租用集合的服务的连接字符串。(Optional) The name of an app setting that contains the connection string to the service which holds the lease collection. 未设置时,使用 connectionStringSetting 值。When not set, the connectionStringSetting value is used. 在门户中创建绑定时,将自动设置该参数。This parameter is automatically set when the binding is created in the portal. 用于租用集合的连接字符串必须具有写入权限。The connection string for the leases collection must have write permissions.
leaseDatabaseNameleaseDatabaseName LeaseDatabaseNameLeaseDatabaseName (可选)数据库的名称,该数据库包含用于存储租用的集合。(Optional) The name of the database that holds the collection used to store leases. 未设置时,使用 databaseName 设置的值。When not set, the value of the databaseName setting is used. 在门户中创建绑定时,将自动设置该参数。This parameter is automatically set when the binding is created in the portal.
leaseCollectionNameleaseCollectionName LeaseCollectionNameLeaseCollectionName (可选)用于存储租用的集合的名称。(Optional) The name of the collection used to store leases. 未设置时,使用值 leasesWhen not set, the value leases is used.
createLeaseCollectionIfNotExistscreateLeaseCollectionIfNotExists CreateLeaseCollectionIfNotExistsCreateLeaseCollectionIfNotExists (可选)设置为 true 时,如果租用集合并不存在,将自动创建该集合。(Optional) When set to true, the leases collection is automatically created when it doesn't already exist. 默认值为 falseThe default value is false.
leasesCollectionThroughputleasesCollectionThroughput LeasesCollectionThroughputLeasesCollectionThroughput (可选)在创建租用集合时,定义要分配的请求单位的数量。(Optional) Defines the amount of Request Units to assign when the leases collection is created. 仅当 createLeaseCollectionIfNotExists 设置为 true 时,才会使用该设置。This setting is only used When createLeaseCollectionIfNotExists is set to true. 使用门户创建绑定时,将自动设置该参数。This parameter is automatically set when the binding is created using the portal.
leaseCollectionPrefixleaseCollectionPrefix LeaseCollectionPrefixLeaseCollectionPrefix (可选)设置后,此项向在此 Function 的“租用”集合中创建的租用添加一个前缀,实际上就是允许两个不同的 Azure Functions(使用不同的前缀)共享同一“租用”集合。(Optional) When set, it adds a prefix to the leases created in the Lease collection for this Function, effectively allowing two separate Azure Functions to share the same Lease collection by using different prefixes.
feedPollDelayfeedPollDelay FeedPollDelayFeedPollDelay (可选)设置后,此项以毫秒为单位定义在所有当前更改均耗尽后,源上新更改的分区轮询间的延迟。(Optional) When set, it defines, in milliseconds, the delay in between polling a partition for new changes on the feed, after all current changes are drained. 默认为 5000(5 秒)。Default is 5000 (5 seconds).
leaseAcquireIntervalleaseAcquireInterval LeaseAcquireIntervalLeaseAcquireInterval (可选)设置后,此项以毫秒为单位定义启动一个计算任务的时间间隔(前提是分区在已知的主机实例中均匀分布)。(Optional) When set, it defines, in milliseconds, the interval to kick off a task to compute if partitions are distributed evenly among known host instances. 默认为 13000(13 秒)。Default is 13000 (13 seconds).
leaseExpirationIntervalleaseExpirationInterval LeaseExpirationIntervalLeaseExpirationInterval (可选)设置后,此项以毫秒为单位定义在表示分区的租用上进行租用的时间间隔。(Optional) When set, it defines, in milliseconds, the interval for which the lease is taken on a lease representing a partition. 如果在此时间间隔内不续订租用,则该租用会过期,分区的所有权会转移到另一个实例。If the lease is not renewed within this interval, it will cause it to expire and ownership of the partition will move to another instance. 默认为 60000(60 秒)。Default is 60000 (60 seconds).
leaseRenewIntervalleaseRenewInterval LeaseRenewIntervalLeaseRenewInterval (可选)设置后,此项以毫秒为单位定义当前由实例拥有的分区的所有租用的续订时间间隔。(Optional) When set, it defines, in milliseconds, the renew interval for all leases for partitions currently held by an instance. 默认为 17000(17 秒)。Default is 17000 (17 seconds).
checkpointFrequencycheckpointFrequency CheckpointFrequencyCheckpointFrequency (可选)设置后,此项以毫秒为单位定义租用检查点的时间间隔。(Optional) When set, it defines, in milliseconds, the interval between lease checkpoints. 默认为始终在进行每个 Function 调用之后进行检查。Default is always after each Function call.
maxItemsPerInvocationmaxItemsPerInvocation MaxItemsPerInvocationMaxItemsPerInvocation (可选)设置后,此项对每次 Function 调用收到的项目的最大数目进行自定义。(Optional) When set, it customizes the maximum amount of items received per Function call.
startFromBeginningstartFromBeginning StartFromBeginningStartFromBeginning (可选)设置时,它会告诉触发器从集合历史记录的开头而不是当前时间开始读取更改。(Optional) When set, it tells the Trigger to start reading changes from the beginning of the history of the collection instead of the current time. 这仅在触发器第一次启动时起作用,因为在后续运行中,已存储检查点。This only works the first time the Trigger starts, as in subsequent runs, the checkpoints are already stored. 如果已经创建租约,则将此值设置为 true 无效。Setting this to true when there are leases already created has no effect.

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

触发器 - 用法Trigger - usage

触发器需要第二个集合,该集合用于存储各分区的_租用_。The trigger requires a second collection that it uses to store leases over the partitions. 必须提供受监视的集合和包含租用的集合,触发器才能正常工作。Both the collection being monitored and the collection that contains the leases must be available for the trigger to work.

重要

如果多个函数都配置为对同一集合使用 Cosmos DB 触发器,则每个函数都应使用专用租用集合,否则应该为每个函数指定不同的 LeaseCollectionPrefixIf multiple functions are configured to use a Cosmos DB trigger for the same collection, each of the functions should use a dedicated lease collection or specify a different LeaseCollectionPrefix for each function. 否则,将只触发其中一个函数。Otherwise, only one of the functions will be triggered. 有关前缀的信息,请参阅“配置”部分For information about the prefix, see the Configuration section.

该触发器并不指示是更新还是插入文档,它仅提供文档本身。The trigger doesn't indicate whether a document was updated or inserted, it just provides the document itself. 如果需要以不同方式处理更新和插入,可通过实现用于插入或更新的时间戳字段来执行该操作。If you need to handle updates and inserts differently, you could do that by implementing timestamp fields for insertion or update.

输入Input

Azure Cosmos DB 输入绑定会使用 SQL API 检索一个或多个 Azure Cosmos DB 文档,并将其传递给函数的输入参数。The Azure Cosmos DB input binding uses the SQL API to retrieve one or more Azure Cosmos DB documents and passes them to the input parameter of the function. 可根据调用函数的触发器确定文档 ID 或查询参数。The document ID or query parameters can be determined based on the trigger that invokes the function.

输入 - 示例Input - examples

请指定一个 ID 值,以便查看可以读取单个文档的特定于语言的示例:See the language-specific examples that read a single document by specifying an ID value:

跳过输入示例Skip input examples

输入 - C# 示例Input - C# examples

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

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

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

跳过输入示例Skip input examples

队列触发器,从 JSON 查找 ID (C#)Queue trigger, look up ID from JSON (C#)

以下示例演示检索单个文档的 C# 函数The following example shows a C# function that retrieves a single document. 该函数由包含 JSON 对象的队列消息触发。The function is triggered by a queue message that contains a JSON object. 队列触发器将 JSON 解析成名为 ToDoItemLookup 的对象,其中包含要查找的 ID。The queue trigger parses the JSON into an object named ToDoItemLookup, which contains the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem 文档。That ID is used to retrieve a ToDoItem document from the specified database and collection.

namespace CosmosDBSamplesV1
{
    public class ToDoItemLookup
    {
        public string ToDoItemId { get; set; }
    }
}
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;

namespace CosmosDBSamplesV1
{
    public static class DocByIdFromJSON
    {
        [FunctionName("DocByIdFromJSON")]
        public static void Run(
            [QueueTrigger("todoqueueforlookup")] ToDoItemLookup toDoItemLookup,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{ToDoItemId}")]ToDoItem toDoItem,
            TraceWriter log)
        {
            log.Info($"C# Queue trigger function processed Id={toDoItemLookup?.ToDoItemId}");

            if (toDoItem == null)
            {
                log.Info($"ToDo item not found");
            }
            else
            {
                log.Info($"Found ToDo item, Description={toDoItem.Description}");
            }
        }
    }
}

跳过输入示例Skip input examples

HTTP 触发器,从查询字符串查找 ID (C#)HTTP trigger, look up ID from query string (C#)

以下示例演示检索单个文档的 C# 函数The following example shows a C# function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID。The function is triggered by an HTTP request that uses a query string to specify the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem 文档。That ID is used to retrieve a ToDoItem document from the specified database and collection.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Net;
using System.Net.Http;

namespace CosmosDBSamplesV1
{
    public static class DocByIdFromQueryString
    {
        [FunctionName("DocByIdFromQueryString")]
        public static HttpResponseMessage Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{Query.id}")] ToDoItem toDoItem,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            if (toDoItem == null)
            {
                log.Info($"ToDo item not found");
            }
            else
            {
                log.Info($"Found ToDo item, Description={toDoItem.Description}");
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

跳过输入示例Skip input examples

HTTP 触发器,从路由数据查找 ID (C#)HTTP trigger, look up ID from route data (C#)

以下示例演示检索单个文档的 C# 函数The following example shows a C# function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由数据用于指定要查找的 ID。The function is triggered by an HTTP request that uses route data to specify the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem 文档。That ID is used to retrieve a ToDoItem document from the specified database and collection.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Net;
using System.Net.Http;

namespace CosmosDBSamplesV1
{
    public static class DocByIdFromRouteData
    {
        [FunctionName("DocByIdFromRouteData")]
        public static HttpResponseMessage Run(
            [HttpTrigger(
                AuthorizationLevel.Anonymous, "get", "post",
                Route = "todoitems/{id}")]HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{id}")] ToDoItem toDoItem,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            if (toDoItem == null)
            {
                log.Info($"ToDo item not found");
            }
            else
            {
                log.Info($"Found ToDo item, Description={toDoItem.Description}");
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

跳过输入示例Skip input examples

HTTP 触发器,使用 SqlQuery 从路由数据查找 ID (C#)HTTP trigger, look up ID from route data, using SqlQuery (C#)

以下示例演示检索单个文档的 C# 函数The following example shows a C# function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由数据用于指定要查找的 ID。The function is triggered by an HTTP request that uses route data to specify the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem 文档。That ID is used to retrieve a ToDoItem document from the specified database and collection.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;

namespace CosmosDBSamplesV1
{
    public static class DocByIdFromRouteDataUsingSqlQuery
    {
        [FunctionName("DocByIdFromRouteDataUsingSqlQuery")]
        public static HttpResponseMessage Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
                Route = "todoitems2/{id}")]HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                SqlQuery = "select * from ToDoItems r where r.id = {id}")] IEnumerable<ToDoItem> toDoItems,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            foreach (ToDoItem toDoItem in toDoItems)
            {
                log.Info(toDoItem.Description);
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

跳过输入示例Skip input examples

HTTP 触发器,使用 SqlQuery 获取多个文档 (C#)HTTP trigger, get multiple docs, using SqlQuery (C#)

以下示例演示检索文档列表的 C# 函数The following example shows a C# function that retrieves a list of documents. 此函数由 HTTP 请求触发。The function is triggered by an HTTP request. 此查询在 SqlQuery 特性属性中指定。The query is specified in the SqlQuery attribute property.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;

namespace CosmosDBSamplesV1
{
    public static class DocsBySqlQuery
    {
        [FunctionName("DocsBySqlQuery")]
        public static HttpResponseMessage Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
                HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                SqlQuery = "SELECT top 2 * FROM c order by c._ts desc")]
                IEnumerable<ToDoItem> toDoItems,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            foreach (ToDoItem toDoItem in toDoItems)
            {
                log.Info(toDoItem.Description);
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

跳过输入示例Skip input examples

HTTP 触发器,使用 DocumentClient 获取多个文档 (C#)HTTP trigger, get multiple docs, using DocumentClient (C#)

以下示例演示检索文档列表的 C# 函数The following example shows a C# function that retrieves a list of documents. 此函数由 HTTP 请求触发。The function is triggered by an HTTP request. 此代码使用 Azure Cosmos DB 绑定提供的 DocumentClient 实例来读取文档列表。The code uses a DocumentClient instance provided by the Azure Cosmos DB binding to read a list of documents. DocumentClient 实例也可用于写入操作。The DocumentClient instance could also be used for write operations.

using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace CosmosDBSamplesV1
{
    public static class DocsByUsingDocumentClient
    {
        [FunctionName("DocsByUsingDocumentClient")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
            [DocumentDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")] DocumentClient client,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            Uri collectionUri = UriFactory.CreateDocumentCollectionUri("ToDoItems", "Items");
            string searchterm = req.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "searchterm", true) == 0)
                .Value;

            if (searchterm == null)
            {
                return req.CreateResponse(HttpStatusCode.NotFound);
            }

            log.Info($"Searching for word: {searchterm} using Uri: {collectionUri.ToString()}");
            IDocumentQuery<ToDoItem> query = client.CreateDocumentQuery<ToDoItem>(collectionUri)
                .Where(p => p.Description.Contains(searchterm))
                .AsDocumentQuery();

            while (query.HasMoreResults)
            {
                foreach (ToDoItem result in await query.ExecuteNextAsync())
                {
                    log.Info(result.Description);
                }
            }
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

跳过输入示例Skip input examples

输入 - C# 脚本示例Input - C# script examples

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

HTTP 触发器示例引用简单的 ToDoItem 类型:The HTTP trigger examples refer to a simple ToDoItem type:

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

跳过输入示例Skip input examples

队列触发器,从字符串查找 ID(C# 脚本)Queue trigger, look up ID from string (C# script)

以下示例演示 function.json 文件中的一个 Cosmos DB 输入绑定以及使用该绑定的 C# 脚本函数The following example shows a Cosmos DB input binding in a function.json file and a C# script function that uses the binding. 该函数读取单个文档,并更新文档的文本值。The function reads a single document and updates the document's text value.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "name": "inputDocument",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "id" : "{queueTrigger}",
    "partitionKey": "{partition key value}",
    "connection": "MyAccount_COSMOSDB",
    "direction": "in"
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

    using System;

    // Change input document contents using Azure Cosmos DB input binding
    public static void Run(string myQueueItem, dynamic inputDocument)
    {
        inputDocument.text = "This has changed.";
    }

跳过输入示例Skip input examples

队列触发器,使用 SqlQuery 获取多个文档(C# 脚本)Queue trigger, get multiple docs, using SqlQuery (C# script)

以下示例演示 function.json 文件中的一个 Azure Cosmos DB 输入绑定以及使用该绑定的 C# 脚本函数The following example shows an Azure Cosmos DB input binding in a function.json file and a C# script function that uses the binding. 该函数使用队列触发器自定义查询参数检索 SQL 查询指定的多个文档。The function retrieves multiple documents specified by a SQL query, using a queue trigger to customize the query parameters.

队列触发器提供参数 departmentIdThe queue trigger provides a parameter departmentId. { "departmentId" : "Finance" } 的队列消息将返回财务部的所有记录。A queue message of { "departmentId" : "Finance" } would return all records for the finance department.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "name": "documents",
    "type": "documentdb",
    "direction": "in",
    "databaseName": "MyDb",
    "collectionName": "MyCollection",
    "sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
    "connection": "CosmosDBConnection"
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

    public static void Run(QueuePayload myQueueItem, IEnumerable<dynamic> documents)
    {
        foreach (var doc in documents)
        {
            // operate on each document
        }
    }

    public class QueuePayload
    {
        public string departmentId { get; set; }
    }

跳过输入示例Skip input examples

HTTP 触发器,从查询字符串查找 ID(C# 脚本)HTTP trigger, look up ID from query string (C# script)

以下示例演示检索单个文档的 C# 脚本函数The following example shows a C# script function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID。The function is triggered by an HTTP request that uses a query string to specify the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem 文档。That ID is used to retrieve a ToDoItem document from the specified database and collection.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "Id": "{Query.id}"
    }
  ],
  "disabled": true
}

C# 脚本代码如下所示:Here's the C# script code:

using System.Net;

public static HttpResponseMessage Run(HttpRequestMessage req, ToDoItem toDoItem, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    if (toDoItem == null)
    {
        log.Info($"ToDo item not found");
    }
    else
    {
        log.Info($"Found ToDo item, Description={toDoItem.Description}");
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

跳过输入示例Skip input examples

HTTP 触发器,从路由数据查找 ID(C# 脚本)HTTP trigger, look up ID from route data (C# script)

以下示例演示检索单个文档的 C# 脚本函数The following example shows a C# script function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由数据用于指定要查找的 ID。The function is triggered by an HTTP request that uses route data to specify the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem 文档。That ID is used to retrieve a ToDoItem document from the specified database and collection.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ],
      "route":"todoitems/{id}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "Id": "{id}"
    }
  ],
  "disabled": false
}

C# 脚本代码如下所示:Here's the C# script code:

using System.Net;

public static HttpResponseMessage Run(HttpRequestMessage req, ToDoItem toDoItem, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    if (toDoItem == null)
    {
        log.Info($"ToDo item not found");
    }
    else
    {
        log.Info($"Found ToDo item, Description={toDoItem.Description}");
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

跳过输入示例Skip input examples

HTTP 触发器,使用 SqlQuery 获取多个文档(C# 脚本)HTTP trigger, get multiple docs, using SqlQuery (C# script)

以下示例演示检索文档列表的 C# 脚本函数The following example shows a C# script function that retrieves a list of documents. 此函数由 HTTP 请求触发。The function is triggered by an HTTP request. 此查询在 SqlQuery 特性属性中指定。The query is specified in the SqlQuery attribute property.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "toDoItems",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "sqlQuery": "SELECT top 2 * FROM c order by c._ts desc"
    }
  ],
  "disabled": false
}

C# 脚本代码如下所示:Here's the C# script code:

using System.Net;

public static HttpResponseMessage Run(HttpRequestMessage req, IEnumerable<ToDoItem> toDoItems, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    foreach (ToDoItem toDoItem in toDoItems)
    {
        log.Info(toDoItem.Description);
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

跳过输入示例Skip input examples

HTTP 触发器,使用 DocumentClient 获取多个文档(C# 脚本)HTTP trigger, get multiple docs, using DocumentClient (C# script)

以下示例演示检索文档列表的 C# 脚本函数The following example shows a C# script function that retrieves a list of documents. 此函数由 HTTP 请求触发。The function is triggered by an HTTP request. 此代码使用 Azure Cosmos DB 绑定提供的 DocumentClient 实例来读取文档列表。The code uses a DocumentClient instance provided by the Azure Cosmos DB binding to read a list of documents. DocumentClient 实例也可用于写入操作。The DocumentClient instance could also be used for write operations.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "client",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "inout"
    }
  ],
  "disabled": false
}

C# 脚本代码如下所示:Here's the C# script code:

#r "Microsoft.Azure.Documents.Client"

using System.Net;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, DocumentClient client, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    Uri collectionUri = UriFactory.CreateDocumentCollectionUri("ToDoItems", "Items");
    string searchterm = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "searchterm", true) == 0)
        .Value;

    if (searchterm == null)
    {
        return req.CreateResponse(HttpStatusCode.NotFound);
    }

    log.Info($"Searching for word: {searchterm} using Uri: {collectionUri.ToString()}");
    IDocumentQuery<ToDoItem> query = client.CreateDocumentQuery<ToDoItem>(collectionUri)
        .Where(p => p.Description.Contains(searchterm))
        .AsDocumentQuery();

    while (query.HasMoreResults)
    {
        foreach (ToDoItem result in await query.ExecuteNextAsync())
        {
            log.Info(result.Description);
        }
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

跳过输入示例Skip input examples

输入 - JavaScript 示例Input - JavaScript examples

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

跳过输入示例Skip input examples

队列触发器,从 JSON 查找 ID (JavaScript)Queue trigger, look up ID from JSON (JavaScript)

以下示例演示 function.json 文件中的一个 Cosmos DB 输入绑定以及使用该绑定的 JavaScript 函数The following example shows a Cosmos DB input binding in a function.json file and a JavaScript function that uses the binding. 该函数读取单个文档,并更新文档的文本值。The function reads a single document and updates the document's text value.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "name": "inputDocumentIn",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "id" : "{queueTrigger_payload_property}",
    "partitionKey": "{queueTrigger_payload_property}",
    "connection": "MyAccount_COSMOSDB",
    "direction": "in"
},
{
    "name": "inputDocumentOut",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": false,
    "partitionKey": "{queueTrigger_payload_property}",
    "connection": "MyAccount_COSMOSDB",
    "direction": "out"
}

配置部分解释了这些属性。The configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

    // Change input document contents using Azure Cosmos DB input binding, using context.bindings.inputDocumentOut
    module.exports = function (context) {
    context.bindings.inputDocumentOut = context.bindings.inputDocumentIn;
    context.bindings.inputDocumentOut.text = "This was updated!";
    context.done();
    };

跳过输入示例Skip input examples

HTTP 触发器,从查询字符串查找 ID (JavaScript)HTTP trigger, look up ID from query string (JavaScript)

以下示例演示检索单个文档的 JavaScript 函数The following example shows a JavaScript function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID。The function is triggered by an HTTP request that uses a query string to specify the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem 文档。That ID is used to retrieve a ToDoItem document from the specified database and collection.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "Id": "{Query.id}"
    }
  ],
  "disabled": true
}

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context, req, toDoItem) {
    context.log('JavaScript queue trigger function processed work item');
    if (!toDoItem)
    {
        context.log("ToDo item not found");
    }
    else
    {
        context.log("Found ToDo item, Description=" + toDoItem.Description);
    }

    context.done();
};

跳过输入示例Skip input examples

HTTP 触发器,从路由数据查找 ID (JavaScript)HTTP trigger, look up ID from route data (JavaScript)

以下示例演示检索单个文档的 JavaScript 函数The following example shows a JavaScript function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID。The function is triggered by an HTTP request that uses a query string to specify the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem 文档。That ID is used to retrieve a ToDoItem document from the specified database and collection.

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ],
      "route":"todoitems/{id}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "Id": "{id}"
    }
  ],
  "disabled": false
}

JavaScript 代码如下所示:Here's the JavaScript code:

module.exports = function (context, req, toDoItem) {
    context.log('JavaScript queue trigger function processed work item');
    if (!toDoItem)
    {
        context.log("ToDo item not found");
    }
    else
    {
        context.log("Found ToDo item, Description=" + toDoItem.Description);
    }

    context.done();
};

跳过输入示例Skip input examples

队列触发器,使用 SqlQuery 获取多个文档 (JavaScript)Queue trigger, get multiple docs, using SqlQuery (JavaScript)

以下示例演示 function.json 文件中的一个 Azure Cosmos DB 输入绑定以及使用该绑定的 JavaScript 函数The following example shows an Azure Cosmos DB input binding in a function.json file and a JavaScript function that uses the binding. 该函数使用队列触发器自定义查询参数检索 SQL 查询指定的多个文档。The function retrieves multiple documents specified by a SQL query, using a queue trigger to customize the query parameters.

队列触发器提供参数 departmentIdThe queue trigger provides a parameter departmentId. { "departmentId" : "Finance" } 的队列消息将返回财务部的所有记录。A queue message of { "departmentId" : "Finance" } would return all records for the finance department.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "name": "documents",
    "type": "documentdb",
    "direction": "in",
    "databaseName": "MyDb",
    "collectionName": "MyCollection",
    "sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
    "connection": "CosmosDBConnection"
}

配置部分解释了这些属性。The configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

    module.exports = function (context, input) {
        var documents = context.bindings.documents;
        for (var i = 0; i < documents.length; i++) {
            var document = documents[i];
            // operate on each document
        }
        context.done();
    };

跳过输入示例Skip input examples

输入 - F# 示例Input - F# examples

以下示例演示 function.json 文件中的一个 Cosmos DB 输入绑定以及使用该绑定的 F# 函数The following example shows a Cosmos DB input binding in a function.json file and a F# function that uses the binding. 该函数读取单个文档,并更新文档的文本值。The function reads a single document and updates the document's text value.

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "name": "inputDocument",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "id" : "{queueTrigger}",
    "connection": "MyAccount_COSMOSDB",
    "direction": "in"
}

配置部分解释了这些属性。The configuration section explains these properties.

F# 代码如下所示:Here's the F# code:

    (* Change input document contents using Azure Cosmos DB input binding *)
    open FSharp.Interop.Dynamic
    let Run(myQueueItem: string, inputDocument: obj) =
    inputDocument?text <- "This has changed."

此示例要求具有指定 FSharp.Interop.DynamicDynamitey NuGet 依赖关系的 project.json 文件:This example requires a project.json file that specifies the FSharp.Interop.Dynamic and Dynamitey NuGet dependencies:

{
    "frameworks": {
        "net46": {
            "dependencies": {
                "Dynamitey": "1.0.2",
                "FSharp.Interop.Dynamic": "3.0.0"
            }
        }
    }
}

若要添加 project.json 文件,请参阅 F# 包管理To add a project.json file, see F# package management.

输入 - 特性Input - attributes

C# 类库中,使用 DocumentDB 特性。In C# class libraries, use the DocumentDB 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 the following configuration section.

输入 - 配置Input - configuration

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

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 必须设置为 documentdbMust be set to documentdb.
directiondirection 必须设置为 inMust be set to in.
name name 表示函数中的文档的绑定参数的名称。Name of the binding parameter that represents the document in the function.
databaseNamedatabaseName DatabaseNameDatabaseName 包含文档的数据库。The database containing the document.
collectionNamecollectionName CollectionNameCollectionName 包含文档的集合的名称。The name of the collection that contains the document.
idid IdId 要检索的文档的 ID。The ID of the document to retrieve. 此属性支持绑定表达式This property supports binding expressions. 不要同时设置 idsqlQuery 属性。Don't set both the id and sqlQuery properties. 如果上述两个属性都未设置,则会检索整个集合。If you don't set either one, the entire collection is retrieved.
sqlQuerysqlQuery SqlQuerySqlQuery 用于检索多个文档的 Azure Cosmos DB SQL 查询。An Azure Cosmos DB SQL query used for retrieving multiple documents. 该属性支持运行时绑定,如以下示例中所示:SELECT * FROM c where c.departmentId = {departmentId}The property supports runtime bindings, as in this example: SELECT * FROM c where c.departmentId = {departmentId}. 不要同时设置 idsqlQuery 属性。Don't set both the id and sqlQuery properties. 如果上述两个属性都未设置,则会检索整个集合。If you don't set either one, the entire collection is retrieved.
连接connection ConnectionStringSettingConnectionStringSetting 内含 Azure Cosmos DB 连接字符串的应用设置的名称。The name of the app setting containing your Azure Cosmos DB connection string.
partitionKeypartitionKey PartitionKeyPartitionKey 指定用于查找分区键值。Specifies the partition key value for the lookup. 可以包含绑定参数。May include binding parameters.

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

输入 - 用法Input - usage

在 C# 函数和 F# 函数中,函数成功退出后,通过命名输入参数对输入文档所做的任何更改都会自动保存。In C# and F# functions, when the function exits successfully, any changes made to the input document via named input parameters are automatically persisted.

在 JavaScript 函数中,函数退出时不会自动进行更新。In JavaScript functions, updates are not made automatically upon function exit. 请改用 context.bindings.<documentName>Incontext.bindings.<documentName>Out 进行更新。Instead, use context.bindings.<documentName>In and context.bindings.<documentName>Out to make updates. 请参阅 JavaScript 示例See the JavaScript example.

OutputOutput

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.

输出 - 示例Output - examples

请参阅语言特定的示例:See the language-specific examples:

另请参阅使用 DocumentClient输入示例See also the input example that uses DocumentClient.

跳过输出示例Skip output examples

输出 - C# 示例Output - C# examples

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

  • 队列触发器,写入一个文档Queue trigger, write one doc
  • 队列触发器,使用 IAsyncCollector 来写入文档Queue trigger, write docs using IAsyncCollector

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

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

跳过输出示例Skip output examples

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

以下示例演示一个使用队列存储消息中提供的数据,将文档添加到数据库的 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 System;

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

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

跳过输出示例Skip output examples

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

以下示例演示了一个 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;

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

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

跳过输出示例Skip output examples

输出 - C# 脚本示例Output - C# script examples

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

  • 队列触发器,写入一个文档Queue trigger, write one doc
  • 队列触发器,使用 IAsyncCollector 来写入文档Queue trigger, write docs using IAsyncCollector

跳过输出示例Skip output examples

队列触发器,写入一个文档(C# 脚本)Queue trigger, write one doc (C# script)

以下示例演示 function.json 文件中的一个 Azure Cosmos DB 输出绑定以及使用该绑定的 C# 脚本函数The following example shows an Azure Cosmos DB output binding in a function.json file and a C# script function that uses the binding. 该函数使用一个用于某个队列的队列输入绑定,该队列以下列格式接收 JSON:The function uses a queue input binding for a queue that receives JSON in the following format:

{
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

该函数按下列格式为每个记录创建 Azure Cosmos DB 文档:The function creates Azure Cosmos DB documents in the following format for each record:

{
    "id": "John Henry-123456",
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "name": "employeeDocument",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connection": "MyAccount_COSMOSDB",
    "direction": "out"
}

配置部分解释了这些属性。The configuration section explains these properties.

C# 脚本代码如下所示:Here's the C# script code:

    #r "Newtonsoft.Json"

    using Microsoft.Azure.WebJobs.Host;
    using Newtonsoft.Json.Linq;

    public static void Run(string myQueueItem, out object employeeDocument, TraceWriter log)
    {
        log.Info($"C# Queue trigger function processed: {myQueueItem}");

        dynamic employee = JObject.Parse(myQueueItem);

        employeeDocument = new {
            id = employee.name + "-" + employee.employeeId,
            name = employee.name,
            employeeId = employee.employeeId,
            address = employee.address
        };
    }

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

若要创建多个文档,可以绑定到 ICollector<T>IAsyncCollector<T>,其中 T 是受支持的类型之一。To create multiple documents, you can bind to ICollector<T> or IAsyncCollector<T> where T is one of the supported types.

此示例引用简单的 ToDoItem 类型:This example refers to a simple ToDoItem type:

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

function.json 文件如下所示:Here's the function.json file:

{
  "bindings": [
    {
      "name": "toDoItemsIn",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "todoqueueforwritemulti",
      "connection": "AzureWebJobsStorage"
    },
    {
      "type": "documentDB",
      "name": "toDoItemsOut",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 脚本代码如下所示:Here's the C# script code:

using System;

public static async Task Run(ToDoItem[] toDoItemsIn, IAsyncCollector<ToDoItem> toDoItemsOut, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed {toDoItemsIn?.Length} items");

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

跳过输出示例Skip output examples

输出 - JavaScript 示例Output - JavaScript examples

以下示例演示 function.json 文件中的一个 Azure Cosmos DB 输出绑定以及使用该绑定的 JavaScript 函数The following example shows an Azure Cosmos DB output binding in a function.json file and a JavaScript function that uses the binding. 该函数使用一个用于某个队列的队列输入绑定,该队列以下列格式接收 JSON:The function uses a queue input binding for a queue that receives JSON in the following format:

{
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

该函数按下列格式为每个记录创建 Azure Cosmos DB 文档:The function creates Azure Cosmos DB documents in the following format for each record:

{
    "id": "John Henry-123456",
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "name": "employeeDocument",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connection": "MyAccount_COSMOSDB",
    "direction": "out"
}

配置部分解释了这些属性。The configuration section explains these properties.

JavaScript 代码如下所示:Here's the JavaScript code:

    module.exports = function (context) {

      context.bindings.employeeDocument = JSON.stringify({
        id: context.bindings.myQueueItem.name + "-" + context.bindings.myQueueItem.employeeId,
        name: context.bindings.myQueueItem.name,
        employeeId: context.bindings.myQueueItem.employeeId,
        address: context.bindings.myQueueItem.address
      });

      context.done();
    };

跳过输出示例Skip output examples

输出 - F# 示例Output - F# examples

以下示例演示 function.json 文件中的一个 Azure Cosmos DB 输出绑定以及使用该绑定的 F# 函数The following example shows an Azure Cosmos DB output binding in a function.json file and an F# function that uses the binding. 该函数使用一个用于某个队列的队列输入绑定,该队列以下列格式接收 JSON:The function uses a queue input binding for a queue that receives JSON in the following format:

{
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

该函数按下列格式为每个记录创建 Azure Cosmos DB 文档:The function creates Azure Cosmos DB documents in the following format for each record:

{
    "id": "John Henry-123456",
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:

{
    "name": "employeeDocument",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connection": "MyAccount_COSMOSDB",
    "direction": "out"
}

配置部分解释了这些属性。The configuration section explains these properties.

F# 代码如下所示:Here's the F# code:

    open FSharp.Interop.Dynamic
    open Newtonsoft.Json

    type Employee = {
      id: string
      name: string
      employeeId: string
      address: string
    }

    let Run(myQueueItem: string, employeeDocument: byref<obj>, log: TraceWriter) =
      log.Info(sprintf "F# Queue trigger function processed: %s" myQueueItem)
      let employee = JObject.Parse(myQueueItem)
      employeeDocument <-
        { id = sprintf "%s-%s" employee?name employee?employeeId
          name = employee?name
          employeeId = employee?employeeId
          address = employee?address }

此示例要求具有指定 FSharp.Interop.DynamicDynamitey NuGet 依赖关系的 project.json 文件:This example requires a project.json file that specifies the FSharp.Interop.Dynamic and Dynamitey NuGet dependencies:

{
    "frameworks": {
        "net46": {
          "dependencies": {
            "Dynamitey": "1.0.2",
            "FSharp.Interop.Dynamic": "3.0.0"
           }
        }
    }
}

若要添加 project.json 文件,请参阅 F# 包管理To add a project.json file, see F# package management.

输出 - 特性Output - attributes

C# 类库中,使用 DocumentDB 特性。In C# class libraries, use the DocumentDB 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. 下面是某个方法签名中的 DocumentDB 特性示例:Here's a DocumentDB attribute example in a method signature:

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

有关完整示例,请参阅输出 - C# 示例For a complete example, see Output - C# example.

输出 - 配置Output - configuration

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

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 必须设置为 documentdbMust be set to documentdb.
directiondirection 必须设置为 outMust be set to out.
name name 表示函数中的文档的绑定参数的名称。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, defines the partition key path for the created collection.
collectionThroughputcollectionThroughput CollectionThroughputCollectionThroughput CreateIfNotExists 为 true 时,将定义所创建集合的吞吐量When CreateIfNotExists is true, defines the throughput of the created collection.
连接connection ConnectionStringSettingConnectionStringSetting 内含 Azure Cosmos DB 连接字符串的应用设置的名称。The name of the app setting containing your Azure Cosmos DB connection string.

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

输出 - 用法Output - 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

后续步骤Next steps