適用於 Azure Functions 2.x 和更新版本的 Azure Cosmos DB 輸出系結

Azure Cosmos DB 輸出系結可讓您使用 SQL API 將新檔寫入 Azure Cosmos DB 資料庫。

如需安裝和組態詳細數據的詳細資訊,請參閱概

重要

本文使用索引標籤來支援多個版本的Node.js程序設計模型。 v4 模型已正式推出,旨在為 JavaScript 和 TypeScript 開發人員提供更靈活的直覺式體驗。 如需 v4 模型運作方式的詳細資訊,請參閱 Azure Functions Node.js開發人員指南。 若要深入瞭解 v3 與 v4 之間的差異,請參閱 移轉指南

Azure Functions 支援兩種適用於 Python 的程式設計模型。 您定義系結的方式取決於您所選擇的程式設計模型。

Python v2 程式設計模型可讓您直接在 Python 函式程式代碼中使用裝飾項目來定義系結。 如需詳細資訊,請參閱 Python 開發人員指南

本文支援這兩種程序設計模型。

您可以使用下列其中一種 C# 模式來建立 C# 函式:

  • 隔離的背景工作模型:在與運行時間隔離的背景工作進程中執行的已編譯 C# 函式。 需要隔離的背景工作進程,才能支援在 LTS 和非 LTS 版本 .NET 和 .NET Framework 上執行的 C# 函式。 隔離背景工作進程函式的延伸模組會使用 Microsoft.Azure.Functions.Worker.Extensions.* 命名空間。
  • 同進程模型:在與 Functions 運行時間相同的進程中執行的已編譯 C# 函式。 在此模型的變化中,函式可以使用 C# 腳本來執行,主要支援 C# 入口網站編輯。 進程內函式的延伸模組會使用 Microsoft.Azure.WebJobs.Extensions.* 命名空間。

重要

支援將於 2026 年 11 月 10 日結束進程模型。 強烈建議您將 應用程式移轉至隔離的背景工作模型 ,以取得完整支援。

範例

除非另有說明,否則本文中的範例會以 Azure Cosmos DB 擴充功能 3.x 版為目標。 若要搭配 4.x 版的延伸模組使用,您必須將 屬性和屬性名稱中的字串collection取代為 containerconnectionconnection_string_setting

下列程式代碼會 MyDocument 定義類型:

public class MyDocument
{
    public string Id { get; set; }

    public string Text { get; set; }

    public int Number { get; set; }

    public bool Boolean { get; set; }
}

在下列範例中,傳回類型是 IReadOnlyList<T>,這是觸發程式系結參數中已修改的檔清單:

using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

namespace SampleApp
{
    public class CosmosDBFunction
    {
        private readonly ILogger<CosmosDBFunction> _logger;

        public CosmosDBFunction(ILogger<CosmosDBFunction> logger)
        {
            _logger = logger;
        }

        //<docsnippet_exponential_backoff_retry_example>
        [Function(nameof(CosmosDBFunction))]
        [ExponentialBackoffRetry(5, "00:00:04", "00:15:00")]
        [CosmosDBOutput("%CosmosDb%", "%CosmosContainerOut%", Connection = "CosmosDBConnection", CreateIfNotExists = true)]
        public object Run(
            [CosmosDBTrigger(
                "%CosmosDb%",
                "%CosmosContainerIn%",
                Connection = "CosmosDBConnection",
                LeaseContainerName = "leases",
                CreateLeaseContainerIfNotExists = true)] IReadOnlyList<MyDocument> input,
            FunctionContext context)
        {
            if (input != null && input.Any())
            {
                foreach (var doc in input)
                {
                    _logger.LogInformation("Doc Id: {id}", doc.Id);
                }

                // Cosmos Output
                return input.Select(p => new { id = p.Id });
            }

            return null;
        }
        //</docsnippet_exponential_backoff_retry_example>
    }

佇列觸發程式,透過傳回值將訊息儲存至資料庫

下列範例顯示 Java 函式,此函式會將檔新增至資料庫中,其中包含佇列記憶體中訊息的數據。

@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 函式,其簽章會加上 @CosmosDBOutput 批注,且 具有 類型的 String傳回值。 函式傳回的 JSON 檔會自動寫入對應的 Azure Cosmos DB 集合。

    @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 函式,可透過 OutputBinding<T> 輸出參數將檔寫入 Azure Cosmos DB。 在此範例中 outputItem ,參數必須加上 @CosmosDBOutput批注,而不是函式簽章。 使用 OutputBinding<T> 可讓您的函式利用系結將檔寫入 Azure Cosmos DB,同時允許將不同的值傳回給函式呼叫端,例如 JSON 或 XML 檔。

    @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 函式,可透過 OutputBinding<T> 輸出參數將多個檔寫入 Azure Cosmos DB。 在此範例中 outputItem ,參數會加上 @CosmosDBOutput批注,而不是函式簽章。 輸出參數具有 outputItem 物件清單 ToDoItem 做為其範本參數類型。 使用 OutputBinding<T> 可讓您的函式利用系結將檔寫入 Azure Cosmos DB,同時允許將不同的值傳回給函式呼叫端,例如 JSON 或 XML 檔。

    @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 函式運行時間連結庫中,對 @CosmosDBOutput 將寫入 Azure Cosmos DB 的參數使用註釋。 註釋參數類型應該是 OutputBinding<T>,其中 T 是原生 Java 類型或 POJO。

下列範例顯示接收 JSON 格式之佇列的記憶體佇列觸發 TypeScript 函 式:

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

此函式會針對每一筆記錄建立下列格式的 Azure Cosmos DB 文件:

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

以下是 TypeScript 程式代碼:

import { app, InvocationContext, output } from '@azure/functions';

interface MyQueueItem {
    name: string;
    employeeId: string;
    address: string;
}

interface MyCosmosItem {
    id: string;
    name: string;
    employeeId: string;
    address: string;
}

export async function storageQueueTrigger1(queueItem: MyQueueItem, context: InvocationContext): Promise<MyCosmosItem> {
    return {
        id: `${queueItem.name}-${queueItem.employeeId}`,
        name: queueItem.name,
        employeeId: queueItem.employeeId,
        address: queueItem.address,
    };
}

app.storageQueue('storageQueueTrigger1', {
    queueName: 'inputqueue',
    connection: 'MyStorageConnectionAppSetting',
    return: output.cosmosDB({
        databaseName: 'MyDatabase',
        collectionName: 'MyCollection',
        createIfNotExists: true,
        connectionStringSetting: 'MyAccount_COSMOSDB',
    }),
    handler: storageQueueTrigger1,
});

若要輸出多個檔,請傳回數位,而不是單一物件。 例如:

return [
    {
        id: 'John Henry-123456',
        name: 'John Henry',
        employeeId: '123456',
        address: 'A town nearby',
    },
    {
        id: 'John Doe-123457',
        name: 'John Doe',
        employeeId: '123457',
        address: 'A town far away',
    },
];

下列範例會針對接收下列格式 JSON 的佇列,顯示已觸發 記憶體佇列的 JavaScript 函 式:

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

此函式會針對每一筆記錄建立下列格式的 Azure Cosmos DB 文件:

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

以下是 JavaScript 程式代碼:

const { app, output } = require('@azure/functions');

const cosmosOutput = output.cosmosDB({
    databaseName: 'MyDatabase',
    collectionName: 'MyCollection',
    createIfNotExists: true,
    connectionStringSetting: 'MyAccount_COSMOSDB',
});

app.storageQueue('storageQueueTrigger1', {
    queueName: 'inputqueue',
    connection: 'MyStorageConnectionAppSetting',
    return: cosmosOutput,
    handler: (queueItem, context) => {
        return {
            id: `${queueItem.name}-${queueItem.employeeId}`,
            name: queueItem.name,
            employeeId: queueItem.employeeId,
            address: queueItem.address,
        };
    },
});

若要輸出多個檔,請傳回數位,而不是單一物件。 例如:

return [
    {
        id: 'John Henry-123456',
        name: 'John Henry',
        employeeId: '123456',
        address: 'A town nearby',
    },
    {
        id: 'John Doe-123457',
        name: 'John Doe',
        employeeId: '123457',
        address: 'A town far away',
    },
];

下列範例示範如何使用輸出系結將數據寫入 Azure Cosmos DB。 系結會在函式的組態檔 (functions.json) 中宣告,並從佇列訊息擷取數據並寫出至 Azure Cosmos DB 檔。

{ 
  "name": "EmployeeDocument",
  "type": "cosmosDB",
  "databaseName": "MyDatabase",
  "collectionName": "MyCollection",
  "createIfNotExists": true,
  "connectionStringSetting": "MyStorageConnectionAppSetting",
  "direction": "out" 
} 

在 run.ps1 檔案中,從 函式傳回的對象會對應至EmployeeDocument資料庫中保存的物件。

param($QueueItem, $TriggerMetadata) 

Push-OutputBinding -Name EmployeeDocument -Value @{ 
    id = $QueueItem.name + '-' + $QueueItem.employeeId 
    name = $QueueItem.name 
    employeeId = $QueueItem.employeeId 
    address = $QueueItem.address 
} 

下列範例示範如何將檔寫入 Azure Cosmos DB 資料庫作為函式的輸出。 此範例取決於您使用的是 v1 或 v2 Python 程式設計模型

import logging
import azure.functions as func

app = func.FunctionApp()

@app.route()
@app.cosmos_db_output(arg_name="documents", 
                      database_name="DB_NAME",
                      collection_name="COLLECTION_NAME",
                      create_if_not_exists=True,
                      connection_string_setting="CONNECTION_SETTING")
def main(req: func.HttpRequest, documents: func.Out[func.Document]) -> func.HttpResponse:
    request_body = req.get_body()
    documents.set(func.Document.from_json(request_body))
    return 'OK'

屬性

進程內隔離的背景工作進程 C# 連結庫都會使用屬性來定義函式。 C# 文稿會改用function.json組態檔,如 C# 腳本指南中所述

Attribute 屬性 描述
[連接] 應用程式設定或設定集合的名稱,該名稱會指定如何連接到要監視的 Azure Cosmos DB 帳戶。 如需詳細資訊,請參閱連線
DatabaseName 該 Azure Cosmos DB 資料庫名稱含有要監視的容器。
ContainerName 要監視的容器名稱。
CreateIfNotExists 一個布林值,用來指出當容器不存在時,是否要建立集合。 預設是 false,因為新容器建立時會保留輸送量,對成本可能會有所影響。 如需詳細資訊,請參閱價格網頁
PartitionKey CreateIfNotExists 為 true 時,它會定義所建立容器的分割區金鑰路徑。 可能包含繫結參數。
ContainerThroughput CreateIfNotExists 為 true 時,它會定義所建立容器的輸送量
PreferredLocations (選用) 定義 Azure Cosmos DB 服務中異地複寫資料庫帳戶的慣用位置 (區域)。 應該以逗號將值分隔。 例如: East US,South Central US,North Europe

裝飾項目

僅適用於 Python v2 程式設計模型。

針對使用裝飾項目定義的 Python v2 函式,在上 cosmos_db_output具有下列屬性:

屬性 說明
arg_name 函式程式碼中使用的變數名稱,代表有變更的文件清單。
database_name 受監視集合的 Azure Cosmos DB 資料庫名稱。
collection_name 要監視的 Azure Cosmos DB 集合名稱。
create_if_not_exists 布爾值,指出如果資料庫和集合不存在,是否應該建立資料庫和集合。
connection_string_setting 正在監視的 Azure Cosmos DB 連接字串。

如需使用 function.json 定義的 Python 函式,請參閱組 一節。

註釋

從 Java 函式運行時間連結庫,對寫入 Azure Cosmos DB 的參數使用@CosmosDBOutput註釋。 註解支援下列屬性:

組態

僅適用於 Python v1 程式設計模型。

下表說明您可以在傳遞至 output.cosmosDB() 方法的物件options上設定的屬性。 typedirectionname 屬性不適用於 v4 模型。

下表說明您在 function.json 檔案中設定的系結組態屬性,其中屬性與延伸模組版本不同:

function.json 屬性 描述
connection 應用程式設定或設定集合的名稱,該名稱會指定如何連接到要監視的 Azure Cosmos DB 帳戶。 如需詳細資訊,請參閱連線
databaseName 該 Azure Cosmos DB 資料庫名稱含有要監視的容器。
containerName 要監視的容器名稱。
createIfNotExists 一個布林值,用來指出當容器不存在時,是否要建立集合。 預設是 false,因為新容器建立時會保留輸送量,對成本可能會有所影響。 如需詳細資訊,請參閱價格網頁
partitionKey createIfNotExists 為 true 時,它會定義所建立容器的分割區金鑰路徑。 可能包含繫結參數。
containerThroughput createIfNotExists 為 true 時,它會定義所建立容器的輸送量
preferredLocations (選用) 定義 Azure Cosmos DB 服務中異地複寫資料庫帳戶的慣用位置 (區域)。 應該以逗號將值分隔。 例如: East US,South Central US,North Europe

如需完整範例, 請參閱範例一節

使用方式

根據預設,當您在函式中寫入輸出參數時,會在資料庫中建立檔。 您應該指定輸出檔的檔案識別碼,方法是在傳遞至輸出參數的 JSON 物件中指定 id 屬性。

注意

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

Cosmos DB 輸出系結所支持的參數類型取決於 Functions 運行時間版本、擴充套件版本,以及所使用的 C# 形式。

當您要函式寫入單一檔時,Cosmos DB 輸出系結可以繫結至下列類型:

類型 描述
JSON 可序列化型別 物件,表示檔的 JSON 內容。 函式會嘗試將一般舊的CLR物件 (POCO) 類型串行化為 JSON 數據。

當您要函式寫入多個檔案時,Cosmos DB 輸出系結可以繫結至下列類型:

類型 描述
T[] 其中 T 是 JSON 可串行化類型 包含多個檔的陣列。 每個專案都代表一份檔。

針對其他輸出案例,請直接從 Microsoft.Azure.Cosmos 建立和使用類型。

連線

connectionStringSetting/connectionleaseConnectionStringSetting/leaseConnection 屬性是環境組態的參考,其會指定應用程式應該如何連線到 Azure Cosmos DB。 他們可以指定:

如果設定的值既與單一設定完全相符,又是其他設定的前置詞比對,則會使用完全相符專案。

連接字串

資料庫帳戶的 連接字串 應該儲存在應用程式設定中,其名稱符合系結組態的連接屬性所指定的值。

身分識別型連線

如果您使用 4.x 版或更高版本的延伸模組,而不是使用具有秘密的 連接字串,您可以讓應用程式使用 Microsoft Entra 身分識別。 若要執行此動作,您會在觸發程序和繫結設定中對應至「連線」屬性的通用前置詞下定義設定。

在此模式中,延伸模組需要下列屬性:

屬性 環境變數範本 描述 範例值
帳戶端點 <CONNECTION_NAME_PREFIX>__accountEndpoint Azure Cosmos DB 帳戶端點 URI。 <https:// database_account_name.documents.azure.com:443/>

其他屬性可以設定為自定義連線。 請參閱 身分識別型連線的一般屬性。

主控於 Azure Functions 服務時,以身分識別為基礎的連接會使用受控識別。 雖然可以使用 credentialclientID 屬性指定使用者指派的身分識別,但預設會使用系統指派的身分識別。 請注意,不支援使用資源標識符設定使用者指派的身分識別。 在其他內容中執行時,例如本機開發,會改用您的開發人員身分識別,但您可以自定義此身分識別。 請參閱 使用身分識別型連線進行本機開發。

授與權限給身分識別

正在使用的任何身分識別,都必須具有執行預期動作的權限。 對於大部分的 Azure 服務,這表示您必須 使用內建或自定義角色,在 Azure RBAC 中指派角色,以提供這些許可權。

重要

部分權限可能會由所有內容都不需要的目標服務公開。 可以的話,請遵循最低權限原則,只授與身分識別所需的權限。 例如,如果應用程式只需要能夠從數據源讀取,請使用只有讀取許可權的角色。 指派也允許寫入該服務的角色是不適當的,因為這會是讀取作業的過度許可權。 同樣地,您會想要確保角色指派的範圍僅限於需要讀取的資源。

Cosmos DB 不會針對數據作業使用 Azure RBAC。 相反地,它會使用 以類似概念為基礎的 Cosmos DB 內建 RBAC 系統 。 您必須建立角色指派,以在運行時間提供資料庫帳戶的存取權。 Azure RBAC 管理角色,例如 擁有者 不足。 下表顯示在正常作業中使用 Azure Cosmos DB 擴充功能時建議的內建角色。 您的應用程式可能需要根據您撰寫的程式代碼來取得其他許可權。

繫結類型 範例內建角色1
觸發程式2 Cosmos DB 內建數據參與者
輸入繫結 Cosmos DB 內建數據讀取器
輸出繫結 Cosmos DB 內建數據參與者

1 這些角色不能用於 Azure RBAC 角色指派中。 如需如何指派這些角色的詳細資訊,請參閱 Cosmos DB 內建的 RBAC 系統檔。

2 使用身分識別時,Cosmos DB 會將容器建立視為管理作業。 它無法做為觸發程式的數據平面作業。 在設定函式之前,您必須確定您已建立觸發程式所需的容器(包括租用容器)。

例外狀況和傳回碼

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

下一步