Azure Functions Cosmos DB Bindings

Cosmos DB Bindings

Azure Functions provides built-in bindings for Azure Cosmos DB, simplifying integration with your serverless applications. These bindings allow you to easily read from and write to Cosmos DB collections without needing to write explicit SDK code.

Input Bindings

Input bindings enable you to retrieve documents from Cosmos DB and make them available to your function. You can bind to a single document or a collection of documents.

Single Document

To retrieve a single document, use an input binding with the id parameter.


{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "inputDocument",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "myDatabase",
      "collectionName": "myCollection",
      "id": "{id}",
      "partitionKey": "{partitionKey}",
      "connectionStringSetting": "CosmosDBConnection"
    }
  ]
}
                

In this example, {id} and {partitionKey} are typically passed from another trigger, such as an HTTP trigger's route parameters.

Collection of Documents

To retrieve multiple documents, you can bind to a collection. This is often used with queries.


{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "inputDocuments",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "myDatabase",
      "collectionName": "myCollection",
      "SqlQuery": "SELECT * FROM c WHERE c.status = 'active'",
      "connectionStringSetting": "CosmosDBConnection"
    }
  ]
}
                

Output Bindings

Output bindings allow you to write data to Cosmos DB. You can create new documents or replace existing ones.

Creating or Replacing Documents

Use an output binding to write a document to Cosmos DB.


{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "outputDocument",
      "type": "cosmosDB",
      "direction": "out",
      "databaseName": "myDatabase",
      "collectionName": "myCollection",
      "createIfNotExists": true,
      "connectionStringSetting": "CosmosDBConnection"
    }
  ]
}
                

In your function code, you would assign the document to the outputDocument variable.

Configuration

The Cosmos DB binding relies on a connection string defined in your application's settings (e.g., local.settings.json for local development or application settings in Azure).


{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "CosmosDBConnection": "AccountEndpoint=https://your-cosmosdb-account.documents.azure.com:443/;AccountKey=your-account-key;"
  }
}
                

Examples

Here's a simple example of a Python function that uses an HTTP trigger to receive data and an output binding to save it to Cosmos DB:


import logging
import azure.functions as func

def main(req: func.HttpRequest, outputDocument: func.Out[func.Document]) -> None:
    logging.info('Python HTTP trigger function processed a request.')

    try:
        req_body = req.get_json()
    except ValueError:
        logging.warning('Request body is not valid JSON.')
        return

    if req_body and 'id' in req_body and 'data' in req_body:
        document_to_save = {
            "id": req_body['id'],
            "data": req_body['data'],
            "timestamp": func.get_utc_now().isoformat()
        }
        outputDocument.set(func.Document.from_dict(document_to_save))
        logging.info(f"Document with id {req_body['id']} saved to Cosmos DB.")
    else:
        logging.warning('Missing required fields (id or data) in request body.')
                

Note on Partition Keys

When working with Cosmos DB, understanding and correctly using partition keys is crucial for performance and scalability. Ensure your bindings are configured to handle partition keys appropriately, especially when dealing with large datasets or specific queries.

Important Considerations

  • Always use connection strings stored securely in application settings, not directly in code.
  • For read operations, consider using Cosmos DB's built-in query capabilities for efficiency.
  • Pay attention to the createIfNotExists property for output bindings; setting it to true will create the collection if it doesn't exist (requires appropriate permissions).

Further Reading