使用编程接口来创建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() }}新闻热点
疑难解答