Azure Cosmos DB output binding for Azure Functions 2.x and higher

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 框架上運行的 C# 函式。 孤立工作程序函式的擴充功能使用 Microsoft.Azure.Functions.Worker.Extensions.* 命名空間。
  • 同進程模型:在與 Functions 運行時間相同的進程中執行的已編譯 C# 函式。 在此模型的變化中,函式可以使用 C# 腳本來執行,主要支援 C# 入口網站編輯。 進行中功能的擴充功能使用 Microsoft.Azure.WebJobs.Extensions.* 命名空間。

範例

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

目前這款綁定沒有 Go 支援。

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

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

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

以下範例展示了一個 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 functions 執行時函式庫 中使用寫入 Azure Cosmos DB 的參數 @CosmosDBOutput 註解。 註解參數類型應為 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 程式代碼:

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

下列範例會針對接收下列格式 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 程式碼:

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

以下範例展示了如何使用輸出綁定寫入 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# 腳本指南中所述。

屬性內容 描述
[連接] 指定如何連接被監控的 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 資料庫名稱,包含被監控的容器。
container_name 被監控的 Azure Cosmos DB 容器名稱。
create_if_not_exists 布爾值,指出如果資料庫和集合不存在,是否應該建立資料庫和集合。
connection_string_setting 監控中 Azure Cosmos DB 的 連接字串。

關於使用 function.json 定義的Python函數,請參見 Configuration 章節。

註釋

從 Java 函式執行庫 中,對寫入 Azure Cosmos DB 的參數使用 @CosmosDBOutput 註解。 註解支援下列屬性:

組態

僅適用於 Python v1 程式模型。

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

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

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

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

使用方式

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

注意

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

輸出函式參數必須定義為 func.Out[func.Document]。 如需詳細資訊,請參閱 輸出範例 。

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

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

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

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

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

對於其他輸出情境,則建立並使用 CosmosClient,並搭配 Microsoft.Azure 的其他類型。Cosmos 直接。 請參見 Register Azure clients,了解如何利用依賴注入從 Azure SDK 建立客戶端類型。

連線

connection和 leaseConnection 屬性在應用程式設定中被設定為鍵,回傳 Functions 執行時用來連接 Azure Cosmos DB 帳號端點的值。 這些物業設定的價值取決於連接的類型:

  • 管理身份連線:該 connection 屬性由 <CONNECTION_NAME_PREFIX> 一組設定共享,這些設定共同定義了與帳戶的身份連結。 欲了解更多資訊,請參閱定義身份連結。
  • 金鑰保存庫 參考:connection屬性設定會回傳一個 Azure Key Vault 的參考,指向該 連接字串 集中維護的位置。 欲了解更多資訊,請參閱定義 金鑰保存庫 連接。
  • App Configuration 參考:connection屬性設定回傳一個 Azure 應用程式組態 參考,該參考會回傳一個 連接字串 或 金鑰保存庫 參考。 欲了解更多資訊,請參閱連接條目中的 Azure 應用程式組態。
  • Connection string:屬性設定會connection回傳實際的帳戶 連接字串。 由於 連接字串 包含共享的秘密金鑰,建議在可能的情況下使用管理身份連線。 欲了解更多資訊,請參閱定義連結。

想了解更多關於綁定連接的資訊,請參閱 Azure Functions 中的「管理連線」。 要取得 連接字串,請進入你的 Azure Cosmos DB 帳號,選擇 Keys,然後複製 PRIMARY CONNECTION STRING 或 SECONDARY CONNECTION STRING 值。 這些連接字串包含共享的秘密金鑰,必須加以保護。

在早期版本的擴展中,連接屬性被命名 connectionStringSetting 為 和 leaseConnectionStringSetting。

例外狀況和傳回碼

繫結 參考
Azure Cosmos DB HTTP 狀態碼用於 Azure Cosmos DB

下一步