0

我需要在 Azure Synapse Analytics 的 Spark Notebook 中展平一个简单的 Json 文件(json 行)并将其转换为 Parquet 格式。任何列都只有一层嵌套对象。但是,我发现获取数据框的架构并没有返回嵌套对象的架构。我使用的是 c#,以便其他公司开发人员不必学习其他支持的语言。

4

1 回答 1

0

下面的代码适用于上述情况。希望它可以节省其他人几个小时。在将子项的属性添加到父数据框中后,它还会从数据框中删除父列。

因为我们没有嵌套对象,所以我不需要将这段代码变成递归的横向。

using System;
using System.Collections.Generic;
using Microsoft.Spark.Sql;
using Microsoft.Spark.Sql.Types;
using System.Diagnostics;


var df = spark.Read().Json("{Your source file path here}");

//get the schema of the data frame
var dfSchema = df.Schema() ;
// traverse the schema of the dataframe
foreach(var parentSchemaField in dfSchema.Fields) {
    
    if (parentSchemaField.DataType is StructType) {
        // get a new dataframe that just contains the child data from the parent
        var childFrame = df.Select($"{parentSchemaField.Name}.*") ;
        // traverse the schema of the child dataframe
        foreach(var childSchemaField in childFrame.Schema().Fields) {   
            //make a new column in the parent dataframe for each parents child property
            df = df.WithColumn($"{parentSchemaField.Name}.{childSchemaField.Name}",Col($"{parentSchemaField.Name}.{childSchemaField.Name}")) ;
        }
        // drop the parent column from the data frame its no longer needed
        df = df.Drop(parentSchemaField.Name) ;
    }
}
df.Write().Parquet("{Your sink file path here}") ;
于 2022-02-11T18:10:43.283 回答