【问题标题】:Copy nested objects from SQL Server to Azure CosmosDB using a Data Factory使用数据工厂将嵌套对象从 SQL Server 复制到 Azure CosmosDB
【发布时间】:2019-01-15 14:52:39
【问题描述】:

假设我有以下数据结构:

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 DB。对于每个人,我想创建一个包含帐户作为嵌套对象的 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

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

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

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

【问题讨论】:

    标签: json sql-server azure-cosmosdb azure-data-factory


    【解决方案1】:

    对于处于相同情况的任何人,我最终编写了一个 .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.CosmosDB.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);
    

    【讨论】:

      猜你喜欢
      • 2020-12-22
      • 2021-10-13
      • 2022-08-18
      • 1970-01-01
      • 2018-09-20
      • 2023-04-11
      • 1970-01-01
      • 2021-08-26
      • 2022-06-22
      相关资源
      最近更新 更多