首页 文章

如何使用Cosmos DB数据迁移工具导入包含数组的文档

提问于
浏览
2

我正在尝试从SQL Server数据库导入文档 . 每个文档都有一个客户购买的产品列表,例如:

{
        "name": "John Smith"
        "products": [
             {
                 "name": "Pencil Sharpener"
                 "description": "Something, this and that."
             },
             { 
                 "name": "Pencil case"
                 "description": "A case for pencils."
             }
        ]
    }

在SQL Server数据库中,客户和产品存储在单独的表中,客户和产品之间具有一对多关系:

Customer

Id INT
Name VARCHAR

Product

Id INT
CustomerId INT (FK)
Name VARCHAR
Description VARCHAR

我已经检查了documentation,但是看不到有关如何编写SQL查询以将一对多关系映射到单个文档的任何提及 .

我认为可能有一种方法可以像 Target Information 步骤那样(当选择 DocumentDB - Bulk import (single partition collections) 时)可以选择提供bulk insert stored procedure . 也许这些产品可以分配到文档's products array from within there. I'我只是不确定如何去做,因为我是Cosmos DB的新手 .

我希望这很清楚,并提前感谢您的帮助!

1 回答

  • 3

    当你import data from SQL Server using the Azure Cosmos DB: DocumentDB API Data Migration tool时,似乎你想要返回格式为json的产品信息 . 根据你的 customerproducts 表结构和你的要求,我做了以下测试,这对我来说很好 . 你可以参考它 .

    Import data from SQL Server to JSON file

    enter image description here

    enter image description here

    Query

    select distinct c.Name, (SELECT p.Name as [name], p.[Description] as [description] from [dbo].[Product] p where c.Id = p.CustomerId for JSON path) as products 
    from [dbo].[Customer] c
    

    JSON output

    [
      {
        "Name": "Jack",
        "products": null
      },
      {
        "Name": "John Smith",
        "products": "[{\"name\":\"Pencil Sharpener\",\"description\":\"Something, this and that\"},{\"name\":\"Pencil case\",\"description\":\"A case for pencils.\"}]"
      }
    ]
    

    Parsing the products

    在'Target Information'步骤中,您需要使用自己的BulkTransformationInsert.js版本 . 第32行是'transformDocument'函数,您可以在其中编辑文档 . 以下将解析产品,然后在返回之前将它们分配回文档;

    function transformDocument(doc) {
        if (doc["products"]) {
            let products = doc["products"];
            let productsArr = JSON.parse(products);
            doc["products"] = productsArr;
        }
    
        return doc;
    }
    

相关问题