Spark DataSet 、DataFrame 一些使用示例
以前使用过DS和DF,最近使用Spark ML跑实验,再次用到简单复习一下。
//案例数据
1,2,3
4,5,6
7,8,9
10,11,12
13,14,15
1,2,3
4,5,6
7,8,9
10,11,12
13,14,15
1,2,3
4,5,6
7,8,9
10,11,12
13,14,15
1:DS与DF关系?
type DataFrame = Dataset[Row]
2:加载txt数据
val rdd = sc.textFile("data")
val df = rdd.toDF()
这种直接生成DF,df数据结构为(查询语句:df.select("*").show(5)):

只有一列,属性为value。
3: df.printSchema()

4:case class 可以直接就转成DS
// Note: Case classes in Scala 2.10 can support only up to 22 fields. To work around this limit,
// you can use custom classes that implement the Product interface
case class Person(name: String, age: Long) // Encoders are created for case classes
val caseClassDS = Seq(Person("Andy", 32)).toDS()
5:直接解析主流格式文件
val path = "examples/src/main/resources/people.json"
val peopleDS = spark.read.json(path).as[Person]
6:RDD转成DataSet两种方法
数据格式:
xiaoming,18,iPhone
mali,22,xiaomi
jack,26,smartisan
mary,16,meizu
kali,45,huawei
(a):使用反射推断模式
val persons = rdd.map {
x =>
val fs = x.split(",")
Person(fs(0), fs(1).toInt, fs(2))
}
persons.toDS().show(2)
persons.toDF("newName", "newAge", "newPhone").show(2)
persons.toDF().show(2)

(b):编程方式指定模式
步骤:

import org.apache.spark.sql.types._
//1:创建RDD
val rddString = sc.textFile("C:\\Users\\Daxin\\Documents\\GitHub\\OptimizedRF\\sql_data")
//2:创建schema
val schemaString = "name age phone"
val fields = schemaString.split(" ").map {
filedName => StructField(filedName, StringType, nullable = true)
}
val schema = StructType(fields)
//3:数据转成Row
val rowRdd = rddString.map(_.split(",")).map(attributes => Row(attributes(0), attributes(1), attributes(2)))
//创建DF
val personDF = spark.createDataFrame(rowRdd, schema)
personDF.show(5)
7:注册视图
//全局表,生命周期多个session可以共享并且创建该视图的sparksession停止该视图也不会过期
personDF.createGlobalTempView("GlobalTempView_Person")
//临时表,存在的话覆盖。生命周期和sparksession相同
personDF.createOrReplaceTempView("TempView_Person")
//personDF.createTempView("TempView_Person") //如果视图已经存在则异常 // Global temporary view is tied to a system preserved database `global_temp`
//全局视图存储在global_temp数据库中,如果不加数据库前缀异常,提示找不到视图
spark.sql("select * from global_temp.GlobalTempView_Person").show(2)
//临时表不需要添加数据库
spark.sql("select * from TempView_Person").show(2)

8:UDF 定义:
Untyped User-Defined Aggregate Functions
package com.daxin.sq.df import org.apache.spark.sql.expressions.MutableAggregationBuffer
import org.apache.spark.sql.expressions.UserDefinedAggregateFunction
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row /**
* Created by Daxin on 2017/11/18.
* url:http://spark.apache.org/docs/latest/sql-programming-guide.html#untyped-user-defined-aggregate-functions
*/ //Untyped User-Defined Aggregate Functions
object MyAverage extends UserDefinedAggregateFunction { // Data types of input arguments of this aggregate function
override def inputSchema: StructType = StructType(StructField("inputColumn", IntegerType) :: Nil) //2 // Updates the given aggregation buffer `buffer` with new input data from `input`
//TODO 第一个缓冲区是sum,第二个缓冲区是元素个数
override def update(buffer: MutableAggregationBuffer, input: Row): Unit = {
if (!input.isNullAt(0)) {
buffer(0) = buffer.getInt(0) + input.getInt(0) // input.getInt(0)是中inputSchema定义的第0个元素
buffer(1) = buffer.getInt(1) + 1
println()
}
} // Data types of values in the aggregation buffer
//TODO 定义缓冲区的模型(也就是数据结构)
override def bufferSchema: StructType = StructType(StructField("sum", IntegerType) :: StructField("count", IntegerType) :: Nil) // Merges two aggregation buffers and stores the updated buffer values back to `buffer1`
//TODO MutableAggregationBuffer 是Row子类
override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {
//TODO 合并分区,将结果更新到buffer1
buffer1(0) = buffer1.getInt(0) + buffer2.getInt(0)
buffer1(1) = buffer1.getInt(1) + buffer2.getInt(1) println()
} // Initializes the given aggregation buffer. The buffer itself is a `Row` that in addition to
// standard methods like retrieving a value at an index (e.g., get(), getBoolean()), provides
// the opportunity to update its values. Note that arrays and maps inside the buffer are still
// immutable.
override def initialize(buffer: MutableAggregationBuffer): Unit = {
buffer(0) = 0
buffer(1) = 0
} // Whether this function always returns the same output on the identical input
override def deterministic: Boolean = true // Calculates the final result
override def evaluate(buffer: Row): Int = buffer.getInt(0) / buffer.getInt(1) // The data type of the returned value,返回值类型
override def dataType: DataType = IntegerType //
}
测试代码:
spark.udf.register("myAverage", MyAverage)
val result = spark.sql("SELECT myAverage(age) FROM TempView_Person")
result.show()
8:关于机器学习中的DataFrame的schema定:
一列名字为 label,另一列名字为 features。一般可以使用case class完成转换
case class UDLabelpOint(label: Double, features: org.apache.spark.ml.linalg.Vector)
Spark DataSet 、DataFrame 一些使用示例的更多相关文章
- Spark Dataset DataFrame 操作
Spark Dataset DataFrame 操作 相关博文参考 sparksql中dataframe的用法 一.Spark2 Dataset DataFrame空值null,NaN判断和处理 1. ...
- Spark Dataset DataFrame空值null,NaN判断和处理
Spark Dataset DataFrame空值null,NaN判断和处理 import org.apache.spark.sql.SparkSession import org.apache.sp ...
- Spark提高篇——RDD/DataSet/DataFrame(二)
该部分分为两篇,分别介绍RDD与Dataset/DataFrame: 一.RDD 二.DataSet/DataFrame 该篇主要介绍DataSet与DataFrame. 一.生成DataFrame ...
- spark第七篇:Spark SQL, DataFrame and Dataset Guide
预览 Spark SQL是用来处理结构化数据的Spark模块.有几种与Spark SQL进行交互的方式,包括SQL和Dataset API. 本指南中的所有例子都可以在spark-shell,pysp ...
- Spark提高篇——RDD/DataSet/DataFrame(一)
该部分分为两篇,分别介绍RDD与Dataset/DataFrame: 一.RDD 二.DataSet/DataFrame 先来看下官网对RDD.DataSet.DataFrame的解释: 1.RDD ...
- Spark获取DataFrame中列的几种姿势--col,$,column,apply
1.doc上的解释(https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/Column.html) df("c ...
- RDD/Dataset/DataFrame互转
1.RDD -> Dataset val ds = rdd.toDS() 2.RDD -> DataFrame val df = spark.read.json(rdd) 3.Datase ...
- 【spark】dataframe常见操作
spark dataframe派生于RDD类,但是提供了非常强大的数据操作功能.当然主要对类SQL的支持. 在实际工作中会遇到这样的情况,主要是会进行两个数据集的筛选.合并,重新入库. 首先加载数据集 ...
- Spark:将DataFrame写入Mysql
Spark将DataFrame进行一些列处理后,需要将之写入mysql,下面是实现过程 1.mysql的信息 mysql的信息我保存在了外部的配置文件,这样方便后续的配置添加. //配置文件示例: [ ...
- Spark:DataFrame批量导入Hbase的两种方式(HFile、Hive)
Spark处理后的结果数据resultDataFrame可以有多种存储介质,比较常见是存储为文件.关系型数据库,非关系行数据库. 各种方式有各自的特点,对于海量数据而言,如果想要达到实时查询的目的,使 ...
随机推荐
- Python使用@property装饰类方法
Python版本:3.5.2 假如我们有一个Student类,并在其中定义了一个score属性,但是score属性会被显露出去,没办法检查参数,导致成绩可以随意更改: stu = Student() ...
- asp.net mvc之自定义WebViewPage
采用Razor引擎的View文件最终都会编译成一个WebViewPage类型, 通过自定义WebViewPage,添加相应的属性和方法,你可以很方便的在View里调用, 自定义WebViewPage只 ...
- Nuget快捷实践
Nuget快捷实践 简介 本文主要包含三个部分,即创建nuget包.上传nuget包和删除nuget包.旨在引导快速使用nuget打包和使用,并实现对于nuget的简单管理. 本文使用的nuget服务 ...
- failed to install tomcat6 service ,check your setting and permissions
出现的问题: 刚刚重新装了tomcat7,出现提示:Tomcat安装不成功.提示是:failed to install tomcat6 service ,check your setting and ...
- 【Tomcat】Tomcat日志切割
下载并解压缩 cronolog # tar zxvf cronolog-1.6.2.tar.gz 2.进入cronolog安装文件所在目录 # cd cronolog-1.6.2 3.运行安装 # ...
- Matlab Euler's method
% matlab script to test efficiency of % Euler's method, classical Runge-Kutta, and ode45 % on Arenst ...
- Frobenius norm(Frobenius 范数)
Frobenius 范数,简称F-范数,是一种矩阵范数,记为||·||F. 矩阵A的Frobenius范数定义为矩阵A各项元素的绝对值平方的总和,即 可用于 利用低秩矩阵来近似单一数据矩阵. 用数学表 ...
- spring boot (2):spring boot 打包tomcat、tomcat 部署多个项目、服务器部署项目SSL 设置(阿里云)
一.spring boot 内置tomcat配置https: 关于自签名证书可以看下上一篇 spring boot1 更详细的可以看转载 https://www.jianshu.com/p/8d4ab ...
- Python 练习: 简单的用户登录判断
_user = "klvchen" _passwd = " counter = 0 while counter < 3: username = raw_input( ...
- Python 练习: 打印0到99小于50或大于70的数字
for i in range(100): if i < 50 or i > 70: print(i) 注意: range(100) 表示 0 到 99 个数字