azure - 如何将序列化数据从 SQL 数据库传输到 cosmos Db

标签 azure azure-cosmosdb

我在将 SQL 表数据传输到 Cosmos DB 时遇到问题。 我的 SQL 表包含一列,其中包含序列化数据,例如

'[{"Id":"1","Name":"AA","Address":"HQ - 主线"}]'

使用“Document Db 数据迁移工具”时,它会正确创建所有文档,但保存序列化数据的文档属性除外 其中包含值(value)

"info": "[{\"Id\":\"1\",\"Name\":\"AA\",\"Address\":\"HQ - Main Line\"}]"

数据迁移工具为"添加了额外的反斜杠,但我想要与 SQL 表相同

最佳答案

由于您使用迁移工具导入数据,因此无法使用 PreTrigger更改创建的文档的格式。 PreTrigger需要通过代码或者rest api调用。

我建议您使用 Azure Function Cosmos DB 触发器。请引用我的代码:

using System;
using System.Collections.Generic;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json.Linq;

namespace ProcessJson
{
    public class Class1
    {
        [FunctionName("DocumentUpdates")]
        public static void Run(
        [CosmosDBTrigger(databaseName:"db",collectionName: "item", ConnectionStringSetting = "CosmosDBConnection",LeaseCollectionName = "leases",
            CreateLeaseCollectionIfNotExists = true)]
        IReadOnlyList<Document> documents,
        TraceWriter log)
        {
            log.Verbose("Start.........");
            String endpointUrl = "https://***.documents.azure.com:443/";
            String authorizationKey = "***";
            String databaseId = "db";
            String collectionId = "import";

            DocumentClient client = new DocumentClient(new Uri(endpointUrl), authorizationKey);

            for (int i = 0; i < documents.Count; i++)
            {
                Document doc = documents[i];
                String info = doc.GetPropertyValue<String>("info");
                JArray o = JArray.Parse(info);

                doc.SetPropertyValue("info", o);

                client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, doc.Id), doc);

                log.Verbose("Update document Id " + doc.Id);
            }
        }
    }
}

结果:

enter image description here

希望对您有帮助。

关于azure - 如何将序列化数据从 SQL 数据库传输到 cosmos Db,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51307678/

相关文章:

c# - 读取可能不存在的 Azure DocumentDB 文档

azure-cosmosdb - documentdb 创建请求消息时出错

azure - 当 HasMoreResults 为 True 时,为什么 CosmosDB FeedResponse 不包含结果

azure - 从 cosmosDB 文档的嵌套数组中删除数据

.net - nginx 入口 Controller 日志 499

c# - DocumentDB 替换文档失败

mysql - 从 azure webapp 从另一台服务器访问数据库

azure - 通过 Azure CLI 在资源创建阶段设置标签

azure - 是否可以在使用逻辑应用插入 SQL 表期间触发?

python - 使用托管身份将 Function App 连接到 CosmosDB