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可以有多种存储介质,比较常见是存储为文件.关系型数据库,非关系行数据库. 各种方式有各自的特点,对于海量数据而言,如果想要达到实时查询的目的,使 ...
随机推荐
- [算法]PHP随机合并数组并保持原排序
场景 原有帖子列表A,现需在A中推广新业务B,则需要在A列表中1:1混合B的数据,随机混合,但需保持A和B两列表原来的数据排序.具体参考下面示例的效果. 原理 获知总共元素数量N: for循环N次,取 ...
- [Cerc2012]Non-boring sequences
Description 定义一个序列是不无聊的,当且仅当它的所有子区间都存在一个独一无二的数字,即每个子区间里至少存在一个数字只出现过一次.给定一个长度为\(N(N\leq2\times 10^5)\ ...
- 为 Html 5 和 CSS 3.0 而生——Modernizr的介绍和使用
传统浏览器目前不会被完全取代,令你难以将最新的 CSS3 或 HTML5 功能嵌入你的网站. Modernizr 正是为解决这一难题应运而生,作为一个开源的 JavaScript 库,Moderniz ...
- Transformation和Action
spark的运算操作有两种类型:分别是Transformation和Action,区别如下: Transformation:代表的是转化操作就是我们的计算流程,返回是RDD[T],可以是一个链式的 ...
- 用idea搭建SSM项目,原来这么简单
目录 前言 软件环境 创建项目 数据库文件 配置文件 pom.xml log4j.properties jdbc.properties applicationContext.xml spring-mv ...
- MATLAB indexing question
Question: I have a matrix, for example A = [ 1 2 3; 4 5 6; 7 8 9] ; and a vector of size 1x3 which s ...
- Spring容器的初始化流程
一.创建BeanFactory流程 1.流程入口 创建BeanFactory的流程是从refresh方法的第二步开始的,通过调用obtainFreshBeanFactory方法完成流程. Config ...
- TestOps - 最健壮性的测试角色
一十一 发表于 2018-03-02 09:10:08 TestOps 最具影响力的测试运维一体化综合平台. DevOps实现了从代码到服务的快速落地,而TestOps集成了DevOps效率,更是 ...
- 【作业一】Android开发环境以及开发前的准备
对于Android平台的开发工具,我知道的就是Eclipse和Android Studio(后面简称AS).之前在学习JAVA时,渐渐习惯了Eclipse,后来要搭建Android的开发环境时,本来也 ...
- MVC与单元测试实践之健身网站(五)-系统信息、前台入口
Fit项目停滞了一段时间,现在继续吧.上一篇完成了动作文本和配图的添加.编辑等内容.接下来要完成的是后台的最后一个模块:系统信息:以及前台的入口:关于注册.登录.修改密码等. 一 系统信息 a) 用户 ...