1
votes

I need to write an Azure Function that returns data against a Cosmos DB Database using Version 2 of Azure Functions. However, I am having hard time finding any good examples on how to do this. I can find very basic examples that involve search on an id.

I want to be able to send the azure function some fields to query on. Such as "Likes" and "City" with in a partition and outside a partition as well. I want it to return all the all the records as json documents.

Example of Cosmos DB Json document.

{ "id": "46465464565455566546bddgd" "Name": "Scott Smith" "City": "Scottsdale" "_pk": "56"

My code so far

`
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;

using Newtonsoft.Json;

namespace csharp { public static class GetData {

    private static readonly string CosmosDbApiKey = Environment.GetEnvironmentVariable("CosmosDbApiKey");
    private static readonly string CosmosDbUri = Environment.GetEnvironmentVariable("CosmosDbUri");
    private static readonly DocumentClient DocumentClient = new DocumentClient(new Uri(CosmosDbUri), CosmosDbApiKey);


    [FunctionName(nameof(GetData))]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "api/data/getdata/{city}{likes},{_pk}")]HttpRequest req,
        string city,
        string likes,
        string _pk,
        TraceWriter log)
    {

        IActionResult result;

        try
        {

            var Options = new RequestOptions() { PartitionKey = new PartitionKey(_pk) };
            var Sql = "SELECT * FROM c" WHERE c.name={name};

            var Uri = UriFactory.CreateDocumentCollectionUri("meddb", "medcol");
            var documentUri = DocumentClient.CreateDocumentQuery(Uri, Sql, Options);
            ResourceResponse<Document> document = await DocumentClient.ReadDocumentAsync(documentUri);


            result = new OkObjectResult(
                JsonConvert.SerializeObject(document.Resource, Formatting.Indented)
            );
        }
        catch (Exception e)
        {
            log.Error(e.Message, e);
            result = new BadRequestObjectResult(e);
        }

        return result;
    }
}
}
  `

I would greatly appreciate any help! Where I am having is issues is after the "Try" section. Or if there is a better way of doing this I am open too!

Thank you!

1
What database are you using ? Mongo, Graph API, Table storage ?Thomas
I am using dot net SQL APIJeremy W

1 Answers

4
votes

The standard way to connect Functions to Cosmos DB is to use Azure Cosmos DB bindings. See that article for installation instructions.

You can also get an instance of DocumentClient from it to execute custom queries. Several examples of using the binding can be found in Functions Recipes: Cosmos DB (DocumentDB) Bindings (they are for v1, so still DocumentDB).

Your code will look like:

[FunctionName(nameof(GetData))]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "api/data/getdata/{city}{likes},{_pk}")] HttpRequest req,
    [CosmosDB("test", "test", ConnectionStringSetting = "CosmosDB")] DocumentClient client, 
    string city,
    string likes,
    string _pk,
    TraceWriter log)

The implementation of the method shouldn't be different, and it's not really specific to Functions.

P.S. You haven't mentioned any specific problems, but if you have troubles writing proper query, make a new question with smaller code sample with Cosmos DB code only and exact problem statement.