c# - Azure 函数 C# : Create or replace document in cosmos db on HTTP request

标签 c# function azure azure-cosmosdb document

我正在尝试用 C# 构建一个 Azure 函数,如果 ID 尚不存在,则使用 SQL API 在 Azure cosmos DB 中创建一个新文档对象,如果文档对象已存在,则更新该对象。

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

输入:
带参数的 HTTP GET 请求(id(字符串)、chatHistory(字符串)和 chatDateTime(字符串))

输出:
如果具有相同 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 Output Binding 。输出绑定(bind)执行更新插入操作。

[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

关于c# - Azure 函数 C# : Create or replace document in cosmos db on HTTP request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52437913/

相关文章:

azure - 为 Azure Bing map 配置编程部署

c# - 如果有人使用外部类库中的某些类,我如何报告编译错误

C# Zlib在winform应用程序中的使用

javascript - JS 多个同名函数

r - 函数语法//泛化函数

sql-server - 带有 Oracle SQL Developer 4.1 的 SQL Server - 无法查看表

c# - 如何在 .NET Core 2.2 WebApi 和 Azure AD 2.0 中配置 Swagger?

C# 代码片段不会自动导入命名空间

c++ - 错误:第6行 '{' token 之前不允许在此处进行功能定义

Azure 表 - 分区键和行键 - 正确选择