Rediger

Azure Tables input bindings for Azure Functions

Use the Azure Tables input binding to read a table in Azure Cosmos DB for Table or Azure Table Storage.

For information on setup and configuration details, see the overview.

Important

This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. For more details about how the v4 model works, refer to the Azure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to the migration guide.

Example

Go support isn't currently available for this binding.

The usage of the binding depends on the extension package version and the C# modality used in your function app, which can be one of the following:

An isolated worker process class library compiled C# function runs in a process isolated from the runtime.

Choose a version to see examples for the mode and version.

The following MyTableData class represents a row of data in the table:

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; }
}

The following function, which is started by a Queue Storage trigger, reads a row key from the queue, which is used to get the row from the input table. The expression {queueTrigger} binds the row key to the message metadata, which is the message string.

[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}"
    };
}

The following Queue-triggered function returns the first 5 entities as an IEnumerable<T>, with the partition key value set as the queue message.

[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}");
    }
}

The Filter and Take properties are used to limit the number of entities returned.

The following example shows an HTTP triggered function which returns a list of person objects who are in a specified partition in Table storage. In the example, the partition key is extracted from the http route, and the tableName and connection are from the function settings.

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;
}

The TableInput annotation can also extract the bindings from the json body of the request, like the following example shows.

@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();
}

The following example uses a filter to query for persons with a specific name in an Azure Table, and limits the number of possible matches to 10 results.

@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;
}

The following example shows a table input binding that uses a queue trigger to read a single table row. The binding specifies a partitionKey and a rowKey. The rowKey value "{queueTrigger}" indicates that the row key comes from the queue message string.

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);
    },
});

The following function uses a queue trigger to read a single table row as input to a function.

In this example, the binding configuration specifies an explicit value for the table's partitionKey and uses an expression to pass to the rowKey. The rowKey expression, {queueTrigger}, indicates that the row key comes from the queue message string.

Binding configuration in 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
}

PowerShell code in run.ps1:

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

The following function uses an HTTP trigger to read a single table row as input to a function.

In this example, binding configuration specifies an explicit value for the table's partitionKey and uses an expression to pass to the rowKey. The rowKey expression, {id} indicates that the row key comes from the {id} part of the route in the request.

import json
import azure.functions as func

app = func.FunctionApp()

@app.route(route="messages/{id}")
@app.table_input(arg_name="messageJSON",
                 connection="AzureWebJobsStorage",
                 table_name="messages",
                 row_key='{id}',
                 partition_key="message")
def table_in_binding(req: func.HttpRequest, messageJSON):
    message = json.loads(messageJSON)
    return func.HttpResponse(f"Table row: {messageJSON}")

With this simple binding, you can't programmatically handle a case in which no row that has a row key ID is found. For more fine-grained data selection, use the storage SDK.

Attributes

Both in-process and isolated worker process C# libraries use attributes to define the function. C# script instead uses a function.json configuration file as described in the C# scripting guide.

In C# class libraries, the TableInputAttribute supports the following properties:

Attribute property Description
TableName The name of the table.
PartitionKey Optional. The partition key of the table entity to read.
RowKey Optional. The row key of the table entity to read.
Take Optional. The maximum number of entities to read into an IEnumerable<T>. Can't be used with RowKey.
Filter Optional. An OData filter expression for entities to read into an IEnumerable<T>. Can't be used with RowKey.
Connection The name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

Annotations

In the Java functions runtime library, use the @TableInput annotation on parameters whose value would come from Table storage. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>. This annotation supports the following elements:

Element Description
name The name of the variable that represents the table or entity in function code.
tableName The name of the table.
partitionKey Optional. The partition key of the table entity to read.
rowKey Optional. The row key of the table entity to read.
take Optional. The maximum number of entities to read.
filter Optional. An OData filter expression for table input.
connection The name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

Configuration

The following table explains the properties that you can set on the options object passed to the input.table() method.

Property Description
tableName The name of the table.
partitionKey Optional. The partition key of the table entity to read.
rowKey Optional. The row key of the table entity to read. Can't be used with take or filter.
take Optional. The maximum number of entities to return. Can't be used with rowKey.
filter Optional. An OData filter expression for the entities to return from the table. Can't be used with rowKey.
connection The name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

Configuration

The following table explains the binding configuration properties that you set in the function.json file.

function.json property Description
type Must be set to table. This property is set automatically when you create the binding in the Azure portal.
direction Must be set to in. This property is set automatically when you create the binding in the Azure portal.
name The name of the variable that represents the table or entity in function code.
tableName The name of the table.
partitionKey Optional. The partition key of the table entity to read.
rowKey Optional. The row key of the table entity to read. Can't be used with take or filter.
take Optional. The maximum number of entities to return. Can't be used with rowKey.
filter Optional. An OData filter expression for the entities to return from the table. Can't be used with rowKey.
connection The name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Connections

The connection property is set to a key in application settings that returns a value used by the Functions runtime to connect to the storage account used by the extension. The value of the connection property setting depends on the type of connection:

  • Managed identity connection: The connection property is a <CONNECTION_NAME_PREFIX> shared by a group of settings that together define an identity-based connection to the storage account. For more information, see Define identity connections.
  • Key Vault reference: The connection property setting returns an Azure Key Vault reference to the location where the connection string is centrally maintained. For more information, see Define Key Vault connections.
  • App Configuration reference: The connection property setting returns an Azure App Configuration reference that returns a connection string or a Key Vault reference. For more information, see Azure App Configuration in the connections article.
  • Connection string: The connection property setting returns the actual storage account connection string. Because the connection string contains shared secret keys, you should consider using a managed identity connection, when possible. For more information, see Define connections.

To learn more about bindings connections, see Manage connection in Azure Functions. To obtain a connection string, follow the steps shown at Manage storage account access keys.

When you set connection to a key or key prefix named AzureWebJobsStorage or to an empty string, the binding extension uses the default host storage account. For more information, see Optimize storage performance.

Usage

The usage of the binding depends on the extension package version, and the C# modality used in your function app, which can be one of the following:

An isolated worker process class library compiled C# function runs in a process isolated from the runtime.

Choose a version to see usage details for the mode and version.

When working with a single table entity, the Azure Tables input binding can bind to the following types:

Type Description
A JSON serializable type that implements ITableEntity Functions attempts to deserialize the entity into a plain-old CLR object (POCO) type. The type must implement ITableEntity or have a string RowKey property and a string PartitionKey property.
TableEntity1 The entity as a dictionary-like type.

When working with multiple entities from a query, the Azure Tables input binding can bind to the following types:

Type Description
IEnumerable<T> where T implements ITableEntity An enumeration of entities returned by the query. Each entry represents one entity. The type T must implement ITableEntity or have a string RowKey property and a string PartitionKey property.
TableClient1 A client connected to the table. This offers the most control for processing the table and can be used to write to it if the connection has sufficient permission.

1 To use these types, you need to reference Microsoft.Azure.Functions.Worker.Extensions.Tables 1.2.0 or later and the common dependencies for SDK type bindings.

The TableInput attribute gives you access to the table row that triggered the function.

Get the input row data by using context.extraInputs.get().

Data is passed to the input parameter as specified by the name key in the function.json file. Specifying The partitionKey and rowKey allows you to filter to specific records.

Table data is passed to the function as a JSON string. De-serialize the message by calling json.loads as shown in the input example.

For specific usage details, see Example.

Next steps