将 JSON 数据行旋转到列中

Pivoting JSON Data Rows into Column

我需要关注方面的帮助。 我有这样的数据

[{
"id": "0001",
"type": "donut",
"name": "Cake",
"topping":
    [
        { "id": "5003", "type": "Chocolate" },
        { "id": "5004", "type": "Maple" }
    ]
}]

我想把这个转换成下面的

参数将是动态的或多重的,而不仅仅是巧克力和枫木)

我想创建一个流分析查询来处理这些数据并将其存储到目标 table 中,目标 table 中已有这些列,例如 Id、名称、类型、巧克力、枫树...... 请帮助我。

您可以从 ASA 中的 udf 获得帮助。

UDF代码:

function main(arg) {
    var array = arg.topping;
    var map = {};
    map["id"] = arg.id;
    map["type"] = arg.type;
    map["name"] = arg.name;
    for(var i=0;i<array.length;i++){        
        var key=array[i].type;        
        map[key] = array[i].id;      
    }
    return map;  
}

SQL:

WITH 
c AS
(
    SELECT 
    udf.processArray(jsoninput) as result
    from jsoninput
)

select c.result
INTO
    jaycosmos
from c

示例数据:

[{
"id": "0001",
"type": "donut",
"name": "Cake",
"topping":
    [
        { "id": "5003", "type": "Chocolate" },
        { "id": "5004", "type": "Maple" }
    ]
},
{
"id": "0002",
"type": "donut2",
"name": "Cake2",
"topping":
    [
        { "id": "5005", "type": "Chocolate" }
    ]
}
]

输出:

基于 Jay 的回答,您可以使用以下 udf 代码更高效地执行相同的操作:

function main(arg) {
    return arg.map(x => (
        x.topping.reduce((acc, cur) => {
            acc[cur.type] = cur.id; // dynamically add items from topping array
            return acc;
        }, { id: x.id, type: x.type, name: x.name }) // initialise with static items
    )); 
}

不幸的是,在撰写本文时,CosmosDb 不支持 ECMAScript2018,因此您不能在对象上使用扩展运算符 ...,否则您可以使用以下一行:

function main(arg) {
    return arg.map(x => (
        x.topping.reduce(
            (acc, cur) => ({ ...acc, [cur.type]: cur.id }), 
            { id: x.id, type: x.type, name: x.name }
        )
));
}