1. 程式人生 > >SPark SQL編程初級實踐

SPark SQL編程初級實踐

列數 library spa insert driver 到你 lib 輸出結果 src

今下午在課上沒有將實驗做完,課下進行了補充,最終完成。下面附上廈門大學數據庫實驗室中spark實驗官網提供的標準答案,以供參考。

三、實驗內容和要求

1.Spark SQL 基本操作

將下列 json 數據復制到你的 ubuntu 系統/usr/local/spark 下,並保存命名為 employee.json。 { "id":1 ,"name":" Ella","age":36 } { "id":2,"name":"Bob","age":29 }

{ "id":3 ,"name":"Jack","age":29 }

{ "id":4 ,"name":"Jim","age":28 }

{ "id":5 ,"name":"Damon" }

{ "id":5 ,"name":"Damon" }

首先為 employee.json 創建 DataFrame,並寫出 Scala 語句完成下列操作:創建 DataFrame

答案:

scala> import org.apache.spark.sql.SparkSession scala> val spark=SparkSession.builder().getOrCreate() scala> import spark.implicits._

scala> val df = spark.read.json("file:///usr/local/spark/test/employee.json")

(1) 查詢 DataFrame 的所有數據答案:scala> df.show()

(2) 查詢所有數據,並去除重復的數據

答案:scala> df.distinct().show()

(3) 查詢所有數據,打印時去除 id 字段

答案:scala> df.drop("id").show() (4) 篩選age>20的記錄答案:scala> df.filter(df("age") > 30 ).show()

(5) 將數據按 name 分組

答案:scala> df.groupBy("name").count().show()

(6) 將數據按 name 升序排列

答案:scala> df.sort(df("name").asc).show()

(7) 取出前 3 行數據

答案:scala> df.take(3) 或scala> df.head(3) (8) 查詢所有記錄的 name 列,並為其取別名為 username

答案:scala> df.select(df("name").as("username")).show()

(9) 查詢年齡 age 的平均值

答案:scala> df.agg("age"->"avg") (10) 查詢年齡 age 的最小值

答案:scala> df.agg("age"->"min")

2.編程實現將 RDD 轉換為 DataFrame

源文件內容如下(包含 id,name,age),將數據復制保存到 ubuntu 系統/usr/local/spark 下,命名為 employee.txt,實現從 RDD 轉換得到 DataFrame,並按 id:1,name:Ella,age:36 的格式

打印出 DataFrame 的所有數據。請寫出程序代碼。(任選一種方法即可)

1,Ella,36

2,Bob,29

3,Jack,29

答案:

假設當前目錄為/usr/local/spark/mycode/rddtodf,在當前目錄下新建一個目錄 mkdir -p src/main/scala ,然後在目錄 /usr/local/spark/mycode/rddtodf/src/main/scala 下新建一個

rddtodf.scala,復制下面代碼;(下列兩種方式任選其一)

方法一:利用反射來推斷包含特定類型對象的RDD的schema,適用對已知數據結構的RDD 轉換;

import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder import org.apache.spark.sql.Encoder import spark.implicits._ object RDDtoDF {

def main(args: Array[String]) { case class Employee(id:Long,name: String, age: Long) val employeeDF =

spark.sparkContext.textFile("file:///usr/local/spark/employee.txt").map(_.split(",")).map(at tributes => Employee(attributes(0).trim.toInt,attributes(1), attributes(2).trim.toInt)).toDF() employeeDF.createOrReplaceTempView("employee")

val employeeRDD = spark.sql("select id,name,age from employee") employeeRDD.map(t => "id:"+t(0)+","+"name:"+t(1)+","+"age:"+t(2)).show()

}

}

方法二:使用編程接口,構造一個 schema 並將其應用在已知的 RDD 上。

import org.apache.spark.sql.types._import org.apache.spark.sql.Encoder import org.apache.spark.sql.Row object RDDtoDF {

def main(args: Array[String]) {

val employeeRDD =

spark.sparkContext.textFile("file:///usr/local/spark/employee.txt") val schemaString = "id name age"

val fields = schemaString.split(" ").map(fieldName => StructField(fieldName,

StringType, nullable = true)) val schema = StructType(fields)

val rowRDD = employeeRDD.map(_.split(",")).map(attributes =>

Row(attributes(0).trim, attributes(1), attributes(2).trim)) val employeeDF = spark.createDataFrame(rowRDD, schema) employeeDF.createOrReplaceTempView("employee") val results = spark.sql("SELECT id,name,age FROM employee") results.map(t => "id:"+t(0)+","+"name:"+t(1)+","+"age:"+t(2)).show()

}

}

在目錄/usr/local/spark/mycode/rddtodf 目錄下新建 simple.sbt,復制下面代碼:

name := "Simple Project"

version := "1.0" scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" % "spark-core" % "2.1.0"

在目錄/usr/local/spark/mycode/rddtodf 下執行下面命令打包程序

/usr/local/sbt/sbt package

最後在目錄/usr/local/spark/mycode/rddtodf 下執行下面命令提交程序

/usr/local/spark/bin/spark-submit --class " RDDtoDF

/usr/local/spark/mycode/rddtodf/target/scala-2.11/simple-project_2.11-1.0.jar

"

在終端即可看到輸出結果。

3. 編程實現利用 DataFrame 讀寫 MySQL 的數據

(1) 在 MySQL 數據庫中新建數據庫 sparktest,再建表 employee,包含下列兩行數據;表 1 employee 表原有數據

id

name

gender

age

1

Alice

F

22

2

John

M

25

答案:

mysql> create database sparktest; mysql> use sparktest;

mysql> create table employee (id int(4), name char(20), gender char(4), age int(4)); mysql> insert into employee values(1,‘Alice‘,‘F‘,22); mysql> insert into employee values(2,‘John‘,‘M‘,25);

(2) 配置 Spark通過 JDBC 連接數據庫MySQL,編程實現利用 DataFrame 插入下列數據到 MySQL,最後打印出 age 的最大值和 age 的總和。表 2 employee 表新增數據

id

name

gender

age

3

Mary

F

26

4

Tom

M

23

答案:假設當前目錄為/usr/local/spark/mycode/testmysql,在當前目錄下新建一個目錄 mkdir -p src/main/scala ,然後在目錄 /usr/local/spark/mycode/testmysql/src/main/scala 下新建一個 testmysql.scala,復制下面代碼;

import java.util.Properties import org.apache.spark.sql.types._ import org.apache.spark.sql.Row object TestMySQL {

def main(args: Array[String]) { val employeeRDD = spark.sparkContext.parallelize(Array("3 Mary F 26","4 Tom M

23")).map(_.split(" "))

val schema = StructType(List(StructField("id", IntegerType, true),StructField("name", StringType, true),StructField("gender", StringType, true),StructField("age", IntegerType, true)))

val rowRDD = employeeRDD.map(p => Row(p(0).toInt,p(1).trim,

p(2).trim,p(3).toInt)) val employeeDF = spark.createDataFrame(rowRDD, schema) val prop = new Properties() prop.put("user", "root") prop.put("password", "hadoop") prop.put("driver","com.mysql.jdbc.Driver")

employeeDF.write.mode("append").jdbc("jdbc:mysql://localhost:3306/sparktest",

sparktest.employee", prop) val jdbcDF = spark.read.format("jdbc").option("url",

"jdbc:mysql://localhost:3306/sparktest").option("driver","com.mysql.jdbc.Driver").optio n("dbtable","employee").option("user","root").option("password", "hadoop").load() jdbcDF.agg("age" -> "max", "age" -> "sum")

}

}

在目錄/usr/local/spark/mycode/testmysql 目錄下新建 simple.sbt,復制下面代碼:

name := "Simple Project" version := "1.0" scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" % "spark-core" % "2.1.0"

在目錄/usr/local/spark/mycode/testmysql 下執行下面命令打包程序

/usr/local/sbt/sbt package

最後在目錄/usr/local/spark/mycode/testmysql 下執行下面命令提交程序

/usr/local/spark/bin/spark-submit --class " TestMySQL

/usr/local/spark/mycode/testmysql/target/scala-2.11/simple-project_2.11-1.0.jar

"

在終端即可看到輸出結果。

SPark SQL編程初級實踐