Spark RDD转DataFrame
import org.apache.spark.sql.{Row, SparkSession} import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType} /** * RDD转DataFrame */ object DataFrameRDD { def main(args: Array[String]): Unit = { val spark = SparkSession.builder() .appName("") .master("local") .getOrCreate() val rdd = spark.sparkContext.textFile("person.text") /** * 1.RDD转DataFrame * 导入包,支持把一个RDD隐式转换为DataFrame, * 这里的spark不是某个包下的东西,而是上面声明的变量 */ import spark.implicits._ val df = rdd.map(_.split(",")).map(attributes=>Person(attributes(0),attributes(1).trim.toInt)).toDF() //注册表 df.createOrReplaceTempView("person") val frame = spark.sql("select * from person where age > 20") df.map(t=> "name:"+t(0) + "," + "age:"+t(1) ).show() /** * 2.RDD转DataFrame */ //构建表头 val fields = Array(StructField("name",StringType,true),StructField("age",IntegerType,true)) val schema = StructType(fields) //表中的记录 val rowRdd = rdd.map(_.split(",")).map(attributes=> Row(attributes(0),attributes(1).trim.toInt)) //把表头和表中的记录拼接起来 val dataframe = spark.createDataFrame(rowRdd,schema) //注册表 dataframe.createOrReplaceTempView("person") val dataframe2 = spark.sql("select * from person where age > 20") dataframe2.map(t=> "name:"+t(0) + "," + "age:"+t(1) ).show() } }
相关推荐
Johnson0 2020-07-28
Oeljeklaus 2020-05-29
登峰小蚁 2020-05-11
Hhanwen 2020-05-04
Oeljeklaus 2020-04-19
81510295 2020-11-17
roamer 2020-10-29
listep 2020-09-11
Tristahong 2020-08-24
三石 2020-08-23
QianYanDai 2020-08-16
mmmjyjy 2020-07-16
santiago00 2020-07-11
QianYanDai 2020-07-05
QianYanDai 2020-07-05
jiahaohappy 2020-06-21
QianYanDai 2020-06-16
zhangxiaojiakele 2020-05-25
人家 2020-05-17