1.Spark SQL基本操作
将下列 json 数据复制到你的 ubuntu 系统/usr/local/spark 下,并保存命名为 employee.json
答案:
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/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
答案:假设当前目录为/usr/local/spark/mycode/rddtodf,在当前目录下新建一个目录 mkdir -p src/main/scala ,然后在目录/usr/local/spark/mycode/rddtodf/src/main/scala 下 新 建 一 个 rddtodf.scala,复制下面代码
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() } }
在目录/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> 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)假设当前目录为/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