Spark之DataFrame与RDD之间的两种转换方式

说明:在SparkSQL中读外部数据进行读取进行ETL操作时,首先读取的数据格式为RDD数据结构,因此我们一项主要目标就是将读取到的RDD格式转化为DataFrame。

RDD结构转化为DataFrame的形式主要分为两种:①反射②编程Row(StructType)

package LogsAnalyse

import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}

/***
  * 反射:case class  前提:事先需要知道你的字段、字段类型
  * 编程Row    如果第一种情况不能满足你的要求(事先不知道列)
  * 选型:优先考虑第一种
  */
object DataFrameRDDApp {
  /**
    * Row编程创建StructType将RDD转换为DataFrame
    * @param args
    */
  def main(args: Array[String]): Unit = {
    def program(spark:SparkSession): Unit ={
      val rdd = spark.sparkContext.textFile("D:\\Data\\students.txt")
      println()
      val infoRDD=rdd.map(_.split(",")).map(line => Row(line(0).toInt,line(1),line(2).toInt))
      val structType = StructType(Array(StructField("id",IntegerType,true),
        StructField("name",StringType,true),
        StructField("id",IntegerType,true)))
      val infoDF = spark.createDataFrame(infoRDD,structType)
      infoDF.printSchema()
      infoDF.show()

    }

    /**
      * 反射
      * @param spark
      */
    def Reflection(spark:SparkSession): Unit ={
      val spark = SparkSession.builder().appName("DataFrameRDDApp").master("local[2]").getOrCreate()
      val rdd = spark.sparkContext.textFile("D:\\Data\\students.txt")
      import spark.implicits._
      val infoDF = rdd.map(_.split(",")).map(line => Info(line(0).toInt,line(1),line(2).toInt)).toDF()
      infoDF.show()
      infoDF.filter(infoDF.col("age")>18).show()
      //创建零时视图或者表使用SQL方式对DataFrame完成操作
      infoDF.createOrReplaceTempView("infos")
      spark.sql("select * from infos where age > 18").show()
      spark.close()
    }
  }
  case class Info(id:Int,name:String,age:Int)
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值