Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Modifying Data before inserting it in Cosmos DB

I am doing an HTTP trigger in Azure Function which add or update data in the Cosmos Db based on a condition. The data which is inserted has a modified date key(see below). I would like to update this key into date when this trigger ran and updated the record in Cosmos Db. If the update of Modified Date key is not possible, then I would prefer adding a new key here like date Updated and insert the current date.

How can I achieve this??

here is the code and structure of data inserted

public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,            
            ILogger log )
        {
           


            log.LogInformation("C# HTTP trigger function processed a request.");
            bool upsert = bool.Parse(req.Query["upsert"]);
            string cosmosDbKey = "TestDJIWEHLM+4Jw==";
            string cosmosDbInstance = "https://localhost:80761";
            string cosmosDbName = "TestProfiles";
            string cosmosDbCollection = "Profiles";
            Uri CollectionUri = UriFactory.CreateDocumentCollectionUri( cosmosDbName, cosmosDbCollection );
            DocumentClient Client = new DocumentClient( new Uri( cosmosDbInstance ), cosmosDbKey );

            string requestBody = await new StreamReader( req.Body ).ReadToEndAsync();
           

            string responseMessage =  upsert;
               
            var rec = JsonConvert.DeserializeObject( requestBody );
            var obj = JObject.Parse( rec.ToString() );
            if( upsert )
            {
                await Client.CreateDocumentAsync(
                    CollectionUri,
                    obj );
            }
            else
            {
                await Client.UpsertDocumentAsync(
                CollectionUri,
                obj);
            }
          
            
            return new OkObjectResult( responseMessage );
           

        }
    }

The Obj which I am inserting/Update is of this format:

{
    "id": "Test",
    "Type": "tes",
    "LastModified": "2020-03-29T22:22:25.6016794Z",
    "Tags": `["ta` btest "," tabtest2 "]," Properties ":{}," Categories ":[]," Quality ":{" Level ":0}," System ":{" OSVersion ":{" Platform ":2," ServicePack ":" "," Version ":" 10.0.19042.0 "," VersionString ":" Microsoft Windows NT 10.0.19042.0 "}}," DataSets ":[{" Name ":" DataSet1 "," DataFiles ":[{" Name ":" Readme.txt "," LastModified ":" 2020 - 03 - 29T22: 21: 30.570373Z "," Digest ":{" Hash ":" sAxMlg == "," Length ":5}}]}]," FileStore ":{" Service ":" AZURE "}," _etag ":"  "0500b9f2-0000-0c00-0000-5f884cba0000"",
    "Trigger": true,
    "Project": "TDemo",
    "ProjectId": "0mh45lfb.zqr"
}

requestBody:

"{"id":"Test","DocType":"REC","LastModified":"2020-03-29T22:22:25.6016794Z","Tags":["tabtest","tabtest2"],"Properties":{},"Categories":[],"Quality":{"Level":0},"System":{"OSVersion":{"Platform":2,"ServicePack":"","Version":"10.0.19042.0","VersionString":"Microsoft Windows NT 10.0.19042.0"}},"DataSets":[{"Name":"DataSet1","DataFiles":[{"Name":"Readme.txt","LastModified":"2020-03-29T22:21:30.570373Z","Digest":{"Hash":"sAnyGxMlg==","Length":5}}]}],"FileStore":{"Service":"AZURE"},"_etag":"\"0500b9f2-0000-0c00-0000-5f884cba0000\"","Trigger":true,"Project":"Test","ProjectId":"0mh45lfb.zqr"}"
            
question from:https://stackoverflow.com/questions/65950917/modifying-data-before-inserting-it-in-cosmos-db

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can achieve it by playing a little with Newtonsoft.Json:

 public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            bool upsert = bool.Parse(req.Query["upsert"]);
            string cosmosDbKey = "TestDJIWEHLM+4Jw==";
            string cosmosDbInstance = "https://localhost:80761";
            string cosmosDbName = "TestProfiles";
            string cosmosDbCollection = "Profiles";
            Uri CollectionUri = UriFactory.CreateDocumentCollectionUri(cosmosDbName, cosmosDbCollection);
            DocumentClient Client = new DocumentClient(new Uri(cosmosDbInstance), cosmosDbKey);

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();


            string responseMessage = upsert;

            var rec = JsonConvert.DeserializeObject<DBObject>(requestBody);
            rec.LastModified = DateTime.UtcNow;
            var obj = JObject.Parse(rec.ToString());

            if (upsert)
            {
                await Client.CreateDocumentAsync(
                    CollectionUri,
                    obj);
            }
            else
            {
                await Client.UpsertDocumentAsync(
                CollectionUri,
                obj);
            }


            return new OkObjectResult(responseMessage);


        }

        public class DBObject
        {
            public string id { get; set; }
            public string Type { get; set; }
            public DateTime LastModified { get; set; }
            public string[] Tags { get; set; }
            public string Project { get; set; }
            public string ProjectId { get; set; }
        }

    }

Suggestion (not a part of your question's answer): Don't take LastModified value in request body of Azure Function. You should always change DateTime (CDC - Change Data Capture) values at Data Access layer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...