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!