简体   繁体   中英

Azure C#, filtering raw data stored in a cosmos DB (displayed through the function URL)

I have JSON data (temperature, humidity, light) that is stored in a cosmos DB and is shown as raw data in the function URL, I am able to return all data unfiltered. How would I be able to filter this data, to only show specific data such as temperature, Im new to azure and I have no idea how I would start.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, IEnumerable<dynamic> inputDocument, ILogger log)
{
    var result = new OkObjectResult(inputDocument);
    return result;
}

I have attempted to store result in a JSON object but when I return it, there is no data in the function URL.

Data that I am attempting to filter:

[
  {
    "myIoTHubMessage": "{\"temperature\":34.123939224110885,\"humidity\":64.35605799050818,\"light\":21.041931184493905,\"decibel\":14.208070081289891}"
  }
]

Based on this comment:

Id like to return a subset of data provided to the function, so lets say I store temperature, humidity and light, I would like to filter out humidity and light so it only displays temperature when returned

This can be as simple as returning an Anonymous type .

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

In your specific case (pseudo code):

public static async Task<IActionResult> Run(HttpRequest req, IEnumerable<dynamic> inputDocuments, ILogger log)
{
    return new OkObjectResult(inputDocuments.Select(document => new 
    {
        Temperature = document.Temperature
    }));
}

BTW: If you know the type of the documents coming in, you might want to explicitly type them instead of using dynamic .

EDIT:
As I specified, I posted some pseudo code to give you a general feel of how this might work. There is some work involved in actually getting it to work for your specific scenario. For instance: based on the question you posted, we didn't have any idea about the structure of your message.

I checked, this code works:

dynamic dyn = JsonConvert.DeserializeObject("{ \"myIoTHubMessage\": {\"temperature\":34.123939224110885,\"humidity\":64.35605799050818,\"light\":21.041931184493905,\"decibel\":14.208070081289891 } }");
var x = new { Temperature = dyn.myIoTHubMessage.temperature };

x 的值

Now it's up to you to make it work in your scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM