以前使用过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 一些使用示例的更多相关文章

  1. Spark Dataset DataFrame 操作

    Spark Dataset DataFrame 操作 相关博文参考 sparksql中dataframe的用法 一.Spark2 Dataset DataFrame空值null,NaN判断和处理 1. ...

  2. Spark Dataset DataFrame空值null,NaN判断和处理

    Spark Dataset DataFrame空值null,NaN判断和处理 import org.apache.spark.sql.SparkSession import org.apache.sp ...

  3. Spark提高篇——RDD/DataSet/DataFrame(二)

    该部分分为两篇,分别介绍RDD与Dataset/DataFrame: 一.RDD 二.DataSet/DataFrame 该篇主要介绍DataSet与DataFrame. 一.生成DataFrame ...

  4. spark第七篇:Spark SQL, DataFrame and Dataset Guide

    预览 Spark SQL是用来处理结构化数据的Spark模块.有几种与Spark SQL进行交互的方式,包括SQL和Dataset API. 本指南中的所有例子都可以在spark-shell,pysp ...

  5. Spark提高篇——RDD/DataSet/DataFrame(一)

    该部分分为两篇,分别介绍RDD与Dataset/DataFrame: 一.RDD 二.DataSet/DataFrame 先来看下官网对RDD.DataSet.DataFrame的解释: 1.RDD ...

  6. 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 ...

  7. RDD/Dataset/DataFrame互转

    1.RDD -> Dataset val ds = rdd.toDS() 2.RDD -> DataFrame val df = spark.read.json(rdd) 3.Datase ...

  8. 【spark】dataframe常见操作

    spark dataframe派生于RDD类,但是提供了非常强大的数据操作功能.当然主要对类SQL的支持. 在实际工作中会遇到这样的情况,主要是会进行两个数据集的筛选.合并,重新入库. 首先加载数据集 ...

  9. Spark:将DataFrame写入Mysql

    Spark将DataFrame进行一些列处理后,需要将之写入mysql,下面是实现过程 1.mysql的信息 mysql的信息我保存在了外部的配置文件,这样方便后续的配置添加. //配置文件示例: [ ...

  10. Spark:DataFrame批量导入Hbase的两种方式(HFile、Hive)

    Spark处理后的结果数据resultDataFrame可以有多种存储介质,比较常见是存储为文件.关系型数据库,非关系行数据库. 各种方式有各自的特点,对于海量数据而言,如果想要达到实时查询的目的,使 ...

随机推荐

  1. IdentityServer4 中文文档 -1- (简介)背景

    IdentityServer4 中文文档 -1- (简介)背景 原文:http://docs.identityserver.io/en/release/intro/big_picture.html 目 ...

  2. [转]使用@Test 也可以从spring容器中获取依赖注入

    转自:http://blog.csdn.net/u010987379/article/details/52091790 @RunWith(SpringJUnit4ClassRunner.class) ...

  3. 深入理解JVM——对象

    对象的创建 虚拟机遇到一条new指令时,首先检查指令的参数能否在常量池中定位到一个类的符号引用,并且检查这个符号引用代表的类是否已经被加载.解析和初始化过.如果没有,必须先执行相应的类加载过程. 接下 ...

  4. 如何把SVG小图片转换为 html字体图表

    自制作的简单字体图表使用案例:查看demo 制作步骤: 1:登录制作工具在线网站 https://icomoon.io/ 2:右上角红色 按钮进入到:https://icomoon.io/app/#/ ...

  5. linux学习笔记-grub模式引导进入系统

    我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! 1.设置系统启动盘所在位置 set root='hd0,msdosx' 2.手动加载内核驱动程序并配置root目录位置 linu ...

  6. 原生JS强大DOM选择器querySelector与querySelectorAll

    在传统的 JavaScript 开发中,查找 DOM 往往是开发人员遇到的第一个头疼的问题,原生的 JavaScript 所提供的 DOM 选择方法并不多,仅仅局限于通过 tag, name, id ...

  7. 【读书笔记】iOS-成为一名开发者

    iOS开发者计划是按年付费的,在过期前60天可以开始续费.如果你不续费的话,你将无法发布应用.另外苹果会吊销你的开发者证书和发布证书.最后,苹果将你在iTunes App Store上的所有应用下架. ...

  8. MinGW编译Mongo-CXX-Driver

    8. mongo-cxx-driver pacman -S mingw-w64-x86_64-cyrus-sasl pacman -S mingw-w64-x86_64-extra-cmake-mod ...

  9. Oracle 11gR2_database在Linux下的安装

    Oracle 11gR2_database在Linux下的安装 by:授客 QQ:1033553122 由于篇幅问题,采用链接分享的形式,烦请复制以下网址,黏贴到浏览器中打开,下载 http://pa ...

  10. onSaveInstanceState场景

    需要注意的是, onSaveInstanceState()方法并不是一定会被调用的, 因为有些场景是不需要保存状态数据的. 比如用户按下BACK键退出activity时, 用户显然想要关闭这个acti ...