3

I'm trying to connect an Azure DocumentDB and save documents using Azure Functions but I don't know how to create the connection.

OmG
  • 18,337
  • 10
  • 57
  • 90
Luís Fura
  • 263
  • 1
  • 3
  • 6
  • What have you tried so far, within your Azure Function? Please edit your question with more information. As your question currently stands, it's not really clear where you're stuck. – David Makogon Aug 02 '16 at 14:17
  • For now I created the database and created an azure function but I don't know how I can connect with the database to list, update, create, etc – Luís Fura Aug 02 '16 at 21:44
  • It's the same way as though you were doing on ASPNET app, Console App and so on. You're able to find an example here on my [repo](https://github.com/jr-araujo/AzureFunctionsCreateUser) – Jose Roberto Araujo Jul 03 '17 at 13:36

5 Answers5

4

You can do it using the Azure Portal. After you created the DocumentDB -

  • Create new Azure Function.
  • Go to the Integrate Tab.
  • You can choose Azure Document DB as an output for your function.
  • Choose your Document DB/Database Name/Collection you want to use.
  • Document parameter name is the Output of your function.

For example

using System;

public static void Run(string input, out object document, TraceWriter log)
{
    log.Info($"C# manually triggered function called with input: {input}");
    document = new {
        text = $"I'm running in a C# function! {input}"
    };
}

you need to provide out object which is the same as you defined in the output tab.

shachar
  • 589
  • 3
  • 12
  • And how I connect with the database and get the information? – Luís Fura Aug 02 '16 at 21:46
  • @LuísFura If you want to query document Db you have many guides online. For Example - https://azure.microsoft.com/en-us/documentation/articles/documentdb-get-started/ – shachar Aug 03 '16 at 07:09
  • I tried to add the azure.documents reference and I got an error message. Where I can add the references to my function? – Luís Fura Aug 03 '16 at 18:30
  • here you have a guide how to add reference to azure functions - https://azure.microsoft.com/en-us/documentation/articles/functions-reference-csharp/ also, from SO - http://stackoverflow.com/questions/36411536/how-can-i-use-nuget-packages-in-my-azure-functions – shachar Aug 04 '16 at 06:11
  • I just recently answered a similar question for access to DocumentClient from within a script: https://social.msdn.microsoft.com/Forums/azure/en-US/0d315697-f605-4489-ba0c-ab940b0612dc/azure-functions-with-azure-documentdb?forum=AzureFunctions – brettsam Aug 17 '16 at 18:16
  • is it the better option comparing to Azure Offline Snyc with azure sql table? Can cost be reduced and performance enhanced? – Emil Nov 14 '16 at 11:35
1

You can just use the document client directly:

var endpoint = "https://XXXXX.documents.azure.com:443/";
var authKey = "XXXXX";

using (var client = new DocumentClient(new Uri(endpoint), authKey))
{
    var sqlCountQuery = "select value count(1) from c";
    IDocumentQuery<dynamic> query = client.CreateDocumentQuery<dynamic>(UriFactory.CreateDocumentCollectionUri("YOUR_DB_ID", "YOUR_COLLECTON_ID"), sqlCountQuery).AsDocumentQuery();
    ....
}
1

Azure Functions supports Document DB (Cosmos DB) out-of-the-box. You can just simply add an environment variable called AzureWebJobsDocumentDBConnectionString in V1 or AzureWebJobsCosmosDBConnectionString in V2.

Then just use a CosmosDBTrigger binding attribute for input binding like (in C# for example):

public static class UpsertProductCosmosDbTrigger
{
    [FunctionName("ProductUpsertCosmosDbTrigger")]
    public static void Run(
        [CosmosDBTrigger(
        // Those names come from the application settings.
        // Those names can come with both preceding % and trailing %.
        databaseName: "CosmosDbDdatabaseName",
        collectionName: "CosmosDbCollectionName",
        LeaseDatabaseName = "CosmosDbDdatabaseName",
        LeaseCollectionName = "CosmosDbLeaseCollectionName")] 
        IReadOnlyList<Document> input,

        TraceWriter log)
...

For output binding use DocumentDB output binding attribute in V1 and CosmosDB in V2 like:

[FunctionName("ProductUpsertHttpTrigger")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = "products")] 
    HttpRequestMessage req,

    [DocumentDB(
    databaseName: "%CosmosDbDdatabaseName%",
    collectionName: "%CosmosDbCollectionName%")] IAsyncCollector<Product> collector,

    TraceWriter log)
...

I've written a blog post about this: https://blog.mexia.com.au/cosmos-db-in-azure-functions-v1-and-v2

justinyoo
  • 2,123
  • 1
  • 21
  • 24
0
var EndpointUrl = "EndpointUrl";
var PrimaryKey = "PrimaryKeyValue" 
this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
Database database = await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = cosmoDbName });

you can get the End-point-URL and Primary-Key value from the azure portal in the keys section.

ABaig
  • 99
  • 1
  • 10
0

Assume C# has similar SDK like Java. The below is for Java

There are two ways you can connect to documentDB from an Azure function.

  1. Using SDK

    DocumentClient documentClient = new DocumentClient( "SERVICE_ENDPOINT", "MASTER_KEY", ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);

Refer - [https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-java-samples][1]. This has .Net Samples too.

  1. Binding

    @FunctionName("CosmosDBStore") @CosmosDBOutput(name = "database", databaseName = "db_name", collectionName = "col_name", connectionStringSetting = "AzureCosmosDBConnection")

Please make sure you have a variable in the name of "AzureCosmosDBConnection" in your application settings and local.settings.json(if you want to test locally)

Refer - [https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb-v2][1]

The above link has C# example too.

T D
  • 1,080
  • 2
  • 13
  • 20