使用編程接口來創建DataFrame. 注意的問題:需要記住一個這樣的結構~
package sparksqldemoimport org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}import org.apache.spark.sql.{Row, SQLContext}import org.apache.spark.{SparkConf, SparkContext}/** * Created by Youxiangyang on 2017/2/16. * DataFrame * 最核心的編程抽象.可以理解為是以列的形式存儲的,分布式的數據集合. * 和關系型數據庫很類似. * 可以通過多種數據源來構造.如結構化的數據文件,數據庫中的表.hive的表,RDD等 */object Demo01 { def main(args: Array[String]): Unit = { val conf=new SparkConf().setAppName("HiveDemo").setMaster("local") val sc=new SparkContext(conf) val sqlContext=new SQLContext(sc) //設置conf,配置AppName,運行的Master(這里設置為本地模式 //創建一個sc的SQLContext對象 //創建一個sqlcontext對象(也可以是SQLContext的子類對象,如 HiveContext) //加載數據源 val datas=sc.textFile("hdfs://hadoop01:9000/datas/people") //RDD轉換為DataFrame有兩種方式:(這里使用了第二種) //使用反射方式推斷元數據 //使用編程接口來創建DataFrame. val rowRDD=datas.map(line=>{ val stu=line.split("/t") Row(stu(0).toInt,stu(1),stu(2)) //創建出元素為ROW的RDD }) //流程簡介:從原始的RDD創建一個元素為row的RDD;接下來創建一個structType,來代表ROW,最后將動態定義的 //元數據應用到RDD(ROW)上 val structType=StructType(Array( //通過編程的方式動態的構造元數據 StructField("id",IntegerType,true), StructField("name",StringType,true), StructField("sex",StringType,true) )) //通過sqlContext的createDataFrame方法,創建DataFrame, // 將row類型的RDD和數據結構structType結合到一起 val stuDF=sqlContext.createDataFrame(rowRDD,structType) stuDF.show() //show方法可以把里面的數據顯示出來 stuDF.registerTempTable("stu") //注冊為臨時表,這樣就可以使用SQL語句了. sqlContext.sql("select name form stu where sex='m'").show() }}新聞熱點
疑難解答