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

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

Note

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

此绑定最初名为 DocumentDB。This binding was originally named DocumentDB. 在 Functions 2.x 版中,触发器、绑定和包均称为 Cosmos DB。In Functions version 2.x, the trigger, bindings, and package are all named Cosmos DB.

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

受支持的 APISupported APIs

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.

包 - Functions 2.xPackages - Functions 2.x

Microsoft.Azure.WebJobs.Extensions.CosmosDB NuGet 包 3.x 版中提供了 Functions 2.x 版的 Azure Cosmos DB 绑定。The Azure Cosmos DB bindings for Functions version 2.x are provided in the Microsoft.Azure.WebJobs.Extensions.CosmosDB NuGet package, version 3.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 2.xFunctions 2.x
本地开发 - C# 类库Local development - C# class library 安装包Install the package
本地开发 - C# 脚本、JavaScript、F#、JavaLocal development - C# script, JavaScript, F#, Java 注册扩展Register the extension
门户开发Portal development 添加输出绑定时安装Install when adding output binding

若要了解如何更新门户中的现有绑定扩展而不必重新发布函数应用项目,请参阅更新扩展To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

触发器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;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class CosmosTrigger
    {
        [FunctionName("CosmosTrigger")]
        public static void Run([CosmosDBTrigger(
            databaseName: "ToDoItems",
            collectionName: "Items",
            ConnectionStringSetting = "CosmosDBConnection",
            LeaseCollectionName = "leases",
            CreateLeaseCollectionIfNotExists = true)]IReadOnlyList<Document> documents,
            ILogger log)
        {
            if (documents != null && documents.Count > 0)
            {
                log.LogInformation($"Documents modified: {documents.Count}");
                log.LogInformation($"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.DocumentDB.Core"

    using System;
    using Microsoft.Azure.Documents;
    using System.Collections.Generic;
    using Microsoft.Extensions.Logging;

    public static void Run(IReadOnlyList<Document> documents, ILogger log)
    {
      log.LogInformation("Documents modified " + documents.Count);
      log.LogInformation("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();
    }

触发器 - Java 示例Trigger - Java example

以下示例展示了 function.json 文件中的一个 Cosmos DB 触发器绑定以及使用该绑定的 Java 函数The following example shows a Cosmos DB trigger binding in function.json file and a Java function that uses the binding. 当指定数据库和集合中发生插入或更新操作时,会调用该函数。The function is involved when there are inserts or updates in the specified database and collection.

{
    "type": "cosmosDBTrigger",
    "name": "items",
    "direction": "in",
    "leaseCollectionName": "leases",
    "connectionStringSetting": "AzureCosmosDBConnection",
    "databaseName": "ToDoList",
    "collectionName": "Items",
    "createLeaseCollectionIfNotExists": false
}

下面是 Java 代码:Here's the Java code:

    @FunctionName("cosmosDBMonitor")
    public void cosmosDbProcessor(
        @CosmosDBTrigger(name = "items",
            databaseName = "ToDoList",
            collectionName = "Items",
            leaseCollectionName = "leases",
            createLeaseCollectionIfNotExists = true,
            connectionStringSetting = "AzureCosmosDBConnection") String[] items,
            final ExecutionContext context ) {
                context.getLogger().info(items.length + "item(s) is/are changed.");
            }

Java 函数运行时库中,对其值将来自 Cosmos DB 的参数使用 @CosmosDBTrigger 注释。In the Java functions runtime library, use the @CosmosDBTrigger annotation on parameters whose value would come from Cosmos DB. 可以将此注释与本机 Java 类型、POJO 或使用了 Optional<T> 的可为 null 的值一起使用。This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

跳过触发器示例Skip trigger examples

触发器 - C# 特性Trigger - C# 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,
        ILogger 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
type type 必须设置为 cosmosDBTriggerMust be set to cosmosDBTrigger.
direction direction 必须设置为 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, this property sets the maximum amount of items received per Function call. 如果受监视集合中的操作通过存储过程执行,则在从更改源读取项时,会保留事务范围If operations in the monitored collection are performed through stored procedures, transaction scope is preserved when reading items from the Change Feed. 结果就是收到的项的数量可能会高于指定值,因此通过同一事务更改的项会通过某个原子批处理操作返回。As a result of this, it's possible for the amount of items received to be higher than the specified value so that the items changed by the same transaction are returned as part of one atomic batch.
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.

Important

如果多个函数都配置为对同一集合使用 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.

Note

如果集合已分区,则查找操作还需指定分区键值。If the collection is partitioned, lookup operations need to also specify the partition key value.

输入 - 示例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 CosmosDBSamplesV2
{
    public class ToDoItem
    {
        public string Id { get; set; }
        public string PartitionKey { 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 and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem 文档。That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

namespace CosmosDBSamplesV2
{
    public class ToDoItemLookup
    {
        public string ToDoItemId { get; set; }

        public string ToDoItemPartitionKeyValue { get; set; }
    }
}
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class DocByIdFromJSON
    {
        [FunctionName("DocByIdFromJSON")]
        public static void Run(
            [QueueTrigger("todoqueueforlookup")] ToDoItemLookup toDoItemLookup,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{ToDoItemId}",
                PartitionKey = "{ToDoItemPartitionKeyValue}")]ToDoItem toDoItem,
            ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed Id={toDoItemLookup?.ToDoItemId} Key={toDoItemLookup?.ToDoItemPartitionKeyValue}");

            if (toDoItem == null)
            {
                log.LogInformation($"ToDo item not found");
            }
            else
            {
                log.LogInformation($"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 and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem 文档。That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

Note

HTTP 查询字符串参数区分大小写。The HTTP query string parameter is case-sensitive.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class DocByIdFromQueryString
    {
        [FunctionName("DocByIdFromQueryString")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
                HttpRequest req,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{Query.id}",
                PartitionKey = "{Query.partitionKey}")] ToDoItem toDoItem,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

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

跳过输入示例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 and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem 文档。That ID and partition key value are used to retrieve a ToDoItem document from the specified database and collection.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class DocByIdFromRouteData
    {
        [FunctionName("DocByIdFromRouteData")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
                Route = "todoitems/{partitionKey}/{id}")]HttpRequest req,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                Id = "{id}",
                PartitionKey = "{partitionKey}")] ToDoItem toDoItem,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

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

跳过输入示例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.

以下示例演示如何在 SqlQuery 参数中使用绑定表达式。The example shows how to use a binding expression in the SqlQuery parameter. 可以将路由数据传递至所示的 SqlQuery 参数,但目前无法传递查询字符串值You can pass route data to the SqlQuery parameter as shown, but currently you can't pass query string values.

Note

如果需要只按 ID 进行查询,则建议使用查找(如以前的示例所示),因为该查找消耗较少的请求单位If you need to query by just the ID, it is recommended to use a look up, like the previous examples, as it will consume less request units. 点读取操作 (GET) 比按 ID 进行的查询更高效Point read operations (GET) are more efficient than queries by ID.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class DocByIdFromRouteDataUsingSqlQuery
    {
        [FunctionName("DocByIdFromRouteDataUsingSqlQuery")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
                Route = "todoitems2/{id}")]HttpRequest req,
            [CosmosDB("ToDoItems", "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                SqlQuery = "select * from ToDoItems r where r.id = {id}")]
                IEnumerable<ToDoItem> toDoItems,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            foreach (ToDoItem toDoItem in toDoItems)
            {
                log.LogInformation(toDoItem.Description);
            }
            return new OkResult();
        }
    }
}

跳过输入示例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.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class DocsBySqlQuery
    {
        [FunctionName("DocsBySqlQuery")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
                HttpRequest req,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection",
                SqlQuery = "SELECT top 2 * FROM c order by c._ts desc")]
                IEnumerable<ToDoItem> toDoItems,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            foreach (ToDoItem toDoItem in toDoItems)
            {
                log.LogInformation(toDoItem.Description);
            }
            return new OkResult();
        }
    }
}

跳过输入示例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.

Note

还可以使用 IDocumentClient 接口来简化测试。You can also use the IDocumentClient interface to make testing easier.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
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 Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace CosmosDBSamplesV2
{
    public static class DocsByUsingDocumentClient
    {
        [FunctionName("DocsByUsingDocumentClient")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
                Route = null)]HttpRequest req,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")] DocumentClient client,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var searchterm = req.Query["searchterm"];
            if (string.IsNullOrWhiteSpace(searchterm))
            {
                return (ActionResult)new NotFoundResult();
            }

            Uri collectionUri = UriFactory.CreateDocumentCollectionUri("ToDoItems", "Items");

            log.LogInformation($"Searching for: {searchterm}");

            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.LogInformation(result.Description);
                }
            }
            return new OkResult();
        }
    }
}

跳过输入示例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 CosmosDBSamplesV2
{
    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": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "id" : "{queueTrigger}",
    "partitionKey": "{partition key value}",
    "connectionStringSetting": "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": "cosmosDB",
    "direction": "in",
    "databaseName": "MyDb",
    "collectionName": "MyCollection",
    "sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
    "connectionStringSetting": "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 and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem 文档。That ID and partition key value are 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": "cosmosDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "in",
      "Id": "{Query.id}",
      "PartitionKey" : "{Query.partitionKeyValue}"
    }
  ],
  "disabled": false
}

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

using System.Net;
using Microsoft.Extensions.Logging;

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

    if (toDoItem == null)
    {
         log.LogInformation($"ToDo item not found");
    }
    else
    {
        log.LogInformation($"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 and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem 文档。That ID and partition key value are 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/{partitionKeyValue}/{id}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "in",
      "Id": "{id}",
      "PartitionKey": "{partitionKeyValue}"
    }
  ],
  "disabled": false
}

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

using System.Net;
using Microsoft.Extensions.Logging;

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

    if (toDoItem == null)
    {
         log.LogInformation($"ToDo item not found");
    }
    else
    {
        log.LogInformation($"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": "cosmosDB",
      "name": "toDoItems",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "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;
using Microsoft.Extensions.Logging;

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

    foreach (ToDoItem toDoItem in toDoItems)
    {
        log.LogInformation(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": "cosmosDB",
      "name": "client",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "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;
using Microsoft.Extensions.Logging;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, DocumentClient client, ILogger log)
{
    log.LogInformation("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.LogInformation($"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.LogInformation(result.Description);
        }
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

跳过输入示例Skip input examples

输入 - JavaScript 示例Input - JavaScript examples

此部分包含的以下示例可以通过指定各种源提供的 ID 值来读取单个文档:This section contains the following examples that read a single document by specifying an ID value from various sources:

跳过输入示例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": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "id" : "{queueTrigger_payload_property}",
    "partitionKey": "{queueTrigger_payload_property}",
    "connectionStringSetting": "MyAccount_COSMOSDB",
    "direction": "in"
},
{
    "name": "inputDocumentOut",
    "type": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": false,
    "partitionKey": "{queueTrigger_payload_property}",
    "connectionStringSetting": "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 and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem 文档。That ID and partition key value are 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": "cosmosDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "in",
      "Id": "{Query.id}",
      "PartitionKey": "{Query.partitionKeyValue}"
    }
  ],
  "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

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 and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem 文档。That ID and partition key value are 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/{partitionKeyValue}/{id}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "Id": "{id}",
      "PartitionKey": "{partitionKeyValue}"
    }
  ],
  "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": "cosmosDB",
    "direction": "in",
    "databaseName": "MyDb",
    "collectionName": "MyCollection",
    "sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
    "connectionStringSetting": "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": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "id" : "{queueTrigger}",
    "connectionStringSetting": "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.

输入 - Java 示例Input - Java examples

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

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

public class ToDoItem {

  private String id;
  private String description;

  public String getId() {
    return id;
  }

  public String getDescription() {
    return description;
  }

  @Override
  public String toString() {
    return "ToDoItem={id=" + id + ",description=" + description + "}";
  }
}

HTTP 触发器,从查询字符串查找 ID - 字符串参数 (Java)HTTP trigger, look up ID from query string - String parameter (Java)

以下示例展示了检索单个文档的 Java 函数。The following example shows a Java function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID 和分区键值。The function is triggered by a HTTP request that uses a query string to specify the ID and partition key value to look up. 该 ID 和分区键值用于以字符串形式从指定的数据库和集合中检索文档。That ID and partition key value are used to retrieve a document from the specified database and collection, in String form.

public class DocByIdFromQueryString {

    @FunctionName("DocByIdFromQueryString")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              id = "{Query.id}",
              partitionKey = "{Query.partitionKeyValue}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            Optional<String> item,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("String from the database is " + (item.isPresent() ? item.get() : null));

        // Convert and display
        if (!item.isPresent()) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        }
        else {
            // return JSON from Cosmos. Alternatively, we can parse the JSON string
            // and return an enriched JSON object.
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(item.get())
                          .build();
        }
    }
}

Java 函数运行时库中,对其值将来自 Cosmos DB 的函数参数使用 @CosmosDBInput 注释。In the Java functions runtime library, use the @CosmosDBInput annotation on function parameters whose value would come from Cosmos DB. 可以将此注释与本机 Java 类型、POJO 或使用了 Optional<T> 的可为 null 的值一起使用。This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

HTTP 触发器,从查询字符串查找 ID - POJO 参数 (Java)HTTP trigger, look up ID from query string - POJO parameter (Java)

以下示例展示了检索单个文档的 Java 函数。The following example shows a Java function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID 和分区键值。The function is triggered by a HTTP request that uses a query string to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索文档。That ID and partition key value used to retrieve a document from the specified database and collection. 然后将该文档转换为先前创建的 ToDoItem POJO 实例,并作为参数传递给该函数。The document is then converted to an instance of the ToDoItem POJO previously created, and passed as an argument to the function.

public class DocByIdFromQueryStringPojo {

    @FunctionName("DocByIdFromQueryStringPojo")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              id = "{Query.id}",
              partitionKey = "{Query.partitionKeyValue}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            ToDoItem item,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("Item from the database is " + item);

        // Convert and display
        if (item == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        }
        else {
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(item)
                          .build();
        }
    }
}

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

以下示例展示了检索单个文档的 Java 函数。The following example shows a Java function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由参数用于指定要查找的 ID 和分区键值。The function is triggered by a HTTP request that uses a route parameter to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索文档,将它作为 Optional<String> 返回。That ID and partition key value are used to retrieve a document from the specified database and collection, returning it as an Optional<String>.

public class DocByIdFromRoute {

    @FunctionName("DocByIdFromRoute")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS,
              route = "todoitems/{partitionKeyValue}/{id}")
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              id = "{id}",
              partitionKey = "{partitionKeyValue}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            Optional<String> item,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("String from the database is " + (item.isPresent() ? item.get() : null));

        // Convert and display
        if (!item.isPresent()) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        }
        else {
            // return JSON from Cosmos. Alternatively, we can parse the JSON string
            // and return an enriched JSON object.
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(item.get())
                          .build();
        }
    }
}

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

以下示例展示了检索单个文档的 Java 函数。The following example shows a Java function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用路由参数指定要查找的 ID。The function is triggered by a HTTP request that uses a route parameter to specify the ID to look up. 该 ID 用于从指定的数据库和集合中检索文档,将结果集转换为 ToDoItem[],因为可能会返回许多文档,具体取决于查询条件。That ID is used to retrieve a document from the specified database and collection, converting the result set to a ToDoItem[], since many documents may be returned, depending on the query criteria.

Note

如果需要只按 ID 进行查询,则建议使用查找(如以前的示例所示),因为该查找消耗较少的请求单位If you need to query by just the ID, it is recommended to use a look up, like the previous examples, as it will consume less request units. 点读取操作 (GET) 比按 ID 进行的查询更高效Point read operations (GET) are more efficient than queries by ID.

public class DocByIdFromRouteSqlQuery {

    @FunctionName("DocByIdFromRouteSqlQuery")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS,
              route = "todoitems2/{id}")
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              sqlQuery = "select * from Items r where r.id = {id}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            ToDoItem[] item,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("Items from the database are " + item);

        // Convert and display
        if (item == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("Document not found.")
                          .build();
        }
        else {
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(item)
                          .build();
        }
    }
}

HTTP 触发器,使用 SqlQuery 从路由数据获取多个文档 (Java)HTTP trigger, get multiple docs from route data, using SqlQuery (Java)

以下示例展示了多个文档的 Java 函数。The following example shows a Java function that multiple documents. 该函数由 HTTP 请求触发,该请求使用路由参数 desc 指定要在 description 字段中搜索的字符串。The function is triggered by a HTTP request that uses a route parameter desc to specify the string to search for in the description field. 搜索项用于从指定的数据库和集合中检索文档集合,将结果集转换为 ToDoItem[] 并将其作为参数传递给函数。The search term is used to retrieve a collection of documents from the specified database and collection, converting the result set to a ToDoItem[] and passing it as an argument to the function.

public class DocsFromRouteSqlQuery {

    @FunctionName("DocsFromRouteSqlQuery")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET},
              authLevel = AuthorizationLevel.ANONYMOUS,
              route = "todoitems3/{desc}")
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              sqlQuery = "select * from Items r where contains(r.description, {desc})",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            ToDoItem[] items,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());
        context.getLogger().info("Number of items from the database is " + (items == null ? 0 : items.length));

        // Convert and display
        if (items == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                          .body("No documents found.")
                          .build();
        }
        else {
            return request.createResponseBuilder(HttpStatus.OK)
                          .header("Content-Type", "application/json")
                          .body(items)
                          .build();
        }
    }
}

输入 - 特性Input - attributes

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 the following configuration section.

输入 - 配置Input - 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
type type 必须设置为 cosmosDBMust be set to cosmosDB.
direction direction 必须设置为 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.
connectionStringSettingconnectionStringSetting 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. 它是在分区的集合中进行查询所需的。It is required for lookups in partitioned collections.

在本地进行开发时,应用设置将取 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.

输出Output

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 CosmosDBSamplesV2
{
    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 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}");
        }
    }
}

跳过输出示例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;
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);
            }
        }
    }
}

跳过输出示例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": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connectionStringSetting": "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;
    using Microsoft.Extensions.Logging;

    public static void Run(string myQueueItem, out object employeeDocument, ILogger log)
    {
      log.LogInformation($"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 CosmosDBSamplesV2
{
    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",
      "connectionStringSetting": "AzureWebJobsStorage"
    },
    {
      "type": "cosmosDB",
      "name": "toDoItemsOut",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "out"
    }
  ],
  "disabled": false
}

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

using System;
using Microsoft.Extensions.Logging;

public static async Task Run(ToDoItem[] toDoItemsIn, 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);
    }
}

跳过输出示例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": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connectionStringSetting": "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": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connectionStringSetting": "MyAccount_COSMOSDB",
    "direction": "out"
}

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

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

    open FSharp.Interop.Dynamic
    open Newtonsoft.Json
    open Microsoft.Extensions.Logging

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

    let Run(myQueueItem: string, employeeDocument: byref<obj>, log: ILogger) =
      log.LogInformation(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.

输出 - Java 示例Output - Java examples

队列触发器,通过返回值将消息保存到数据库 (Java)Queue trigger, save message to database via return value (Java)

以下示例展示了一个 Java 函数,它向数据库中添加一个文档,该文档包含来自队列存储中消息的数据。The following example shows a Java function that adds a document to a database with data from a message in Queue storage.

@FunctionName("getItem")
@CosmosDBOutput(name = "database",
  databaseName = "ToDoList",
  collectionName = "Items",
  connectionStringSetting = "AzureCosmosDBConnection")
public String cosmosDbQueryById(
    @QueueTrigger(name = "msg",
      queueName = "myqueue-items",
      connection = "AzureWebJobsStorage")
    String message,
    final ExecutionContext context)  {
     return "{ id: \"" + System.currentTimeMillis() + "\", Description: " + message + " }";
   }

HTTP 触发器,通过返回值将文件保存到数据库 (Java)HTTP trigger, save one document to database via return value (Java)

以下示例显示了 Java 函数,其签名使用 @CosmosDBOutput 注释,并且返回值类型为 StringThe following example shows a Java function whose signature is annotated with @CosmosDBOutput and has return value of type String. 该函数返回的 JSON 文档将自动写入相应的 CosmosDB 集合。The JSON document returned by the function will be automatically written to the corresponding CosmosDB collection.

    @FunctionName("WriteOneDoc")
    @CosmosDBOutput(name = "database",
      databaseName = "ToDoList",
      collectionName = "Items",
      connectionStringSetting = "Cosmos_DB_Connection_String")
    public String run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());

        // Parse query parameter
        String query = request.getQueryParameters().get("desc");
        String name = request.getBody().orElse(query);

        // Generate random ID
        final int id = Math.abs(new Random().nextInt());

        // Generate document
        final String jsonDocument = "{\"id\":\"" + id + "\", " +
                                    "\"description\": \"" + name + "\"}";

        context.getLogger().info("Document to be saved: " + jsonDocument);

        return jsonDocument;
    }

HTTP 触发器,通过 OutputBinding 将一个文档保存到数据库 (Java)HTTP trigger, save one document to database via OutputBinding (Java)

以下示例显示了 Java 函数,该函数通过 OutputBinding<T> 输出参数将文档写入 CosmosDB。The following example shows a Java function that writes a document to CosmosDB via an OutputBinding<T> output parameter. 请注意,在此设置中,outputItem 参数需要使用 @CosmosDBOutput 进行注释,而不是函数签名。Note that, in this setup, it is the outputItem parameter that needs to be annotated with @CosmosDBOutput, not the function signature. 使用 OutputBinding<T>,让函数可以利用绑定将文档写入 CosmosDB,同时还可向函数调用者返回不同的值,例如 JSON 或 XML 文档。Using OutputBinding<T> lets your function take advantage of the binding to write the document to CosmosDB while also allowing returning a different value to the function caller, such as a JSON or XML document.

    @FunctionName("WriteOneDocOutputBinding")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBOutput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            OutputBinding<String> outputItem,
            final ExecutionContext context) {

        // Parse query parameter
        String query = request.getQueryParameters().get("desc");
        String name = request.getBody().orElse(query);

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());

        // Generate random ID
        final int id = Math.abs(new Random().nextInt());

        // Generate document
        final String jsonDocument = "{\"id\":\"" + id + "\", " +
                                    "\"description\": \"" + name + "\"}";

        context.getLogger().info("Document to be saved: " + jsonDocument);

        // Set outputItem's value to the JSON document to be saved
        outputItem.setValue(jsonDocument);

        // return a different document to the browser or calling client.
        return request.createResponseBuilder(HttpStatus.OK)
                      .body("Document created successfully.")
                      .build();
    }

HTTP 触发器,通过 OutputBinding 将多个文档保存到数据库 (Java)HTTP trigger, save multiple documents to database via OutputBinding (Java)

以下示例显示了 Java 函数,该函数通过 OutputBinding<T> 输出参数将多个文档写入 CosmosDB。The following example shows a Java function that writes multiple documents to CosmosDB via an OutputBinding<T> output parameter. 请注意,在此设置中,outputItem 参数需要使用 @CosmosDBOutput 进行注释,而不是函数签名。Note that, in this setup, it is the outputItem parameter that needs to be annotated with @CosmosDBOutput, not the function signature. 输出参数 outputItem 有一个 ToDoItem 对象列表作为其模板参数类型。The output parameter, outputItem has a list of ToDoItem objects as its template parameter type. 使用 OutputBinding<T>,让函数可以利用绑定将文档写入 CosmosDB,同时还可向函数调用者返回不同的值,例如 JSON 或 XML 文档。Using OutputBinding<T> lets your function take advantage of the binding to write the documents to CosmosDB while also allowing returning a different value to the function caller, such as a JSON or XML document.

    @FunctionName("WriteMultipleDocsOutputBinding")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBOutput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            OutputBinding<List<ToDoItem>> outputItem,
            final ExecutionContext context) {

        // Parse query parameter
        String query = request.getQueryParameters().get("desc");
        String name = request.getBody().orElse(query);

        // Item list
        context.getLogger().info("Parameters are: " + request.getQueryParameters());

        // Generate documents
        List<ToDoItem> items = new ArrayList<>();

        for (int i = 0; i < 5; i ++) {
          // Generate random ID
          final int id = Math.abs(new Random().nextInt());

          // Create ToDoItem
          ToDoItem item = new ToDoItem(String.valueOf(id), name);

          items.add(item);
        }

        // Set outputItem's value to the list of POJOs to be saved
        outputItem.setValue(items);
        context.getLogger().info("Document to be saved: " + items);

        // return a different document to the browser or calling client.
        return request.createResponseBuilder(HttpStatus.OK)
                      .body("Documents created successfully.")
                      .build();
    }

Java 函数运行时库中,对其值将写入到 Cosmos DB 的参数使用 @CosmosDBOutput 注释。In the Java functions runtime library, use the @CosmosDBOutput annotation on parameters that will be written to Cosmos DB. 注释参数类型应当为 OutputBinding<T>,其中 T 是本机 Java 类型或 POJO。The annotation parameter type should be OutputBinding<T>, where T is either a native Java type or a POJO.

输出 - 特性Output - attributes

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)
    {
        ...
    }

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

输出 - 配置Output - 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
type type 必须设置为 cosmosDBMust be set to cosmosDB.
direction direction 必须设置为 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.
connectionStringSettingconnectionStringSetting 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.

Note

如果指定现有文档的 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