SparkSql学习笔记(包含IDEA编写的本地代码)

  Spark SQL and DataFrame

1.为什么要用Spark Sql

原来我们使用Hive,是将Hive Sql 转换成Map Reduce 然后提交到集群上去执行,大大简化了编写MapReduce的程序的复杂性,由于MapReduce这种计算模型执行效率比较慢,所以Spark Sql的应运而生,它是将SparkSql转换成RDD,然后提交到集群执行,执行效率非常的快。

Spark Sql的有点:1、易整合  2、统一的数据访问方式 3、兼容Hvie 4、标准的数据连接

 

2、DataFrames

什么是DataFrames?

与RDD类似,DataFrames也是一个分布式数据容器,然而DataFrame更像是传统数据库的二维表格,除了数据以外,还记录数据的结构信息,即schema。同时,与Hive类似,DataFrame与支持嵌套数据类型(struct、array和map)。从API的易用性上看,DataFrame API提供的是一套高层的关系操作,比函数式的RDD API要更加友好,门槛更低。由于与R和Pandas的DataFrame类似,Spark DataFrame很好地继承了传统单机数据分析的开发体验。

 

 

创建DataFrames

在Spark SQL中SQLContext是创建DataFrames和执行SQL的入口,在spark-1。5.2中已经内置了一个sqlContext。

1.在本地创建一个文件,有三列,分别是id、name、age,用空格分隔,然后上传到hdfs上

hdfs dfs -put person.txt /

 

2.在spark shell执行下面命令,读取数据,将每一行的数据使用列分隔符分割

val lineRDD = sc.textFile("hdfs://hadoop01:9000/person.txt").map(_.split(" "))

 

3.定义case class(相当于表的schema)

case class Person(id:Int, name:String, age:Int)

 

4.将RDD和case class关联

val personRDD = lineRDD.map(x => Person(x(0).toInt, x(1), x(2).toInt))

 

5.将RDD转换成DataFrame

val personDF = personRDD.toDF

 

6.对DataFrame进行处理

personDF.show

代码:

object SparkSqlTest {

  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setMaster("local").setAppName("SQL-1")
    val sc = new SparkContext(conf)
    fun1(sc)
  }
  //定义case class 相当于表的schema
  case class Person(id:Int,name:String,age:Int)

  def fun1(sc:SparkContext): Unit ={
    val sqlContext = new SQLContext(sc)
  // 位置一般情况下是换成HDFS文件路径 val lineRdd
= sc.textFile("D:\\data\\person.txt").map(_.split(" ")) val personRdd = lineRdd.map(x=>Person(x(0).toInt,x(1),x(2).toInt)) import sqlContext.implicits._ val personDF = personRdd.toDF //注册表 personDF.registerTempTable("person_df") //传入sql val df = sqlContext.sql("select * from person_df order by age desc") //将结果以JSON的方式存储到指定位置 df.write.json("D:\\data\\personOut") sc.stop() }

 

DataFrame 常用操作

DSL风格语法(个人理解短小精悍的含义

 

     // 查看DataFrame部分列中的内容
    df.select(personDF.col("name")).show()
    df.select(col = "age").show()
    df.select("id").show()

    // 打印DataFrame的Schema信息
    df.printSchema()

    //查询所有的name 和 age ,并将 age+2
    df.select(df("id"),df("name"),df("age")+2).show()

    //查询所有年龄大于20的
    df.filter(df("age")>20).show()

    // 按年龄分组并统计相同年龄人数
    df.groupBy("age").count().show()

SQL风格语法(前提:需要将DataFrame注册成表)

//注册成表
 personDF.registerTempTable("person_df")

// 查询年龄最大的两位 并用对象接接收
    val persons = sqlContext.sql("select * from person_df order by age desc limit 2")
    persons.foreach(x=>print(x(0),x(1),x(2)))

 

通过StructType直接指定Schema

 1  /*通过StructType直接指定Schema*/
 2   def fun2(sc: SparkContext): Unit = {
 3     val sqlContext = new SQLContext(sc)
 4     val personRDD = sc.textFile("D:\\data\\person.txt").map(_.split(" "))
 5     // 通过StructType直接指定每个字段的Schema
 6     val schema = StructType(List(StructField("id", IntegerType, true), StructField("name", StringType, true), StructField("age", IntegerType)))
 7     //将rdd映射到RowRDD
 8     val rowRdd = personRDD.map(x=>Row(x(0).toInt,x(1).trim,x(2).toInt))
 9     //将schema信息应用到rowRdd上
10     val dataFrame = sqlContext.createDataFrame(rowRdd,schema)
11     //注册
12     dataFrame.registerTempTable("person_struct")
13 
14     sqlContext.sql("select * from person_struct").show()
15 
16     sc.stop()
17 
18   }

 

连接数据源

 

1 /*连接mysql数据源*/
2   def fun3(sc:SparkContext): Unit ={
3     val sqlContext = new SQLContext(sc)
4     val jdbcDF = sqlContext.read.format("jdbc").options(Map("url"->"jdbc:mysql://192.168.180.100:3306/bigdata","driver"->"com.mysql.jdbc.Driver","dbtable"->"person","user"->"root","password"->"123456")).load()
5     jdbcDF.show()
6     sc.stop()
7   }

 

 

 

 再回写到数据库中

 

 1  // 写入数据库
 2     val personTextRdd = sc.textFile("D:\\data\\person.txt").map(_.split(" ")).map(x=>Row(x(0).toInt,x(1),x(2).toInt))
 3 
 4     val schema = StructType(List(StructField("id", IntegerType), StructField("name", StringType), StructField("age", IntegerType)))
 5 
 6     val personDataFrame = sqlContext.createDataFrame(personTextRdd,schema)
 7 
 8     val prop = new Properties()
 9     prop.put("user","root")
10     prop.put("password","123456")
11     //写入数据库
12     personDataFrame.write.mode("append").jdbc("jdbc:mysql://192.168.180.100:3306/bigdata","bigdata.person",prop)
13 
14     sc.stop()

 

posted @ 2018-08-22 16:28  喜中5000万  阅读(1498)  评论(0编辑  收藏  举报