Spark创建多种数据格式的DataFrame

假如我们要通过RDD[Row]创建一个包含多个列的DataFrame,重点是列的数据类型可能会包含多个,这时候需要有一点技巧。

| uid | user_name | age | income |

|:----|:----------|:----|:-------|

| 1111 | nituchao | 21 | 123.0 |

这个`DataFrame`里包含多个数据类型:

* uid: Long

* user_name: String

* age: Int

* income: Double

我们可以使用下面的方式来构建:

```scala

import org.apache.spark.sql.Row

import org.apache.spark.sql.types.{DoubleType, IntegerType, LongType, StringType, StructField, StructType}

val uidSeq = Seq(1111L)

val nameSeq = Seq("nituchao")

val ageSeq = Seq(21)

val incomeSeq = Seq(123.0)

val rowRDD = spark.sparkContext.parallelize(Seq(Row.fromSeq(uidSeq ++ userNameSeq ++ ageSeq ++ incomeSeq)))

val schema = StructType(Seq(StructField("uid", LongType, nullable = true),

StructField("name", StringType, nullable = true),

StructField("age", IntegerType, nullable = true),

StructField("sex", DoubleType, nullable = true)))

val df = spark.sqlContext.createDataFrame(rowRDD, schema)

df.printSchema()

df.show()

```

输出:

```shell

root

|-- uid: long (nullable = true)

|-- name: string (nullable = true)

|-- age: integer (nullable = true)

|-- sex: double (nullable = true)

+----+---------+---+-----+

| uid|name |age| sex|

+----+---------+---+-----+

|1111| nituchao| 21|123.0|

+----+---------+---+-----+

```

上面的技巧在于,使用`Row.fromSeq()`时,不同类型的数据,要用`Seq()`分别包起来然后`++`拼接后传进去。因为Seq中的元素必须是同类型的,如直接构造成一个Seq则会自动进行类型转换,多种类型数据不能混用。

问题不大,却造成很大困扰。

相关推荐
jstart千语1 小时前
【Redis】分布式锁的实现
数据库·redis·分布式
CONTONUE2 小时前
运行Spark程序-在Idea中(二)
大数据·spark·intellij-idea
计算机人哪有不疯的2 小时前
图文展示HDFS、YARN、MapReduce三者关系
大数据·spark
祈5332 小时前
MapReduce 的工作原理
大数据·mapreduce
Agatha方艺璇2 小时前
MapReduce报错 HADOOP_HOME and hadoop.home.dir are unset.
大数据·hadoop·mapreduce
@十八子德月生3 小时前
8天Python从入门到精通【itheima】-1~5
大数据·开发语言·python·学习
元6333 小时前
Hadoop集群的常用命令
大数据·hadoop
掘金-我是哪吒5 小时前
分布式微服务系统架构第125集:AI大模型
分布式
武汉格发Gofartlic5 小时前
FEKO许可证的安全与合规性
大数据·运维·安全
言小乔.5 小时前
202534 | KafKa简介+应用场景+集群搭建+快速入门
分布式·kafka