Azure 函数 C#:根据 HTTP 请求在 cosmos db 中创建或替换文档

Azure function C#: Create or replace document in cosmos db on HTTP request

我正在尝试在 C# 中构建一个 Azure 函数,它使用 SQL API 在 Azure cosmos DB 中创建一个新的文档对象(如果 id 尚不存在)并更新文档对象如果它已经存在。

这背后的背景是将聊天机器人对话历史记录到唯一的用户会话中。

输入:
带有参数(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
}

这是一个如何操作的例子。您只需要根据需要进行调整即可。

    [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);
    }

您可以使用 Azure Functions 的 Cosmos DB Output Binding。输出绑定执行 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