Introduction
Azure Functions provides powerful built-in bindings for Azure Cosmos DB, enabling seamless integration with your NoSQL data. These bindings simplify data access by abstracting away the complexities of the Cosmos DB SDK, allowing you to focus on your function logic.
You can use these bindings for both input and output operations. This means you can easily read data from Cosmos DB into your function's parameters or write data from your function's return value to a Cosmos DB container.
Input Bindings
Input bindings allow you to retrieve documents from Cosmos DB and pass them as arguments to your Azure Function. The function can receive a single document, a collection of documents, or even a query result.
Example: Reading a single document
This example shows a C# function that retrieves a document based on its ID.
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.CosmosDB;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
public static class GetCosmosDocument
{
[FunctionName("GetCosmosDocument")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "items/{id}")] HttpRequest req,
[CosmosDB(
databaseName: "MyDatabase",
collectionName: "MyCollection",
ConnectionStringSetting = "CosmosDBConnection",
Id = "{id}",
PartitionKey = "{id}")] dynamic item,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
if (item == null)
{
return new NotFoundResult();
}
return new OkObjectResult(item);
}
}
Example: Querying multiple documents
This example demonstrates how to query documents based on a SQL query.
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.CosmosDB;
using System.Collections.Generic;
using System.Threading.Tasks;
public static class GetCosmosItemsByQuery
{
[FunctionName("GetCosmosItemsByQuery")]
public static async Task<IEnumerable<dynamic>> Run(
[TimerTrigger("0 */5 * * * *")] TimerInfo myTimer,
[CosmosDB(
databaseName: "MyDatabase",
collectionName: "MyCollection",
ConnectionStringSetting = "CosmosDBConnection",
SqlQuery = "SELECT * FROM c WHERE c.category = 'electronics'")] IEnumerable<dynamic> items,
ILogger log)
{
log.LogInformation($"Found {items.Count()} electronic items.");
return items;
}
}
Output Bindings
Output bindings allow you to write data from your Azure Function to a Cosmos DB container. This is commonly used to store results, logs, or processed data.
Example: Writing a document
This example shows a C# function that takes data from an HTTP request and saves it to Cosmos DB.
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.CosmosDB;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using System.IO;
using System.Text.Json;
public static class CreateCosmosDocument
{
[FunctionName("CreateCosmosDocument")]
[return: CosmosDB(
databaseName: "MyDatabase",
collectionName: "MyCollection",
ConnectionStringSetting = "CosmosDBConnection",
CreateIfNotExists = true)]
public static async Task<object> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "items")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function to create a Cosmos DB document processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonSerializer.Deserialize<dynamic>(requestBody);
data.id = System.Guid.NewGuid().ToString(); // Assign a new ID
return data;
}
}
Configuration
Cosmos DB connection information is typically stored in your Azure Functions application settings (e.g., in local.settings.json or Azure portal configuration). The ConnectionStringSetting property in the binding refers to the name of this setting.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"CosmosDBConnection": "AccountEndpoint=https://your-cosmos-db-account.documents.azure.com:443/;AccountKey=your-account-key;"
}
}
Key Features & Benefits
Simplified Data Access
Benefit: Reduces boilerplate code for interacting with Cosmos DB.
Declarative Configuration
Benefit: Bindings are configured in function signatures, making code cleaner.
Input & Output Support
Benefit: Versatile for reading data, writing data, and both.
Customizable Queries
Benefit: Supports powerful SQL queries for flexible data retrieval.
Scalability
Benefit: Leverages Azure Functions' scaling capabilities with Cosmos DB.
Connection Management
Description: Handled automatically via connection string settings.