代码之家  ›  专栏  ›  技术社区  ›  Connell.O'Donnell

使用数据工厂将嵌套对象从SQL Server复制到Azure Cosmossdb

  •  1
  • Connell.O'Donnell  · 技术社区  · 7 年前

    假设我有以下数据结构:

    public class Account
    {
        public int AccountID { get; set; }
        public string Name { get; set; }
    }
    
    public class Person
    {
        public int PersonID { get; set; }
        public string Name { get; set; }
        public List<Account> Accounts { get; set; }
    }
    

    我想使用数据工厂将我的数据从SQL Server数据库移动到Azure Cosmos数据库。对于每个人,我想创建一个JSON文件,其中包含作为嵌套对象的帐户,如下所示:

    "PersonID": 1,
    "Name": "Jim",
    "Accounts": [{
        "AccountID": 1,
        "PersonID": 1,
        "Name": "Home"
    },
    {
        "AccountID": 2,
        "PersonID": 1,
        "Name": "Work"
    }]
    

    我写了一个存储过程来检索我的数据。为了将帐户包含为嵌套对象,我将SQL查询的结果转换为JSON:

    select (select *
    from Person p join Account Accounts on Accounts.PersonID = p.PersonID
    for json auto) as JsonResult
    

    不幸的是,我的数据被复制到单个字段中,而不是正确的对象结构:

    enter image description here

    有人知道我该怎么做才能解决这个问题吗?

    编辑 这里有一个类似的问题,但我没有找到一个好答案: Is there a way to insert a document with a nested array in Azure Data Factory?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Connell.O'Donnell    7 年前

    对于同一情况下的任何人,我最终编写了一个.NET应用程序来从数据库中读取条目,并使用SQL API导入。

    https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-dotnet

    对于大型导入来说,该方法有点慢,因为它必须序列化每个对象,然后分别导入它们。稍后我发现的一种更快的方法是使用批量执行器库,它允许您批量导入JSON,而不必首先对其进行序列化:

    https://github.com/Azure/azure-cosmosdb-bulkexecutor-dotnet-getting-started

    https://docs.microsoft.com/en-us/azure/cosmos-db/bulk-executor-overview

    编辑

    安装nuget包microsoft.azure.cosmossdb.bulkExecutor后:

    var documentClient = new DocumentClient(new Uri(connectionConfig.Uri), connectionConfig.Key);
    var dataCollection = documentClient.CreateDocumentCollectionQuery(UriFactory.CreateDatabaseUri(database))
        .Where(c => c.Id == collection)
        .AsEnumerable()
        .FirstOrDefault();
    
    var bulkExecutor = new BulkExecutor(documentClient, dataCollection);
    await bulkExecutor.InitializeAsync();
    

    然后导入文档:

    var response = await client.BulkIMportAsync(docunemts);