package chapter03

import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.hive.HiveContext
import org.apache.spark.{SparkConf, SparkContext} /**
* Created by chenzechao on 2017/12/21.
*/ /**
spark-shell \
--master yarn-client \
--driver-memory 1G \
--driver-cores 1 \
--queue root.queue_0101_04 \
--executor-memory 2G \
--num-executors 2 \
--conf spark.executor.cores=1 \
--name 'tmp_abc_test' \
--conf spark.yarn.executor.memoryOverhead=4096 \
--conf spark.driver.maxResultSize=8G \
--conf spark.sql.hive.metastore.version=1.2.1 \
--conf spark.sql.shuffle.partitions=150
*/ object document {
// 0 获取参数flag //0.设置环境
val conf = new SparkConf().setAppName("tianchi").setMaster("local[*]")
val sc = new SparkContext(conf)
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val hiveContext = new HiveContext(sc) val jsonFile = "file:///tmp/upload/data/json_file"
val jsonFile_hdfs = "/tmp/ccc/tmpc/json_file"
// 执行SQL
val df1 = sqlContext.sql("select * from sx_360_safe.sub_ladm_exc_app_s16_all_for_double").limit(200).cache()
df1.count() // Print the schema in a tree format
df1.printSchema() // Select only then "gu_flag" column
df1.select("gu_flag").show() // Select everybody, but increment the age by 1
df1.select(df1("empno"),df1("age"),df1("age") + 1 ).show // Select emp age older than 21
df1.filter(df1("age") > 21).select(df1("empno"),df1("age")).show() // Count emp by age
df1.groupBy(df1("age")).count().sort(df1("age")).show()
val gb = df1.groupBy(df1("age")).count()
gb.sort(gb("count")).show() // save dataFrame as json file
df1.write.mode("Overwrite").format("json").save(jsonFile_hdfs)
df1.write.mode("Append").format("json").save(jsonFile_hdfs)
df1.select(df1("empno"), df1("gu_flag")).write.mode("Overwrite").format("parquet").saveAsTable("sx_360_safe.tmp_czc_20180323_04") // this is used to implicitly convert an RDD to a DataFrame.
import sqlContext.implicits._ val df2 = sqlContext.read.json(jsonFile) // Encoders for most common types are automatically provided by importing sqlContext.implicits._
val ds1 = Seq(1, 2, 3).toDS()
ds1.map(_ + 1).collect() // Encoders are also created for case class
case class Person(name:String ,age: Long)
val ds = Seq(Person("Andy",35)).toDS()
ds.show() /**
* Inferring the Schema Using Reflection
*/
import sqlContext.implicits._
case class Person2(name:String, age:Int)
val people = sc.textFile("/tmp/ccc/data/tmpa").filter(_.length > 1).map(_.split(",")).map(p => Person2(p(0),p(1).trim.toInt)).toDF()
people.registerTempTable("people")
sqlContext.sql("select * from people limit 10").show val teenagers = sqlContext.sql("select name,age from people where age >= 23 and age<= 26")
teenagers.map(t => "Name: " + t(0)).collect().foreach(println) // or by field name
teenagers.map(t => "Name: " + t.getAs[String]("name")).collect().foreach(println) // row.getValuesMap[T] retrieves multiple columns at once into a Map[String,T]
teenagers.map(_.getValuesMap[Any](List("name","age"))).collect().foreach(println) /**
* Programmatically Specifying the Schema
*/
val schemaString = "name age"
import org.apache.spark.sql.Row
import org.apache.spark.sql.types.{StructType,StructField,StringType} val schema =
StructType(
schemaString.split(" ").map(fieldName => StructField(fieldName,StringType,true))
) // Convert records of the RDD (people) to Rows
val people2 = sc.textFile("/tmp/ccc/data/tmpa")
val rowRDD = people2.map(_.split(",")).map(p => Row(p(0),p(1).trim)) // Apply the schema to the RDD
val peopleDataFrame = sqlContext.createDataFrame(rowRDD,schema) // Register the DataFrames as a table
peopleDataFrame.registerTempTable("people") // SQL val df = sqlContext.read.load("/tmp/examples/src/main/resources/users.parquet") val df3 = sqlContext.read.format("json").load("/tmp/examples/src/main/resources/people.json") // Run SQL on files directly
val df4 = sqlContext.sql("select * from parquet.`/tmp/examples/src/main/resources/users.parquet`") // Save modes
/**
* ErrorIfExists (default)
* Append
* Overwrite
* Ignore
*/ val parquetFile = sqlContext.read.parquet("") }

spark_learn的更多相关文章

随机推荐

  1. 检测 iOS 的 APP 性能的一些方法

    本文转载于微信公众号:iOS大全 首先如果遇到应用卡顿或者因为内存占用过多时一般使用Instruments里的来进行检测.但对于复杂情况可能就需要用到子线程监控主线程的方式来了,下面我对这些方法做些介 ...

  2. Python:正则表达式(二)

    则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配. Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式. re 模块使 Python 语 ...

  3. 在VirtualBox中安装CentOS 7【转载】

    当初接触Linux的时候,因为条件限制,只能在VirtualBox虚拟机中安装Linux系统使用,由于是小白,爬了好多坑.于是决定写一篇关于在虚拟机中安装linux系统的文章.一是为了巩固自己的知识, ...

  4. How to Write a Spelling Corrector用java 写拼写检查器 Java实现 以备查验

    import java.io.*;import java.util.*;import java.util.regex.*; class Spelling { private final HashMap ...

  5. Luogu 2258 [NOIP2014] 子矩阵

    被普及组虐了,感觉

  6. 使用 Node.js 实现简单的 Webhook

    距离 Node.js 这个东西出来已经过了好久了,感觉现在的前端如果不会点 Node.js 就有点太落后于时代啦.我接触它是从去年暑假开始的,当时在写一个比较神奇的东西,就顺便接触了一下.虽然网传 n ...

  7. Object.prototype.toString.call(arg)详解

    经常能碰到Object.prototype.toString.call对参数类型进行判断,一开始只知道怎么使用,却不了解具体实现的原理,最近恶补了一下相关知识,写个笔记加强理解,有什么不对的请指教. ...

  8. 最大子序列和——HDU-1003 Max Sum

    题目大意:给定序列个数n及n个数,求该序列的最大连续子序列的和,要求输出最大连续子序列的和以及子序列的首位位置 解题思路:经典DP,可以定义dp[i]表示以a[i]为结尾的子序列的和的最大值,因而最大 ...

  9. SAS笔记(2) RETAIN语句

    本文重点: 使用RETIAN,INPUT在每次循环执行时保留上一次PDV中的变量值. SUM语句和SET语句会自动RETAIN变量. 1. RETAIN语句 1.1 Example 1 先来看看在DA ...

  10. 动态规划---等和的分隔子集(计蒜课)、从一个小白的角度剖析DP问题

    自己还是太菜了,算法还是很难...这么简单的题目竟然花费了我很多时间...在这里我用一个小白的角度剖析一下这道题目. 晓萌希望将1到N的连续整数组成的集合划分成两个子集合,且保证每个集合的数字和是相等 ...