sparkSQL基础之-----------2.0以前的sql创建

本文详细介绍了使用Apache Spark创建DataFrame的两种方式:一是通过RDD和case class关联;二是通过创建schema信息。这两种方法都包括了从文件读取数据、数据处理、创建DataFrame、注册临时表及执行SQL查询等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我这里创建的方式就是两种

一,通过RDD和case class的关联来进行创建

1.创建SparkConf和SparkContext


 
  1. val conf=new SparkConf()

  2. .setMaster("local")

  3. .setAppName("old_sparkSql")

  4.  
  5. val sc=new SparkContext(conf)

2.创建RDD

  val lines: RDD[String] = sc.textFile("C:\\Demo_data\\people.txt")

3.在object外部创建case class

case  class people(id:Long,name:String,age:Int,fv:Int)

4.对RDD的数据进行处理并与创建的case class进行关联


 
  1. val personRDD: RDD[people] = lines.map(line => {

  2. val fields: Array[String] = line.split(",")

  3. val id = fields(0).toLong

  4. val name = fields(1)

  5. val age = fields(2).toInt

  6. val fv = fields(3).toInt

  7. people(id, name, age, fv)

  8. })

5.创建SQLContext

    val sqlContext=new SQLContext(sc)

6.导入隐士转换并进行DataFrame的创建(导入隐式转换的目的就是当前类没有所需要的但是它存在与别的类里面,可以导入隐式转换)


 
  1. import sqlContext.implicits._

  2.  
  3. val personDF: DataFrame = personRDD.toDF()

7.将创间的datafram进行临时表的创建

   personDF.registerTempTable("T_person")

8.利用sqlContext进行对临时表的查询


 
  1. val result: DataFrame = sqlContext.sql("SELECT name,age,fv FROM T_person ORDER BY fv desc")

  2.  

9.进行actio操作,并且关闭资源:


 
  1. result.write.json("C:\\people.json")

  2.  
  3. sc.stop()

 

二,通过创建schame信息来创建

1.创建SparkConf和SparkContext


 
  1. val conf=new SparkConf()

  2. .setMaster("local")

  3. .setAppName("old_sparkSql_schame")

  4.  
  5. val sc=new SparkContext(conf)

2.创建RDD

  val lines: RDD[String] = sc.textFile("C:\\Demo_data\\people.txt")

3.对RDD的数据进行处理并且设置RDD的类型为 RDD[Row]


 
  1. val peosonRow: RDD[Row] = lines.map(line => {

  2. val Array12: Array[String] = line.split(",")

  3. val id = Array12(0).toLong

  4. val name = Array12(1)

  5. val age = Array12(2).toInt

  6. val fv = Array12(3).toInt

  7. Row(id, name, age, fv)

  8. })

4.创建SQLContext

    val sqlContext=new SQLContext(sc)

5.创建schame元数据信息类型格式


 
  1. val schame=StructType(

  2. List(

  3. StructField("id",LongType,true) ,

  4. StructField("name",StringType,true),

  5. StructField("age",IntegerType,true),

  6. StructField("fv",IntegerType,true)

  7. )

  8. )

 

6.创建DataFream同时传入两个参数

    val pdf: DataFrame = sqlContext.createDataFrame(peosonRow,schame)

7.创建临时表:

    pdf.registerTempTable("t_people")

8.利用sqlContext进行对临时表的查询


 
  1. val result: DataFrame = sqlContext.sql("SELECT name,age,fv FROM T_person ORDER BY fv desc")

  2.  

9.进行actio操作,并且关闭资源:


 
  1. result.write.json("C:\\people.json")

  2.  
  3. sc.stop()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值