適用於 Azure Functions 1.x 的 Azure Cosmos DB 繫結

本文說明如何在 Azure Functions 中使用 Azure Cosmos DB 繫結。 Azure Functions 支援適用於 Azure Cosmos DB 的觸發程序、輸入和輸出繫結。

注意

本文適用於 Azure Functions 1.x。 如需如何在 Functions 2.x 及更新版本中使用這些繫結的資訊,請參閱適用於 Azure Functions 2.x 的 Azure Cosmos DB 繫結

這個繫結最初命名為 DocumentDB。 在 Azure Functions 1.x 版中,只有觸發程序已重新命名為 Azure Cosmos DB;輸入繫結、輸出繫結和 NuGet 套件則保留 DocumentDB 名稱。

注意

目前僅支援將 Azure Cosmos DB 繫結用於 SQL API。 對於其他所有的 Azure Cosmos DB API,您應使用 API 的靜態用戶端,以從函式存取資料庫,包括 Azure Cosmos DB for MongoDBAzure Cosmos DB for Apache CassandraAzure Cosmos DB for Apache GremlinAzure Cosmos DB for Table

套件 - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.DocumentDB NuGet 套件 1.x 版中,提供適用於 Functions 1.x 版的 Azure Cosmos DB 繫結。 繫結的原始程式碼位於 azure-webjobs-sdk-extensions GitHub 存放庫中。

下表說明如何在每個開發環境中為此繫結新增支援。

開發環境 若要新增支援
Functions 1.x
本機開發 - C# 類別庫 安裝套件
本機開發 - C# 指令碼、JavaScript、F# 自動
入口網站開發 自動

觸發程序

Azure Cosmos DB 觸發程序會使用 Azure Cosmos DB 變更摘要,跨分割區接聽插入項目及變更。 變更摘要會發行插入和更新,而非刪除。

觸發程序 - 範例

下列範例顯示當指定的資料庫和集合中有插入或更新時,所叫用的 內建 C# 函式。

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

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

觸發程序 - 屬性

針對 同進程 C# 類別庫,請使用 CosmosDBTrigger 屬性。

屬性的建構函式可接受資料庫名稱和集合名稱。 如需這些設定及其他您可以設定之屬性的相關資訊,請參閱觸發程序 - 組態。 以下是方法簽章中的 CosmosDBTrigger 屬性範例:

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

如需完整範例,請參閱觸發程序 - C# 範例

觸發程式 - 設定

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 CosmosDBTrigger 屬性。

function.json 屬性 屬性內容 描述
type n/a 必須設為 cosmosDBTrigger
direction n/a 必須設為 in。 當您在 Azure 入口網站中建立觸發程序時,會自動設定此參數。
name n/a 函式程式碼中使用的變數名稱,代表有變更的文件清單。
connectionStringSetting ConnectionStringSetting 應用程式設定的名稱,包含用來連接到要監視之 Azure Cosmos DB 帳戶的連接字串。
databaseName DatabaseName 含有要監視之集合的 Azure Cosmos DB 資料庫名稱。
collectionName CollectionName 要監視的集合名稱。
leaseConnectionStringSetting LeaseConnectionStringSetting (選擇性) 應用程式設定的名稱,包含連至保存租用集合之服務的連接字串。 如果未設定,會使用 connectionStringSetting 值。 在入口網站中建立繫結時,會自動設定此參數。 租用集合的連接字串必須具有寫入權限。
leaseDatabaseName LeaseDatabaseName (選擇性) 保存用來儲存租用之集合的資料庫名稱。 如果未設定,會使用 databaseName 設定的值。 在入口網站中建立繫結時,會自動設定此參數。
leaseCollectionName LeaseCollectionName (選擇性) 用來儲存租用的集合名稱。 如果未設定,會使用 leases 值。
createLeaseCollectionIfNotExists CreateLeaseCollectionIfNotExists (選擇性) 設為 true 時,如果租用集合尚未存在,即會自動加以建立。 預設值是 false
leasesCollectionThroughput LeasesCollectionThroughput (選擇性) 定義要在建立租用集合時指派的要求單位數。 只有在將 createLeaseCollectionIfNotExists 設為 true 時才會使用此設定。 使用入口網站建立繫結時,會自動設定此參數。
leaseCollectionPrefix LeaseCollectionPrefix (選擇性) 如果設定,將會為此函式對建立於租用集合中的租用加上前置詞,而有效地讓兩個不同的 Azure Functions 藉由使用不同的前置詞來共用相同的租用。
feedPollDelay FeedPollDelay (選擇性) 如果設定,將會以毫秒為單位定義在目前所有的變更都清空後,每次輪詢分割區以了解摘要上是否有新變更時所要延遲的時間。 預設值為 5000 (5 秒)。
leaseAcquireInterval LeaseAcquireInterval (選擇性) 如果設定,將會以毫秒為單位定義啟動工作以計算分割區是否平均分散到已知主機執行個體的間隔。 預設值為 13000 (13 秒)。
leaseExpirationInterval LeaseExpirationInterval (選擇性) 如果設定,將會以毫秒為單位定義租用代表分割區的間隔。 未在此間隔內更新的租用將會過期,且分割區的擁有權會移轉給另一個執行個體。 預設值為 60000 (60 秒)。
leaseRenewInterval LeaseRenewInterval (選擇性) 如果設定,將會以毫秒為單位定義目前由執行個體保有之分割區的所有租用所適用的更新間隔。 預設值為 17000 (17 秒)。
checkpointFrequency CheckpointFrequency (選擇性) 如果設定,將會以毫秒為單位定義租用檢查點的間隔。 預設永遠是各函式呼叫後。
maxItemsPerInvocation MaxItemsPerInvocation (選擇性) 如果設定,將會自訂每個函式呼叫所接收的項目數量上限。
startFromBeginning StartFromBeginning (選擇性) 如果設定此項,它會告訴觸發程序從集合記錄 (而非當前的時間) 起始點讀取變更。 因為在後續執行中,檢查點已儲存,所以這只會在觸發程序第一次啟動時運作。 若已經建立租用,將此項設為 true 不會有任何作用。

當您在本機開發時,請在 Values 集合的 local.settings.json 檔案中新增應用程式設定。

觸發程序 - 使用方式

觸發程序需要第二個集合,用來在分割區上儲存「租用」。 要監視的集合和包含租用的集合必須可供觸發程序用來運作。

重要事項

如果針對同一個集合設定多個函式使用 Azure Cosmos DB 觸發程序,則每個函式都應該使用專用的租用集合,或為每個函式指定不同的 LeaseCollectionPrefix。 否則,將只會觸發其中一個函式。 如需前置詞的相關資訊,請參閱組態區段

觸發程序不會指示是否更新或插入文件,只是提供文件本身。 如果您需要以不同方式處理更新和插入,您可以透過實作插入或更新的時間戳記欄位執行。

輸入

Azure Cosmos DB 輸入繫結會使用 SQL API 來擷取一或多個 Azure Cosmos DB 文件,並傳遞給函式的輸入參數。 您能以叫用函式的觸發程序作為基礎,來判斷文件識別碼或查詢參數。

輸入 - 範例

本區段包含下列範例:

範例會參考簡單的 ToDoItem 類型:

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

佇列觸發程序,從 JSON 中查閱識別碼

下列範例示範會顯示擷取單一文件的 C# 函式。 函式會由包含 JSON 物件的佇列訊息觸發。 佇列觸發程序會將 JSON 剖析至名為 ToDoItemLookup 的 JSON,其中包含要查閱的識別碼。 該識別碼會用來從指定的資料庫和集合中,擷取 ToDoItem 文件。

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

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

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

HTTP 觸發程序,從查詢字串中查閱識別碼

下列範例示範會顯示擷取單一文件的 C# 函式。 函式會由 HTTP 要求觸發,該 HTTP 要求會使用查詢字串指定要查閱的識別碼。 該識別碼會用來從指定的資料庫和集合中,擷取 ToDoItem 文件。

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

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

HTTP 觸發程序,從路由資料中查閱識別碼

下列範例示範會顯示擷取單一文件的 C# 函式。 函式會由 HTTP 要求觸發,該 HTTP 要求會使用路由資料指定要查閱的識別碼。 該識別碼會用來從指定的資料庫和集合中,擷取 ToDoItem 文件。

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

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

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

跳過輸入範例

HTTP 觸發程序,使用 SqlQuery 從路由資料中查閱識別碼

下列範例示範會顯示擷取單一文件的 C# 函式。 函式會由 HTTP 要求觸發,該 HTTP 要求會使用路由資料指定要查閱的識別碼。 該識別碼會用來從指定的資料庫和集合中,擷取 ToDoItem 文件。

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

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

跳過輸入範例

HTTP 觸發程序,使用 SqlQuery 取得多個文件

下列範例示範會顯示擷取文件清單的 C# 函式。 函式是由 HTTP 要求所觸發。 查詢會在 SqlQuery 屬性內容中指定。

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

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

跳過輸入範例

HTTP 觸發程序,使用 DocumentClient 取得多個文件 (C#)

下列範例示範會顯示擷取文件清單的 C# 函式。 函式是由 HTTP 要求所觸發。 程式碼會使用由 Azure Cosmos DB 繫結提供的 DocumentClient 執行個體來讀取文件清單。 DocumentClient 執行個體也會用來進行寫入作業。

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

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

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

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

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

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

輸入 - 屬性

進程 C# 類別庫中,使用 DocumentDB 屬性。

屬性的建構函式可接受資料庫名稱和集合名稱。 如需這些設定及其他您可以設定之屬性的相關資訊,請參閱下列組態區段

輸入 - 組態

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 DocumentDB 屬性。

function.json 屬性 屬性內容 描述
type n/a 必須設為 documentdb
direction n/a 必須設為 in
name n/a 代表函式中之文件的繫結參數名稱。
databaseName DatabaseName 包含文件的資料庫。
collectionName CollectionName 包含文件的集合名稱。
id Id 要擷取之文件的識別碼。 此屬性支援繫結運算式。 請勿同時設定 idsqlQuery 屬性。 如果您未設定其中一個,就會擷取整個集合。
sqlQuery SqlQuery 用來擷取多份文件的 Azure Cosmos DB SQL 查詢。 屬性會支援執行階段繫結,如此範例所示:SELECT * FROM c where c.departmentId = {departmentId}。 請勿同時設定 idsqlQuery 屬性。 如果您未設定其中一個,就會擷取整個集合。
connection ConnectionStringSetting 包含 Azure Cosmos DB 連接字串的應用程式設定名稱。
partitionKey PartitionKey 指定分割區索引鍵值進行查閱。 可能包含繫結參數。

當您在本機開發時,請在 Values 集合的 local.settings.json 檔案中新增應用程式設定。

輸入 - 使用方式

當函式順利結束時,系統會自動保留透過具名輸入參數對輸入文件所做的任何變更。

輸出

Azure Cosmos DB 輸出繫結可讓您使用 SQL API,將新的文件寫入 Azure Cosmos DB 資料庫。

輸出 - 範例

本區段包含下列範例:

  • 佇列觸發程序,寫入一份文件
  • 佇列觸發程序,使用 IAsyncCollector 寫入文件

範例會參考簡單的 ToDoItem 類型:

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

佇列觸發程序,寫入一份文件

下列範例顯示 C# 函式,它使用佇列儲存體之訊息中提供的資料,將文件新增至資料庫。

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

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

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

佇列觸發程序,使用 IAsyncCollector 寫入文件

下列範例顯示 C# 函式,它會使用佇列訊息 JSON 中提供的資料,將文件集合新增至資料庫中。

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

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

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

輸出 - 屬性

進程 C# 類別庫中,使用 DocumentDB 屬性。

屬性的建構函式可接受資料庫名稱和集合名稱。 如需這些設定及其他您可以設定之屬性的相關資訊,請參閱輸出 - 組態。 以下是方法簽章中的 DocumentDB 屬性範例:

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

如需完整的範例,請參閱輸出

輸出 - 設定

下表說明您在 function.json 檔案中設定的繫結設定屬性內容和 DocumentDB 屬性。

function.json 屬性 屬性內容 描述
type n/a 必須設為 documentdb
direction n/a 必須設為 out
name n/a 代表函式中之文件的繫結參數名稱。
databaseName DatabaseName 包含其中將建立文件之集合的資料庫。
collectionName CollectionName 包含其中將建立文件之集合的名稱。
createIfNotExists CreateIfNotExists 一個布林值,用來指出當集合不存在時,是否要建立集合。 預設是 false,因為會使用保留的輸送量來建立新集合,可能會涉及成本。 如需詳細資訊,請參閱價格頁面
partitionKey PartitionKey CreateIfNotExists 為 true 時,定義所建立集合的分割區索引鍵路徑。
collectionThroughput CollectionThroughput CreateIfNotExists 為 true 時,定義所建立集合的輸送量
connection ConnectionStringSetting 包含 Azure Cosmos DB 連接字串的應用程式設定名稱。

當您在本機開發時,請在 Values 集合的 local.settings.json 檔案中新增應用程式設定。

輸出 - 使用方式

根據預設,當您在函式中寫入輸出參數時,會在資料庫中建立文件。 這份文件已自動產生 GUID 作為文件識別碼。 您可以藉由在傳遞至輸出參數的 JSON 物件中指定 id 屬性,來指定輸出文件的文件識別碼。

注意

當您指定現有文件的識別碼時,新的輸出文件會覆寫現有文件。

例外狀況和傳回碼

繫結 參考
Azure Cosmos DB Azure Cosmos DB 的 HTTP 狀態碼

後續步驟