spark rdd 和 DF 转换

RDD   -》 DF

 

有两种方式

一、

 

一、Inferring the Schema Using Reflection

 

将 RDD[t]   转为一个 object ,然后 to df

 

val peopleDF = spark.sparkContext
  .textFile("examples/src/main/resources/people.txt")
  .map(_.split(","))
  .map(attributes => Person(attributes(0), attributes(1).trim.toInt))
  .toDF()

 

 

rdd 也能直接装 DATASet  要  import 隐式装换 类 import spark.implicits._

 如果  转换的对象为  tuple .   转换后  下标为 _1  _2   .....

 

 

 

二、Programmatically Specifying the Schema

 

把 columnt meta  和  rdd   createDataFrame 在一起

 

val peopleRDD = spark.sparkContext.textFile("examples/src/main/resources/people.txt")

// The schema is encoded in a string
val schemaString = "name age"

// Generate the schema based on the string of schema
val fields = schemaString.split(" ")
  .map(fieldName => StructField(fieldName, StringType, nullable = true))
val schema = StructType(fields)

 

val rowRDD = peopleRDD
  .map(_.split(","))
  .map(attributes => Row(attributes(0), attributes(1).trim))

// Apply the schema to the RDD
val peopleDF = spark.createDataFrame(rowRDD, schema)

// Creates a temporary view using the DataFrame
peopleDF.createOrReplaceTempView("people")

 

 

 

 

 

 

DF  to  RDd

 

val tt = teenagersDF.rdd

 

 

 

 rdd to  ds  会有  rdd[object] 没有TODS 的异常

 

保险搞法

val schema = new StructType()
  .add(StructField("client_date", StringType, true))
  .add(StructField("client_time", StringType, true))
  .add(StructField("server_date", StringType, true))
  .add(StructField("server_time", StringType, true))

。。。。。。

 

 val schema = new StructType()

  .add(StructField("client_date", StringType, true))
  .add(StructField("client_time", StringType, true))
  .add(StructField("server_date", StringType, true))
  .add(StructField("server_time", StringType, true))

 。。。。。。

 

然后 

 

import spark.implicits._
var cubesDF = spark.createDataFrame(cubesRDD, schema)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值