Spark创建具有相同键的数组

时间:2017-01-06 10:17:00

标签: scala hadoop apache-spark spark-hive

我有一个hive表,它存在于spark上下文之上。表的格式如下

| key | param1 | Param 2|
-------------------------
| A   |  A11   | A12    |
| B   |  B11   | B12    |
| A   |  A21   | A22    |

我想用架构

创建一个DataFrame
val dataSchema = new StructType(
    Array(
    StructField("key", StringType, nullable = true),
    StructField("param", ArrayType(
        StructType( Array(
            StructField("param1", StringType, nullable = true),
            StructField("param2", StringType, nullable = true)
        )), containsNull = true), nullable = true)
    )
)

来自上表

这样最终的表变成了

| key | param                                               |
-------------------------------------------------------------
| A   |  [{param1:A11, param2:A12},{param1:A11, param2:A12}]|
| B   |  [{param1:B11, param2:B12}]                         |

我使用hive上下文(hiveContext.table(" table_name"))加载表,它返回数据框。

scala> val df = hiveContext.table("sample")
df: org.apache.spark.sql.DataFrame = [fk: string, param1: string, param2: string]
scala> val dfStruct = df.select($"key", struct($"param1", $"param2").alias("param"))
dfStruct: org.apache.spark.sql.DataFrame = [fk: string, sub: struct<param1:string,param2:string>]
scala> dfStruct.show
+--+----------+
|fk|     param|
+--+----------+
| A| [A11,A12]|
| B| [B11,B12]|
| A| [A21,A22]|
+--+----------+
scala> 

我正在尝试使用groupBy将数据帧转换为上述表格。但是没能做到。

1 个答案:

答案 0 :(得分:0)

我找到了自己。

密钥是使用case class而不是structType

case class Param(param1: String, param2:String)
case class Sample(key: String, param:Array[Param])

val df = hiveContext.table("sample_sub")

val SampleDF = df.select($"fk", $"param1", $"param2")
val SampleDFMap = SampleDF.rdd.groupBy(r => r.getAs[String]("fk"))
val SampleJoinRDD =  SampleDFMap.map(
    r => Sample(r._1.asInstanceOf[String], r._2.map (
        row => Param(row(1).asInstanceOf[String],row(2).asInstanceOf[String])
        ).toArray
    )
)

SampleJoinRDD.toDF.toJSON.collect
// Array({"key":"A","param":[{"param1":"A11","param2":"A12"},{"param1":"A21","param2":"A22"}]}, {"key":"B","param":[{"param1":"B11","param2":"B12"}]})