SparkSQLDemo.scala


import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{StringType, StructField, StructType} object SparkSQLDemo { // $example on:create_ds$
case class Person(name: String, age: Long)
// $example on:create_ds$ def main(args: Array[String]): Unit = {
//开启SparkSession
// $example on: init_session$
val spark = SparkSession
.builder()
.appName("SparkSQLDemo")
.master("local")
.config("spark.some.config.option", "some-value")
.getOrCreate()
// $example off: init_session$ // runBasicDataFrameDemo(spark)
// runDatasetCreationDemo(spark)
// runInferSchemaDemo(spark)
runProgrammaticSchemaDemo(spark) //关闭SparkSeesion
spark.stop() } private def runBasicDataFrameDemo(spark: SparkSession) = { val df = spark.read.json("/Users/hadoop/app/spark/examples/src/main/resources/people.json") //Displays the content of the DataFrame to stdout
df.show() //Print the schema in a tree format
df.printSchema() //Select only the "name" column
df.select("name").show() //This import is needed to use the $-notation
import spark.implicits._
df.select($"name", $"age" + 1).show() //Select people older than 21
df.select($"age" > 21).show() //Count people by age
df.groupBy("age").count().show() //$example on: global_temp_view$
//Register the DataFrame as a SQL temporary view
df.createOrReplaceTempView("people")
val sqlDF = spark.sql("select * from people")
sqlDF.show() //Register the DataFrame as a global temporary view
df.createGlobalTempView("people") //Global temporary view is tied to a system preserved database `global_temp`
spark.sql("select * from global_temp.people").show //Global temporary view is cross-session
spark.newSession().sql("select * from global_temp.people").show() } private def runDatasetCreationDemo(spark: SparkSession) = { // A container for a [[Dataset]], used for implicit conversions in Scala.
// To use this, import implicit conversions in SQL:
import spark.implicits._ // .toDS() -> 这是用括号声明的,以防止Scala编译器将`rdd.toDS(“1”)`视为调用此toDS然后应用于返回的数据集。 //Encoder are created for case classes (为case class 创建编码器)
val caseClassDS = Seq(Person("Andy", 32)).toDS()
caseClassDS.show() //Encoders for most common types are automatically provided by importing spark.implicits._
val primitiveDS = Seq(1, 2, 3).toDS()
primitiveDS.map(_ + 1).foreach(println(_))//.collect() //DataFrames can be converted to a Dataset by providing a class. Mapping will bedone by name
val path = "/Users/hadoop/app/spark/examples/src/main/resources/people.json"
val peopleDS = spark.read.json(path).as[Person]
peopleDS.show() } private def runInferSchemaDemo(spark: SparkSession) = { // $example on: schema_inferring$
//For implicit conversions from RDDs to DataFrames
import spark.implicits._ //Create an RDD of Person objects from a text file, convert it to a DataFrame
val peopleDF = spark.sparkContext
.textFile("/Users/hadoop/app/spark/examples/src/main/resources/people.txt")
.map(_.split(","))
.map(x => Person(x(0), x(1).trim.toInt))
.toDF() //Register the DataFrame as a temporary view
peopleDF.createOrReplaceTempView("people") //SQL statements can be run by using the sql methods provided by Spark
val teenagersDF = spark.sql("select name, age from people where age between 13 and 19") //The columns of a row in the result can be accessed by field index
//(结果中的行的列可以通过字段索引访问)
teenagersDF.map(teenager => s"Name: ${teenager(0)}").show() //or by field name
teenagersDF.map(teenager => s"Name: ${teenager.getAs[String]("name")}").show() //No pre-defined encoders for Dataset[Map[K,V]], define explicitly
//(Dataset[Map[K,V]] 没有预定义的编码器, 显式定义)
implicit val mapEncoder = org.apache.spark.sql.Encoders.kryo[Map[String, Any]] //Primitive types and case classes can be also defined as
//(原始类型和case类也可以定义为隐式val )
//implicit val stringIntMapEncoder: Encoder[Map[String, Any]] = ExpressionEncoder() //row.getValuesMap[T] retrieves multiple columns at once into a Map[String, T]
teenagersDF.map(teenager =>
teenager.getValuesMap[Any](List("name", "age"))
).foreach(println(_))//.collect() // $example off: schema_inferring$ } private def runProgrammaticSchemaDemo(spark: SparkSession) = { import spark.implicits._
// $example on: programmatic_schema$ //Create an RDD
val peopleRDD = spark.sparkContext.textFile("/Users/hadoop/app/spark/examples/src/main/resources/people.txt") //The schema is encoded in a string
val schemaString = "name age" //Generate the schema based on the string of schema
val fields = schemaString.split(" ")
.map(fieldName => StructField(fieldName, StringType, nullable = true))
val schema = StructType(fields) //Convert records of the RDD (people) to Rows
val rowRDD = peopleRDD
.map(_.split(","))
.map(attributes => Row(attributes(0), attributes(1).trim)) //Apply the schema to the RDD
val peopleDF = spark.createDataFrame(rowRDD, schema) //Creates a temporary view using the DataFrame
peopleDF.createOrReplaceTempView("people") //SQL can be run over a temporary view created using DataFrames
val results = spark.sql("select name from people") //The results of SQL queries are DataFrames and support all the normal RDD operations
//The columns of a row in the result can be accessed by field index or by field name
results.map(attributes => s"Name: ${attributes(0)}").show() // $exmaple off: programmatic_schema$
}
}


sparkSQL中的example学习(1)的更多相关文章

  1. sparkSQL中的example学习(3)

    UserDefinedTypedAggregation.scala(用户可自定义类型) import org.apache.spark.sql.expressions.Aggregator impor ...

  2. sparkSQL中的example学习(2)

    UserDefinedUntypedAggregate.scala(默认返回类型为空,不能更改) import org.apache.spark.sql.{Row, SparkSession} imp ...

  3. PHP中的Libevent学习

    wangbin@2012,1,3 目录 Libevent在php中的应用学习 1.      Libevent介绍 2.      为什么要学习libevent 3.      Php libeven ...

  4. JS中childNodes深入学习

    原文:JS中childNodes深入学习 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <ti ...

  5. CNCC2017中的深度学习与跨媒体智能

    CNCC2017中的深度学习与跨媒体智能 转载请注明作者:梦里茶 目录 机器学习与跨媒体智能 传统方法与深度学习 图像分割 小数据集下的深度学习 语音前沿技术 生成模型 基于贝叶斯的视觉信息编解码 珠 ...

  6. 【Spark篇】---SparkSQL中自定义UDF和UDAF,开窗函数的应用

    一.前述 SparkSQL中的UDF相当于是1进1出,UDAF相当于是多进一出,类似于聚合函数. 开窗函数一般分组取topn时常用. 二.UDF和UDAF函数 1.UDF函数 java代码: Spar ...

  7. 图解BERT(NLP中的迁移学习)

    目录 一.例子:句子分类 二.模型架构 模型的输入 模型的输出 三.与卷积网络并行 四.嵌入表示的新时代 回顾一下词嵌入 ELMo: 语境的重要性 五.ULM-FiT:搞懂NLP中的迁移学习 六.Tr ...

  8. python中confIgparser模块学习

    python中configparser模块学习 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section ...

  9. Scala中的类学习

    Scala中的类学习 从java了解类的情况下,了解Scala的类并不难.Scala类中的字段自动带getter和setter方法,用@BeanProperty注解生成javaBean对象的getXX ...

随机推荐

  1. oracle 死锁 锁

    [zhuan]今天看群里在讨论数据库死锁的问题,也一起研究了下,查了些资料在这里总结下. 所谓死锁: 是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将 ...

  2. 告诉你一些DBA求职面试技巧

    告诉你一些DBA求职面试技巧 要自信!永远不要低估你的能力.如果你不了解什么问题的答案,承认它.重点放在你找出答案的能力和你学习的意愿. 不要自大!是的,你可能过于自信而被认为是骄傲的.轻率的,甚至是 ...

  3. MySQL第三课

    首先创建一个数据库: CREATE DATABASE ku; Query OK, 1 row affected 查看一下是否有此数据库: SHOW DATABASES; +-------------- ...

  4. __rpm.so: underfined symbol : rpmpkgverifySigs 故障分析

    前言: 近期漏洞修复频繁,各种组件需要升级,经多次碰撞,发现 yum update 来升级组件是最有效最安全的方式(绿盟通过版本比对的扫描结果可以忽略). 然而,各家的设备各家管,一到升级就发现一堆问 ...

  5. Vue之methods watch和compute的区别和联系

    computed是用来把多个基础的数据组合成一个复杂的数据:同时获得了vue提供的自动变更通知机制. 即将基础数据变为复杂数据,同时获得自动变更通知机制 watch是利用了vue的自动变更通知机制,用 ...

  6. Jenkins显示reportng测试报告

    在搭建Jenkins自动化测试平台后,我们点击立即构建就可以运行测试用例了,但没有地方查看测试报告,现在写这篇博客总结怎么在Jenkins显示reportng测试报告. 在maven项目配置repor ...

  7. Linux下怎么启动、停止和重启MySQL

    一.启动方式 使用linux命令service 启动:service mysqld start 使用 mysqld 脚本启动:/etc/inint.d/mysqld start 使用 safe_mys ...

  8. 通过 Beautiful Soup 4 预防 XSS 攻击

    通过beautifulsoup4预防XSS攻击 借助beautifulsoup4将用户输入内容进行过滤 实际使用时需要采用单例模式 步骤: 实例化对象,对页面进行解析 查找目标标签 将非法标签进行清空 ...

  9. CodeForces - 545CWoodcutters

    传送门 题目大意:n棵树(10^5),坐标xi,高度hi,把这棵树砍到,可以向右倒[xi,xi+hi]被占, 向左倒[xi-hi,xi]被占,必须要倒的坐标没有被占才能倒,不砍倒就xi被占,问最多砍几 ...

  10. MySQL实战45讲学习笔记:第二十五讲

    一.引子 在上一篇文章中,我和你介绍了 binlog 的基本内容,在一个主备关系中,每个备库接收主库的 binlog 并执行. 正常情况下,只要主库执行更新生成的所有 binlog,都可以传到备库并被 ...