适用于 Azure Functions 2.x 及更高版本的 Azure Cosmos DB 输入绑定Azure Cosmos DB input binding for Azure Functions 2.x and higher

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.

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

备注

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

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

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

namespace CosmosDBSamplesV2
{
    public class ToDoItem
    {
        [JsonProperty("id")]
        public string Id { get; set; }
        
        [JsonProperty("partitionKey")]
        public string PartitionKey { get; set; }
        
        public string Description { get; set; }
    }
}

队列触发器,从 JSON 查找 IDQueue trigger, look up ID from JSON

以下示例演示检索单个文档的 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 of type 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}");
            }
        }
    }
}

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

以下示例演示检索单个文档的 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.

备注

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();
        }
    }
}

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

以下示例演示检索单个文档的 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();
        }
    }
}

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

以下示例演示检索单个文档的 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.

备注

如果需要只按 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();
        }
    }
}

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

以下示例演示检索文档列表的 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();
        }
    }
}

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

以下示例演示检索文档列表的 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.

备注

还可以使用 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();
        }
    }
}

特性和注释Attributes and annotations

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

该特性的构造函数采用数据库名称和集合名称。The attribute's constructor takes the database name and collection name. 有关这些设置以及可以配置的其他属性的信息,请参阅下面的“配置”部分For information about those settings and other properties that you can configure, see the following configuration section.

配置Configuration

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

function.json 属性function.json property Attribute 属性Attribute property 说明Description
typetype 不适用n/a 必须设置为 cosmosDBMust be set to cosmosDB.
directiondirection 不适用n/a 必须设置为 inMust be set to in.
namename 不适用n/a 表示函数中的文档的绑定参数的名称。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.
preferredLocationspreferredLocations PreferredLocationsPreferredLocations (可选)为 Azure Cosmos DB 服务中的异地复制数据库帐户定义首选位置(区域)。(Optional) Defines preferred locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. 值应以逗号分隔。Values should be comma-separated.

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

使用情况Usage

函数成功退出时,通过命名输入参数对输入文档所做的任何更改都会自动保存。When the function exits successfully, any changes made to the input document via named input parameters are automatically persisted.

后续步骤Next steps