更新时间:2023-11-18 23:05:16
下面是一个替代的解决方案
在那里我有转换的数据帧到RDD的转换和转换回用数据帧 sqlContext.createDataFrame()
Here is an alternate solution
Where I have converted the dataframe to an rdd for the transformations and converted it back a dataFrame using sqlContext.createDataFrame()
Sample.json
Sample.json
{"employee":"Michale","Address":"NY"}
{"employee":"Michale","Address":"NJ"}
{"employee":"Sam","Address":"NY"}
{"employee":"Max","Address":"NJ"}
星火应用
val df = sqlContext.read.json("sample.json")
// Printing the original Df
df.show()
//Defining the Schema for the aggregated DataFrame
val dataSchema = new StructType(
Array(
StructField("employee", StringType, nullable = true),
StructField("Address", ArrayType(StringType, containsNull = true), nullable = true)
)
)
// Converting the df to rdd and performing the groupBy operation
val aggregatedRdd: RDD[Row] = df.rdd.groupBy(r =>
r.getAs[String]("employee")
).map(row =>
// Mapping the Grouped Values to a new Row Object
Row(row._1, row._2.map(_.getAs[String]("Address")).toArray)
)
// Creating a DataFrame from the aggregatedRdd with the defined Schema (dataSchema)
val aggregatedDf = sqlContext.createDataFrame(aggregatedRdd, dataSchema)
// Printing the aggregated Df
aggregatedDf.show()
输出:
+-------+--------+---+
|Address|employee|num|
+-------+--------+---+
| NY| Michale| 1|
| NJ| Michale| 2|
| NY| Sam| 3|
| NJ| Max| 4|
+-------+--------+---+
+--------+--------+
|employee| Address|
+--------+--------+
| Sam| [NY]|
| Michale|[NY, NJ]|
| Max| [NJ]|
+--------+--------+