sparkSQL读取数据的方法

本文介绍如何使用SparkSQL读取本地的数据源,包括json和txt文件。在尝试使用testFile方法读取txt文件未果后,作者转向使用createDataFrame方法,通过将RDD转换为DataFrame来实现数据查询。

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

本文中所有数据以本地数据为数据源

1、读取json文件

object ReadJson {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder().appName("testpeople").master("local")
      .getOrCreate()
    import spark.implicits._
    val test = spark.read.json("C:/Users/Administrator/Desktop/课程代码/employee.json")
    test.select("name").show()
    test.show()

  }

}

2、读取txt文件

    spark.read下除了json方法用于读取json文件外,还有读取数据的而其他方式,使用testFile方法时一直不行,不清楚是对txt文件的格式有要求还是后续的方法不对,有朋友知道的劳烦指点下

val testtxt = spark.read.textFile("C:/Users/Administrator/Desktop/课程代码/employee.txt")
testtxt.show()    //成功读取文件数据
testtxt.select("name").show()

     后来改用createDataFrame方法,这种方法不像前面的那个,稍微麻烦点,textFile返回的是个RDD,通过createDataFrame方法将RDD转为DataFrame进行查询

object ReadTxt {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder().appName("testpeople").master("local")
      .getOrCreate()
    // 使用createDataFrame
    val FileRDD = spark.sparkContext.textFile("C:/Users/Administrator/Desktop/课程代码/testT.txt",2)
      .map(x=>x.split(","))
      .map(x=>Row(x(0),x(1).trim.toInt))
    //set schema structure
    val schema = StructType(
      Seq(
        StructField("name",StringType,true)
        ,StructField("age",IntegerType,true)
      )
    )
    val DF = spark.createDataFrame(FileRDD,schema)
    DF.show()
    DF.select("name").show() 
 }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值