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

时间:2018-07-12 14:02:36

标签: azure azure-cosmosdb

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

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

在使用'Document Db Data migration tool'时会正确创建所有文档,但是保存序列化数据的文档属性 包含价值

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

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

1 个答案:

答案 0 :(得分:0)

由于您正在使用迁移工具导入数据,因此您无法使用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

希望它对您有帮助。

相关问题