Azure Function V2 against Cosmos Db DocumentClient

二次信任 提交于 2019-12-24 08:57:45

问题


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:


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.



来源:https://stackoverflow.com/questions/50546157/azure-function-v2-against-cosmos-db-documentclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!