Azure Cosmos DB Bindings for Azure Functions
Azure Functions provides powerful bindings for Azure Cosmos DB, allowing you to easily read from and write to your Cosmos DB collections from within your serverless functions. These bindings abstract away the complexities of the Cosmos DB SDK, enabling you to focus on your business logic.
Supported Bindings
Input Bindings
Input bindings allow you to fetch data from Cosmos DB and pass it as parameters to your function. This is useful for scenarios where your function needs to operate on existing data.
Document Input
Fetch a single document based on an ID.
{
"bindings": [
{
"type": "cosmosDB",
"name": "inputDocument",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"id": "{id}",
"partitionKey": "{partitionKey}",
"connectionStringSetting": "CosmosDBConnectionString"
}
]
}
Collection Input
Fetch a collection of documents, optionally with a SQL query.
{
"bindings": [
{
"type": "cosmosDB",
"name": "inputCollection",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * FROM c WHERE c.status = 'Active'",
"connectionStringSetting": "CosmosDBConnectionString"
}
]
}
Output Bindings
Output bindings allow your function to write data to Cosmos DB. This is commonly used after processing data or responding to events.
Document Output
Write a single document to a Cosmos DB collection.
{
"bindings": [
{
"type": "cosmosDB",
"name": "outputDocument",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"createIfNotExists": true,
"connectionStringSetting": "CosmosDBConnectionString"
}
]
}
Important Considerations
When using output bindings, ensure your function correctly returns the data to be inserted or updated. The binding will handle the actual Cosmos DB operation.
Connection Strings
Cosmos DB connections are typically configured using connection strings stored in your Azure Functions application settings. The connectionStringSetting property in the binding configuration specifies the name of the application setting that holds the connection string.
Example connection string format:
AccountEndpoint=https://your-cosmos-db-account.documents.azure.com:443/;AccountKey=your-account-key;
Examples
C# Example: Reading and Writing Documents
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
public static class CosmosDbFunction
{
[FunctionName("CosmosDbTriggerExample")]
public static async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[CosmosDB(
databaseName: "MyDatabase",
collectionName: "MyCollection",
ConnectionStringSetting = "CosmosDBConnectionString",
Id = "{Query.id}",
PartitionKey = "{Query.partitionKey}"
)] CosmosDocument inputDocument,
[CosmosDB(
databaseName: "MyDatabase",
collectionName: "MyCollection",
ConnectionStringSetting = "CosmosDBConnectionString"
)] IAsyncCollector outputDocument,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
if (inputDocument != null)
{
log.LogInformation($"Document found: {JsonConvert.SerializeObject(inputDocument)}");
// Process the input document
var updatedDocument = inputDocument;
updatedDocument.Status = "Processed";
await outputDocument.AddAsync(updatedDocument);
return new OkObjectResult($"Document {inputDocument.Id} processed and updated.");
}
else
{
log.LogWarning("Document not found for the given ID and partition key.");
return new BadRequestObjectResult("Please pass an id and partitionKey on the query string or in the request body");
}
}
public class CosmosDocument
{
public string Id { get; set; }
public string Status { get; set; }
// Other properties
}
}
JavaScript Example: Reading and Writing Documents
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const documentId = context.bindingData.id;
const partitionKey = context.bindingData.partitionKey;
if (req.body && req.body.data) {
const dataToSave = req.body.data;
// Add or update document logic
context.bindings.outputDocument = dataToSave;
context.res = { status: 201, body: "Document created or updated." };
} else if (context.bindings.inputDocument) {
const inputDocument = context.bindings.inputDocument;
context.log(`Document found: ${JSON.stringify(inputDocument)}`);
// Modify and save if needed
inputDocument.status = "Processed";
context.bindings.outputDocument = inputDocument;
context.res = { status: 200, body: `Document ${documentId} processed and updated.` };
} else {
context.res = { status: 400, body: "Please pass a document or provide id/partitionKey." };
}
};
The exact configuration and usage might vary slightly based on your Azure Functions runtime version and the specific programming language you are using.