共用方式為


適用於 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 的靜態用戶端從函式存取資料庫,包括適用於 MongoDB 的 Azure Cosmos DB、適用於 Apache Cassandra 的 Azure Cosmos DB、適用於 Apache Gremlin 的 Azure Cosmos DB,以及適用於數據表的 Azure Cosmos DB。

套件 - Functions 1.x

適用於 Functions 1.x 版的 Azure Cosmos DB 系結是在 Microsoft.Azure.WebJobs.Extensions.DocumentDB NuGet 套件 1.x 版中提供。 系結的原始碼位於 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 (選擇性)定義建立租用集合時要指派的要求單位數量。 只有當 設定為 truecreateLeaseCollectionIfNotExists,才會使用此設定。 使用入口網站建立繫結時,會自動設定此參數。
leaseCollectionPrefix LeaseCollectionPrefix (選擇性)設定時,它會將前置詞新增至此函式之 Lease 集合中建立的租用,有效地允許兩個不同的 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當已建立租用時,將此設定為 沒有作用。

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

觸發程式 - 使用方式

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

重要

如果多個函式設定為使用相同的集合使用 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的物件,其中包含要查閱的標識碼。 該識別碼會用來從指定的資料庫和集合中,擷取 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 指定分割區索引鍵值進行查閱。 可能包含繫結參數。

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

輸入 - 使用量

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

輸出

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 寫入文件

下列範例示範 使用佇列訊息 JSON 中提供的數據,將檔集合新增至資料庫的 C# 函 式。

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 當 為 true 時 CreateIfNotExists ,定義所建立集合的分割區索引鍵路徑。
collectionThroughput CollectionThroughput 當 為 true 時 CreateIfNotExists ,定義 所建立集合的輸送量
connection ConnectionStringSetting 包含 Azure Cosmos DB 連接字串 的應用程式設定名稱。

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

輸出 - 使用量

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

注意

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

例外狀況和傳回碼

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

下一步