SparkSQL使用IDEA快速入門DataFrame與DataSet的完美教程
1、指定列名添加Schema
2、通過StrucType指定Schema
3、編寫樣例類,利用反射機(jī)制推斷Schema
1.1.1指定列名添加Schema//導(dǎo)包import org.apache.spark.rdd.RDDimport org.apache.spark.sql.SparkSession//代碼// 1.創(chuàng)建SparkSession val spark = SparkSession.builder().master('local[*]').appName('sql').getOrCreate()// 2.使用spark 獲取sparkContext 上下文對象 val sc = spark.sparkContext// 3.使用SparkContext 讀取文件并按照空格切分 返回RDD val rowRDD: RDD[(Int, String, Int)] = sc.textFile('./data/person.txt').map(_.split(' ')).map(x=>(x(0).toInt,x(1),x(2).toInt))// 4.導(dǎo)入隱式類 import spark.implicits._//5.將RDD 轉(zhuǎn)換為DataFrame 指定元數(shù)據(jù)信息 val dataFrame = rowRDD.toDF('id','name','age')//6.數(shù)據(jù)展示 dataFrame.show()1.1.2StructType指定Schema
//導(dǎo)包import org.apache.spark.sql.{Row, SparkSession}import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}//編寫代碼//1.實(shí)例SparkSession val spark = SparkSession.builder().master('local[*]').appName('sql').getOrCreate()//2.根據(jù)SparkSession獲取SparkContext 上下文對象 val sc = spark.sparkContext// 3.使用SparkContext讀取文件并按照空開切分并返回元組 val rowRDD = sc.textFile('./data/person.txt').map(_.split(' ')).map(x=>Row(x(0).toInt,x(1),x(2).toInt))// 4.導(dǎo)入隱式類 import spark.implicits._//5.使用StructType 添加元數(shù)據(jù)信息 val schema = StructType(List( StructField('id', IntegerType, true), StructField('name', StringType, true), StructField('age', IntegerType, true) ))//6.將數(shù)據(jù)與元數(shù)據(jù)進(jìn)行拼接 返回一個(gè)DataFrame val dataDF = spark.createDataFrame(rowRDD,schema)//7.數(shù)據(jù)展示 dataDF.show()1.1.3反射推斷Schema
//導(dǎo)包import org.apache.spark.rdd.RDDimport org.apache.spark.sql.SparkSession//定義單例對象 case class Person(Id:Int,name:String,age:Int)//編寫代碼//1.實(shí)例sparkSession val spark = SparkSession.builder().master('local[*]').appName('sql').getOrCreate()//2.通過sparkSession獲取sparkContext 上下文對象 val sc = spark.sparkContext//3.通過sparkContext 讀取文件并按照空格切分 將每一個(gè)數(shù)據(jù)保存到person中 val rowRDD: RDD[Person] = sc.textFile('./data/person.txt').map(_.split(' ')).map(x=>Person(x(0).toInt,x(1),x(2).toInt))// 4.導(dǎo)入隱式類 import spark.implicits._//5.將rowRDD轉(zhuǎn)換為dataFrame val dataFrame = rowRDD.toDF() //6.數(shù)據(jù)展示 dataFrame.show()
到此這篇關(guān)于SparkSQL使用IDEA快速入門DataFrame與DataSet的文章就介紹到這了,更多相關(guān)SparkSQL快速入門內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 使用css實(shí)現(xiàn)全兼容tooltip提示框2. SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導(dǎo)出,在線文件導(dǎo)出)3. 使用ProcessBuilder調(diào)用外部命令,并返回大量結(jié)果4. 通過工廠模式返回Spring Bean方法解析5. JSP實(shí)現(xiàn)客戶信息管理系統(tǒng)6. 關(guān)于Mysql-connector-java驅(qū)動(dòng)版本問題總結(jié)7. python中HTMLParser模塊知識(shí)點(diǎn)總結(jié)8. CSS自定義滾動(dòng)條樣式案例詳解9. python 批量下載bilibili視頻的gui程序10. python:刪除離群值操作(每一行為一類數(shù)據(jù))
