编程实现将 RDD 转换为 DataFrame
将数据复制保存到 ubuntu 系统/usr/local/spark 下,命名为 employee.txt,实现从 RDD 转换得到 DataFrame,并按 id:1,name:Ella,age:36 的格式,打印出 DataFrame 的所有数据。请写出程序代码。(任选一种方法即可),目录为/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
在终端即可看到输出结果。