[英]Azure function C#: Create or replace document in cosmos db on HTTP request
我正在嘗試在C#中構建一個Azure函數,如果沒有ID,則使用SQL API在Azure cosmos DB中創建一個新的文檔對象,如果存在則更新一個文檔對象。
其背后的上下文是將聊天機器人對話歷史記錄到唯一的用戶會話中。
輸入:
帶有參數(id(字符串),chatHistory(字符串)和chatDateTime(字符串))的HTTP GET請求
輸出:
如果具有相同ID的文檔對象已經存在-請使用輸入chatHisotry和chatDateTime更新文檔。
如果不存在具有相同ID的文檔對象,則創建一個ID,chatHistory和chatDateTime等於輸入的新文檔對象。
任何幫助,不勝感激! 掙扎了幾天。
文檔對象示例:
{
"id": "ESCRfAKwlTbH8W5aVRLxgA",
"chatHistory": "Hi, Hello",
"chatDateTime": "Fri Sep 21 2018 05:34:35 GMT+0000 (Coordinated Universal Time)",
"_rid": "RwYSAIqaSVg2AAAAAAAAAA==",
"_self": "dbs/RwYSAA==/colls/RwYSAIqaSVg=/docs/RwYSAIqaSVg2AAAAAAAAAA==/",
"_etag": "\"00007400-0000-0000-0000-5ba482ed0000\"",
"_attachments": "attachments/",
"_ts": 1537508077
}
您可以使用Azure Functions的Cosmos DB輸出綁定 。 輸出綁定執行Upsert操作。
[FunctionName("HttpTriggerWithSingleDocument")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req,
[DocumentDB(databaseName: "your-db",
collectionName: "your-collection",
ConnectionStringSetting = "CosmosDBConnectionString")] out dynamic documentToSave)
{
dynamic data = await req.Content.ReadAsAsync<object>();
if (data == null)
{
documentToSave = null;
return req.CreateResponse(HttpStatusCode.BadRequest);
}
documentToSave = data;
return req.CreateResponse(HttpStatusCode.Created);
}
Azure門戶版本:
using System.Net;
public static async Task<HttpResponseMessage> Run(
HttpRequestMessage req,
IAsyncCollector<dynamic> documentsToStore)
{
dynamic data = await req.Content.ReadAsAsync<object>();
if (data == null)
{
return req.CreateResponse(HttpStatusCode.BadRequest);
}
await documentsToStore.AddAsync(data);
return req.CreateResponse(HttpStatusCode.Created);
}
而且您還需要將function.json
更新為以下內容:
{
"bindings": [
{
"name": "req",
"type": "httpTrigger",
"direction": "in"
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "documentDB",
"name": "documentsToStore",
"databaseName": "<your-database-name>",
"collectionName": "<your-collection-name>",
"createIfNotExists": false,
"connection": "<your-connection-setting-name>",
"direction": "out"
}
]
}
此處提供更多示例: https : //github.com/ealsur/serverless-recipes/tree/master/cosmosdboutputbindings
這是一個示例。 您只需要根據需要進行調整即可。
[FunctionName("Function1")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req,
TraceWriter log)
{
dynamic data = await req.Content.ReadAsAsync<object>();
var connectionString = "DbUri";
var key = "DbKey";
using (var client = new DocumentClient(new Uri(connectionString), key))
{
var collectionLink = UriFactory.CreateDocumentCollectionUri("DbName", "CollectionName");
await client.UpsertDocumentAsync(collectionLink, data);
}
return req.CreateResponse(HttpStatusCode.OK);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.