Azure Functions 的 Azure 數據表輸入系結

使用 Azure 數據表輸入系結,讀取 Azure Cosmos DB 中的數據表作為數據表Azure 數據表 儲存體

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

重要

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

範例

系結的使用方式取決於函式應用程式中所使用的擴充套件版本和 C# 形式,這可以是下列其中一項:

已編譯 C# 函式的隔離背景工作進程類別庫會在與運行時間隔離的進程中執行。

選擇版本以查看模式和版本的範例。

下列 MyTableData 類別代表資料表中的數據列:

public class MyTableData : Azure.Data.Tables.ITableEntity
{
    public string Text { get; set; }

    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTimeOffset? Timestamp { get; set; }
    public ETag ETag { get; set; }
}

下列函式是由 Queue 儲存體 觸發程式啟動,會從佇列讀取數據列索引鍵,用來從輸入數據表取得數據列。 表達式 {queueTrigger} 會將數據列索引鍵系結至訊息元數據,也就是訊息字串。

[Function("TableFunction")]
[TableOutput("OutputTable", Connection = "AzureWebJobsStorage")]
public static MyTableData Run(
    [QueueTrigger("table-items")] string input,
    [TableInput("MyTable", "<PartitionKey>", "{queueTrigger}")] MyTableData tableInput,
    FunctionContext context)
{
    var logger = context.GetLogger("TableFunction");

    logger.LogInformation($"PK={tableInput.PartitionKey}, RK={tableInput.RowKey}, Text={tableInput.Text}");

    return new MyTableData()
    {
        PartitionKey = "queue",
        RowKey = Guid.NewGuid().ToString(),
        Text = $"Output record with rowkey {input} created at {DateTime.Now}"
    };
}

下列佇列觸發函式會以 傳回前 5 個 IEnumerable<T>實體,並將分割區索引鍵值設定為佇列訊息。

[Function("TestFunction")]
public static void Run([QueueTrigger("myqueue", Connection = "AzureWebJobsStorage")] string partition,
    [TableInput("inTable", "{queueTrigger}", Take = 5, Filter = "Text eq 'test'", 
    Connection = "AzureWebJobsStorage")] IEnumerable<MyTableData> tableInputs,
    FunctionContext context)
{
    var logger = context.GetLogger("TestFunction");
    logger.LogInformation(partition);
    foreach (MyTableData tableInput in tableInputs)
    {
        logger.LogInformation($"PK={tableInput.PartitionKey}, RK={tableInput.RowKey}, Text={tableInput.Text}");
    }
}

FilterTake 屬性可用來限制傳回的實體數目。

下列範例顯示 HTTP 觸發的函式,其會傳回數據表記憶體中指定分割區中的人員物件清單。 在此範例中,分割區索引鍵是從 HTTP 路由擷取,而 tableName 和 connection 則是從函式設定中擷取。

public class Person {
    private String PartitionKey;
    private String RowKey;
    private String Name;

    public String getPartitionKey() { return this.PartitionKey; }
    public void setPartitionKey(String key) { this.PartitionKey = key; }
    public String getRowKey() { return this.RowKey; }
    public void setRowKey(String key) { this.RowKey = key; }
    public String getName() { return this.Name; }
    public void setName(String name) { this.Name = name; }
}

@FunctionName("getPersonsByPartitionKey")
public Person[] get(
        @HttpTrigger(name = "getPersons", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.FUNCTION, route="persons/{partitionKey}") HttpRequestMessage<Optional<String>> request,
        @BindingName("partitionKey") String partitionKey,
        @TableInput(name="persons", partitionKey="{partitionKey}", tableName="%MyTableName%", connection="MyConnectionString") Person[] persons,
        final ExecutionContext context) {

    context.getLogger().info("Got query for person related to persons with partition key: " + partitionKey);

    return persons;
}

TableInput 註釋也可以從要求的 json 主體擷取系結,如下列範例所示。

@FunctionName("GetPersonsByKeysFromRequest")
public HttpResponseMessage get(
        @HttpTrigger(name = "getPerson", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.FUNCTION, route="query") HttpRequestMessage<Optional<String>> request,
        @TableInput(name="persons", partitionKey="{partitionKey}", rowKey = "{rowKey}", tableName="%MyTableName%", connection="MyConnectionString") Person person,
        final ExecutionContext context) {

    if (person == null) {
        return request.createResponseBuilder(HttpStatus.NOT_FOUND)
                    .body("Person not found.")
                    .build();
    }

    return request.createResponseBuilder(HttpStatus.OK)
                    .header("Content-Type", "application/json")
                    .body(person)
                    .build();
}

下列範例會使用篩選條件來查詢 Azure 數據表中具有特定名稱的人員,並將可能的相符項目數目限制為 10 個結果。

@FunctionName("getPersonsByName")
public Person[] get(
        @HttpTrigger(name = "getPersons", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.FUNCTION, route="filter/{name}") HttpRequestMessage<Optional<String>> request,
        @BindingName("name") String name,
        @TableInput(name="persons", filter="Name eq '{name}'", take = "10", tableName="%MyTableName%", connection="MyConnectionString") Person[] persons,
        final ExecutionContext context) {

    context.getLogger().info("Got query for person related to persons with name: " + name);

    return persons;
}

下列範例顯示使用佇列觸發程式讀取單一數據表數據列的數據表輸入系結。 繫結會 partitionKey 指定 和 rowKeyrowKey值 “{queueTrigger}” 表示數據列索引鍵來自佇列消息字串。

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

const tableInput = input.table({
    tableName: 'Person',
    partitionKey: 'Test',
    rowKey: '{queueTrigger}',
    connection: 'MyStorageConnectionAppSetting',
});

interface PersonEntity {
    PartitionKey: string;
    RowKey: string;
    Name: string;
}

export async function storageQueueTrigger1(queueItem: unknown, context: InvocationContext): Promise<void> {
    context.log('Node.js queue trigger function processed work item', queueItem);
    const person = <PersonEntity>context.extraInputs.get(tableInput);
    context.log('Person entity name: ' + person.Name);
}

app.storageQueue('storageQueueTrigger1', {
    queueName: 'myqueue-items',
    connection: 'MyStorageConnectionAppSetting',
    extraInputs: [tableInput],
    handler: storageQueueTrigger1,
});
const { app, input } = require('@azure/functions');

const tableInput = input.table({
    tableName: 'Person',
    partitionKey: 'Test',
    rowKey: '{queueTrigger}',
    connection: 'MyStorageConnectionAppSetting',
});

app.storageQueue('storageQueueTrigger1', {
    queueName: 'myqueue-items',
    connection: 'MyStorageConnectionAppSetting',
    extraInputs: [tableInput],
    handler: (queueItem, context) => {
        context.log('Node.js queue trigger function processed work item', queueItem);
        const person = context.extraInputs.get(tableInput);
        context.log('Person entity name: ' + person.Name);
    },
});

下列函式會使用佇列觸發程式,將單一數據表數據列讀取為函式的輸入。

在這裡範例中,系結組態會指定資料表的 partitionKey 明確值,並使用表示式傳遞至 rowKey。 表達式 {queueTrigger}表示數據rowKey列索引鍵來自佇列消息字串。

function.json中的系結組

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "MyQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "PersonEntity",
      "type": "table",
      "tableName": "Person",
      "partitionKey": "Test",
      "rowKey": "{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    }
  ],
  "disabled": false
}

run.ps1 中的 PowerShell 程序代碼:

param($MyQueueItem, $PersonEntity, $TriggerMetadata)
Write-Host "PowerShell queue trigger function processed work item: $MyQueueItem"
Write-Host "Person entity name: $($PersonEntity.Name)"

下列函式會使用 HTTP 觸發程式,將單一數據表數據列讀取為函式的輸入。

在這裡範例中,系結組態會指定資料表的 partitionKey 明確值,並使用表示式傳遞至 rowKey。 表達式 rowKey{id} 表示數據列索引鍵來自 {id} 要求中路由的一部分。

function.json 檔案中的系結組態:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "messageJSON",
      "type": "table",
      "tableName": "messages",
      "partitionKey": "message",
      "rowKey": "{id}",
      "connection": "AzureWebJobsStorage",
      "direction": "in"
    },
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ],
      "route": "messages/{id}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ],
  "disabled": false
}

__init__.py 檔案中的 Python 程式代碼:

import json

import azure.functions as func

def main(req: func.HttpRequest, messageJSON) -> func.HttpResponse:

    message = json.loads(messageJSON)
    return func.HttpResponse(f"Table row: {messageJSON}")

透過這個簡單的系結,您無法以程式設計方式處理沒有找到數據列索引鍵標識碼的數據列。 如需更精細的數據選取,請使用 記憶體 SDK


屬性

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

C# 類別庫中,支援 TableInputAttribute 下列屬性:

Attribute 屬性 描述
TableName 資料表的名稱。
PartitionKey 選擇性。 要讀取之資料表實體的分割區索引鍵。
RowKey 選擇性。 要讀取之資料表實體的資料列索引鍵。
Take 選擇性。 要讀取到 IEnumerable<T>的實體數目上限。 無法與 RowKey 搭配使用。
Filter 選擇性。 要讀取至 之實體的 IEnumerable<T>OData 篩選表達式。 無法與 RowKey 搭配使用。
[連接] 指定如何連線到資料表服務的應用程式設定或設定集合名稱。 請參閱連線

註釋

Java 函式運行時間連結庫中,對 @TableInput 值來自數據表記憶體的參數使用註釋。 此批注可以搭配原生 Java 類型、POJO 或使用 可為 Null 的值使用 Optional<T>。 此批註支援下列元素:

元素 描述
name 代表函式程式碼中的資料表或實體的變數名稱。
tableName 資料表的名稱。
partitionKey 選擇性。 要讀取之資料表實體的分割區索引鍵。
rowKey 選擇性。 要讀取之資料表實體的資料列索引鍵。
take 選擇性。 要讀取的實體數目上限。
filter 選擇性。 數據表輸入的 OData 篩選表達式。
connection 指定如何連線到資料表服務的應用程式設定或設定集合名稱。 請參閱連線

組態

下表說明您可以在傳遞至 input.table() 方法的物件options上設定的屬性。

屬性 說明
tableName 資料表的名稱。
partitionKey 選擇性。 要讀取之資料表實體的分割區索引鍵。
rowKey 選擇性。 要讀取之資料表實體的資料列索引鍵。 無法與 takefilter 搭配使用。
take 選擇性。 要傳回的實體數目上限。 無法與 rowKey 搭配使用。
filter 選擇性。 要從資料表傳回哪些實體的 OData 篩選條件運算式。 無法與 rowKey 搭配使用。
connection 指定如何連線到資料表服務的應用程式設定或設定集合名稱。 請參閱連線

組態

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

function.json 屬性 描述
type 必須設定為 table。 當您在 Azure 入口網站中建立繫結時,會自動設定此屬性。
direction 必須設定為 in。 當您在 Azure 入口網站中建立繫結時,會自動設定此屬性。
name 代表函式程式碼中的資料表或實體的變數名稱。
tableName 資料表的名稱。
partitionKey 選擇性。 要讀取之資料表實體的分割區索引鍵。
rowKey 選擇性。 要讀取之資料表實體的資料列索引鍵。 無法與 takefilter 搭配使用。
take 選擇性。 要傳回的實體數目上限。 無法與 rowKey 搭配使用。
filter 選擇性。 要從資料表傳回哪些實體的 OData 篩選條件運算式。 無法與 rowKey 搭配使用。
connection 指定如何連線到資料表服務的應用程式設定或設定集合名稱。 請參閱連線

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

連線

屬性 connection 是環境組態的參考,指定應用程式應該如何連線到您的數據表服務。 它可以指定:

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

連接字串

若要取得 Azure 資料表記憶體中數據表的 連接字串,請遵循管理記憶體帳戶存取密鑰中所述的步驟。 若要取得 Azure Cosmos DB for Table 中數據表的 連接字串,請遵循 Azure Cosmos DB for Table 常見問題所示的步驟。

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

如果應用程式設定名稱以 「AzureWebJobs」 開頭,您就只能在這裡指定名稱的其餘部分。 例如,如果您設定connection為 「My 儲存體」,Functions 運行時間會尋找名為 「AzureWebJobsMy 儲存體」 的應用程式設定。 如果您保留connection空白,Functions 運行時間會在名為 AzureWebJobsStorage的應用程式設定中使用預設 儲存體 連接字串。

身分識別型連線

如果您使用資料表 API 擴充功能,而不是使用具有秘密的 連接字串,您可以讓應用程式使用 Microsoft Entra 身分識別。 這隻適用於存取 Azure 儲存體 中的數據表時。 若要使用身分識別,您可以在對應至 connection 觸發程式和系結組態中 屬性的通用前置詞下定義設定。

如果您要將 設定connection為 「AzureWebJobs 儲存體」,請參閱使用身分識別來裝載記憶體 連線。 針對所有其他連線,擴充功能需要下列屬性:

屬性 環境變數範本 描述 範例值
數據表服務 URI <CONNECTION_NAME_PREFIX>__tableServiceUri1 您使用 HTTPS 設定連線 Azure 儲存體 資料表服務的數據平面 URI。 https://< storage_account_name.table.core.windows.net>

1<CONNECTION_NAME_PREFIX>__serviceUri 可作為別名。 如果提供這兩個窗體,則會 tableServiceUri 使用表單。 serviceUri在 Blob、佇列和/或數據表之間使用整體聯機組態時,無法使用表單。

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

serviceUri在 Azure 儲存體 中的 Blob、佇列和/或數據表之間使用整體聯機組態時,無法使用表單。 URI 只能指定資料表服務。 或者,您可以針對相同前置詞下的每個服務提供 URI,以允許使用單一連線。

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

授與權限給身分識別

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

重要

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

您必須建立角色指派,以在運行時間存取 Azure 儲存體 數據表服務。 擁有者之類的管理角色是不夠的。 下表顯示針對一般作業中的 Azure 儲存體 使用 Azure Tables 擴充功能時建議的內建角色。 您的應用程式可能需要根據您撰寫的程式代碼來取得其他許可權。

繫結類型 範例內建角色 (Azure 儲存體 1
輸入繫結 儲存體 數據表數據讀取器
輸出繫結 儲存體 數據表數據參與者

1 如果您的應用程式改為連線到適用於數據表的 Azure Cosmos DB 資料表,則不支援使用身分識別,且連線必須使用 連接字串。

使用方式

系結的使用方式取決於延伸模組套件版本,以及函式應用程式中所使用的 C# 形式,這可以是下列其中一項:

已編譯 C# 函式的隔離背景工作進程類別庫會在與運行時間隔離的進程中執行。

選擇版本以查看模式和版本的使用量詳細數據。

使用單一數據表實體時,Azure Tables 輸入系結可以系結至下列類型:

類型 描述
實作 ITableEntity 的 JSON 可串行化類型 函式會嘗試將實體還原串行化為一般舊的CLR物件 (POCO) 類型。 此類型必須實 作 ITableEntity 或具有字串 RowKey 屬性和字串 PartitionKey 屬性。
TableEntity1 實體做為類似字典的類型。

使用查詢中的多個實體時,Azure Tables 輸入系結可以系結至下列類型:

類型 描述
IEnumerable<T> 其中 T 實作 ITableEntity 查詢所傳回之實體的列舉。 每個專案都代表一個實體。 此類型 T 必須實 作 ITableEntity 或具有字串 RowKey 屬性和字串 PartitionKey 屬性。
TableClient1 線上至數據表的用戶端。 這會提供處理數據表的最充分控制權,而且如果連接有足夠的許可權,就可以用來寫入數據表。

1 若要使用這些類型,您必須參考 Microsoft.Azure.Functions.Worker.Extensions.Tables 1.2.0 或更新版本 ,以及 SDK 類型系結的通用相依性。

TableInput 屬性可讓您存取觸發函式的數據表數據列。

使用 context.extraInputs.get()取得輸入數據列數據。

數據會傳遞至輸入參數,如function.json檔案中的索引鍵所name指定。 指定和 partitionKeyrowKey 可讓您篩選至特定記錄。

數據表數據會以 JSON 字串的形式傳遞至函式。 呼叫 json.loads 來取消串行化訊息,如輸入 範例所示。

如需特定使用量詳細數據,請參閱 範例

下一步