Spark SQL支持两种RDDs转换为DataFrames的方式
使用反射获取RDD内的Schema
    当已知类的Schema的时候,使用这种基于反射的方法会让代码更加简洁而且效果也很好。
通过编程接口指定Schema
    通过Spark SQL的接口创建RDD的Schema,这种方式会让代码比较冗长。
    这种方法的好处是,在运行时才知道数据的列以及列的类型的情况下,可以动态生成Schema。
使用反射获取Schema(Inferring the Schema Using Reflection)
import org.apache.spark.sql.{DataFrameReader, SQLContext}
import org.apache.spark.{SparkConf, SparkContext} object InferringSchema {
def main(args: Array[String]) { //创建SparkConf()并设置App名称
val conf = new SparkConf().setAppName("SQL-intsmaze") //SQLContext要依赖SparkContext
val sc = new SparkContext(conf)
//创建SQLContext
val sqlContext = new SQLContext(sc) //从指定的地址创建RDD
val lineRDD = sc.textFile("hdfs://192.168.19.131:9000/person.tzt").map(_.split(",")) //创建case class
//将RDD和case class关联
val personRDD = lineRDD.map(x => Person(x().toInt, x(), x().toInt)) //导入隐式转换,如果不导入无法将RDD转换成DataFrame
//将RDD转换成DataFrame
import sqlContext.implicits._
val personDF = personRDD.toDF //注册表
personDF.registerTempTable("intsmaze")
//传入SQL
val df = sqlContext.sql("select * from intsmaze order by age desc limit 2") //将结果以JSON的方式存储到指定位置
df.write.json("hdfs://192.168.19.131:9000/personresult") //停止Spark Context
sc.stop()
}
}
//case class一定要放到外面
case class Person(id: Int, name: String, age: Int)

spark shell中不需要导入sqlContext.implicits._是因为spark shell默认已经自动导入了。

打包提交到yarn集群:

/home/hadoop/app/spark/bin/spark-submit --class InferringSchema \
--master yarn \
--deploy-mode cluster \
--driver-memory 512m \
--executor-memory 512m \
--executor-cores \
--queue default \
/home/hadoop/sparksql-1.0-SNAPSHOT.jar

通过编程接口指定Schema(Programmatically Specifying the Schema)

当JavaBean不能被预先定义的时候,编程创建DataFrame分为三步:

从原来的RDD创建一个Row格式的RDD.

创建与RDD中Rows结构匹配的StructType,通过该StructType创建表示RDD的Schema.

通过SQLContext提供的createDataFrame方法创建DataFrame,方法参数为RDD的Schema.

import org.apache.spark.sql.{Row, SQLContext}
import org.apache.spark.sql.types._
import org.apache.spark.{SparkContext, SparkConf} object SpecifyingSchema {
def main(args: Array[String]) {
//创建SparkConf()并设置App名称
val conf = new SparkConf().setAppName("SQL-intsmaze")
//SQLContext要依赖SparkContext
val sc = new SparkContext(conf)
//创建SQLContext
val sqlContext = new SQLContext(sc) //从指定的地址创建RDD
val personRDD = sc.textFile(args()).map(_.split(",")) //通过StructType直接指定每个字段的schema
val schema = StructType(
List(
StructField("id", IntegerType, true),
StructField("name", StringType, true),
StructField("age", IntegerType, true)
)
) //将RDD映射到rowRDD
val rowRDD = personRDD.map(p => Row(p().toInt, p().trim, p().toInt)) //将schema信息应用到rowRDD上
val personDataFrame = sqlContext.createDataFrame(rowRDD, schema) //注册表
personDataFrame.registerTempTable("intsmaze")
//执行SQL
val df = sqlContext.sql("select * from intsmaze order by age desc ")
//将结果以JSON的方式存储到指定位置
df.write.json(args())
//停止Spark Context
sc.stop()
}
}

将程序打成jar包,上传到spark集群,提交Spark任务

/home/hadoop/app/spark/bin/spark-submit --class SpecifyingSchema \
--master yarn \
--deploy-mode cluster \
--driver-memory 512m \
--executor-memory 512m \
--executor-cores \
--queue default \
/home/hadoop/sparksql-1.0-SNAPSHOT.jar \
hdfs://192.168.19.131:9000/person.txt hdfs://192.168.19.131:9000/intsmazeresult
/home/hadoop/app/spark/bin/spark-submit --class SpecifyingSchema \
--master yarn \
--deploy-mode client \
--driver-memory 512m \
--executor-memory 512m \
--executor-cores \
--queue default \
/home/hadoop/sparksql-1.0-SNAPSHOT.jar \
hdfs://192.168.19.131:9000/person.txt hdfs://192.168.19.131:9000/intsmazeresult

在maven项目的pom.xml中添加Spark SQL的依赖

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-sql_2.</artifactId>
  <version>1.6.</version>
</dependency>

DataFrames与RDDs的相互转换的更多相关文章

  1. 2.sparkSQL--DataFrames与RDDs的相互转换

    Spark SQL支持两种RDDs转换为DataFrames的方式 使用反射获取RDD内的Schema     当已知类的Schema的时候,使用这种基于反射的方法会让代码更加简洁而且效果也很好. 通 ...

  2. Spark SQL 之 DataFrame

    Spark SQL 之 DataFrame 转载请注明出处:http://www.cnblogs.com/BYRans/ 概述(Overview) Spark SQL是Spark的一个组件,用于结构化 ...

  3. Spark SQL 官方文档-中文翻译

    Spark SQL 官方文档-中文翻译 Spark版本:Spark 1.5.2 转载请注明出处:http://www.cnblogs.com/BYRans/ 1 概述(Overview) 2 Data ...

  4. SparkSql官方文档中文翻译(java版本)

    1 概述(Overview) 2 DataFrames 2.1 入口:SQLContext(Starting Point: SQLContext) 2.2 创建DataFrames(Creating ...

  5. Spark记录-SparkSql官方文档中文翻译(部分转载)

    1 概述(Overview) Spark SQL是Spark的一个组件,用于结构化数据的计算.Spark SQL提供了一个称为DataFrames的编程抽象,DataFrames可以充当分布式SQL查 ...

  6. 转】Spark SQL 之 DataFrame

    原博文出自于: http://www.cnblogs.com/BYRans/p/5003029.html 感谢! Spark SQL 之 DataFrame 转载请注明出处:http://www.cn ...

  7. DataFrames,Datasets,与 SparkSQL

    v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VM ...

  8. A Tale of Three Apache Spark APIs: RDDs, DataFrames, and Datasets(中英双语)

    文章标题 A Tale of Three Apache Spark APIs: RDDs, DataFrames, and Datasets 且谈Apache Spark的API三剑客:RDD.Dat ...

  9. Spark RDDs vs DataFrames vs SparkSQL

    简介 Spark的 RDD.DataFrame 和 SparkSQL的性能比较. 2方面的比较 单条记录的随机查找 aggregation聚合并且sorting后输出 使用以下Spark的三种方式来解 ...

随机推荐

  1. 如何在word文档中添加mathtype加载项

    MathType是强大的数学公式编辑器,通常与office一起使用,mathtype安装完成后,正常情况下会在word文档中的菜单中自动添加mathtype加载项,但有时也会出现小意外,mathtyp ...

  2. Cookie示例

    //caozuocookie        var webusername = "";        function getCookie(name){ var arr,reg=n ...

  3. linux,crontab定时任务中为脚本指定使用参数,crontab的脚本中是否可以带参数

    需求描述: 今天在写脚本的时候,脚本的运行需要给出几个参数,那么就考虑 在crontab写定时任务的时候,是否也是能够在脚本中,增加参数呢, 因为以前没有这么用过,所以呢,就进行一次测试. 测试过程: ...

  4. 一这hash算法

    public static long hash(byte[] digest, int nTime)         {             long rv = ((long)(digest[3 + ...

  5. WebSphere和IHS的安装

    环境:CentOS6.5, IP :192.168.0.91 hostname: IHS 1.下载Installation Manage安装包 URL:http://www.ibm.com/devel ...

  6. Linux同步网络时间

    1.date '+%Y%M%D' 按照格式显示当前日期,结果如下: [root@LAMP ~]# date "+%Y-%m-%d %H:%M:%S" -- :: 2.date -s ...

  7. 说说SPI协议

    SPI,是英语Serial Peripheral Interface 的缩写,顾名思义就是串行外围设备接口.SPI,是一种高速的,全双工,同步的通信总线,并且在芯片的管脚上只占用四根线,节约了芯片的管 ...

  8. linux下jdk,tomcat的安装

    一.安装jdk 1.jdk下载地址: http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.ht ...

  9. eclipse导入maven项目时报Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources

    在用Eclipse IDE for Java EE Developers进行maven项目的开发时,报错Could not calculate build plan: Plugin org.apach ...

  10. xdebug和最重要的php调试技巧

    好几年没有写PHP代码了,最近写了一些.我比较厌烦php,主要是调试麻烦,要按无数次F5,经常刷出空白. 以前调试总是依赖于在代码中加入下面两行 error_reporting(E_ALL ^ E_N ...