在本地文件夹中创建一个文件people.txt 作为样例数据,其内容:
Bob, 25
Jack, 22
Tom, 31
现在把people.txt加载到内存中生成一个DataFrame,并查询其中数据。
1.利用反射机制推断RDD模式
在利用反射机制推断RDD模式时,需要首先定义一个case class, 因为只有case class 才能被Spark 隐式地转换为DataFrame
case class Person(name:String, age:Long)
这句话一定要写在object外面*
添加隐式转换:import spark.implicits._
创建DataFrame
val peopleDF = spark.sparkContext.textFile("E:/pictures_test/people.txt")
.map(_.split(","))
.map(attributes => Person(attributes(0), attributes(1).trim.toInt))
.toDF()
peopleDF 必须注册为临时表,才能供查询使用
peopleDF.createOrReplaceTempView("people")
添加查询的SQL语句
val personsRDD = spark.sql("select name, age from people where age > 20")
输出查询结果
personsRDD.map(t &#