Cosmos DB Bindings for Azure Functions
Azure Functions provides powerful input and output bindings for Azure Cosmos DB, a globally distributed, multi-model database service. These bindings simplify the process of reading from and writing to your Cosmos DB collections directly within your functions.
Key Features
- Input Bindings: Fetch documents or query a collection based on function parameters.
- Output Bindings: Insert or update documents in a Cosmos DB collection.
- Multiple API Support: Works with the Core (SQL) API, MongoDB API, Cassandra API, Gremlin API, and Table API.
- Change Feed Support: Trigger functions on changes within a Cosmos DB collection.
Input Bindings
You can configure input bindings to retrieve a single document, a collection of documents, or the result of a SQL query.
Single Document Input
Retrieve a document by its ID. The ID can be a literal string or bound from another input (e.g., HTTP request parameter).
{
"bindings": [
{
"name": "myDocument",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"id": "{id}",
"partitionKey": "{partitionKey}",
"connectionStringSetting": "CosmosDBConnectionString"
}
]
}
In your function code (e.g., C#):
public static void Run(MyDocumentType myDocument, ILogger log)
{
if (myDocument != null)
{
log.LogInformation($"Found document: {myDocument.Content}");
}
else
{
log.LogInformation("Document not found.");
}
}
Collection Input
Retrieve all documents from a collection or a subset based on a SQL query.
{
"bindings": [
{
"name": "items",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * FROM c WHERE c.status = 'active'",
"connectionStringSetting": "CosmosDBConnectionString"
}
]
}
In your function code (e.g., JavaScript):
module.exports = async function (context, items) {
context.log(`Processing ${items.length} active items.`);
items.forEach(item => {
context.log(`Item ID: ${item.id}, Content: ${item.content}`);
});
};
Output Bindings
Output bindings allow you to easily add or update documents in Cosmos DB.
Document Output
Insert or update a single document. If the document's ID and partition key already exist, it will be updated; otherwise, it will be inserted.
{
"bindings": [
{
"name": "outputDocument",
"type": "cosmosDB",
"direction": "out",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"connectionStringSetting": "CosmosDBConnectionString"
}
]
}
In your function code (e.g., Python):
import logging
def main(input: func.HttpRequest, outputDocument: func.Out[str]) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
document_data = {
"id": "new-item-123",
"content": "This is a new document.",
"status": "pending"
}
outputDocument.set(json.dumps(document_data))
return func.HttpResponse(
"Document created successfully.",
status_code=201
)
Change Feed Trigger
The Cosmos DB trigger allows you to execute a function automatically in response to changes in a Cosmos DB collection. This is ideal for implementing event-driven architectures.
{
"scriptFile": "index.js",
"bindings": [
{
"name": "documents",
"type": "cosmosDBTrigger",
"direction": "in",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"connectionStringSetting": "CosmosDBConnectionString",
"createLeaseCollectionIfNotExists": true
}
]
}
The documents parameter in your function will be an array of documents that have been added or modified since the last execution.
Configuration Options
Here's a summary of common configuration properties for Cosmos DB bindings:
| Property | Description | Required | Type |
|---|---|---|---|
name |
The name of the variable used to access the binding in your function code. | Yes | String |
type |
The type of binding (cosmosDB for input/output, cosmosDBTrigger for triggers). |
Yes | String |
direction |
in for input, out for output. Not applicable for triggers. |
Yes | Enum |
databaseName |
The name of the Cosmos DB database. | Yes | String |
collectionName |
The name of the Cosmos DB collection. | Yes | String |
connectionStringSetting |
The name of the application setting that contains your Cosmos DB connection string. | Yes | String |
id |
For input bindings: The ID of the document to retrieve. Can use binding expressions (e.g., {id}). |
No (unless sqlQuery is used) |
String |
partitionKey |
For input bindings: The partition key of the document to retrieve. Can use binding expressions (e.g., {partitionKey}). |
No (if id is specified and the collection has a simple partition key) |
String |
sqlQuery |
For input bindings: A SQL query to execute against the collection. | No (unless id is used and you need complex filtering) |
String |
leaseCollectionName |
For trigger bindings: The name of the collection used for managing leases. If not provided, it defaults to {collectionName}Leases. |
No | String |
createLeaseCollectionIfNotExists |
For trigger bindings: If set to true, the lease collection will be automatically created if it doesn't exist. |
No | Boolean |