以前使用过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. Dubbo 源码分析系列之一环境搭建

    环境搭建的步骤有哪些 依赖外部的环境 使用的开发工具 源码的拉取 结构大致介绍 1 依赖的外部环境 安装JDK 安装Git 安装maven 这边我们就不介绍怎么安装这些外部环境了,大家自行从安装这些外 ...

  2. [AGC001 E] BBQ Hard

    Description 有\(N(N\leq 200000)\)个数对\((a_i,b_i)(a_i,b_i,\leq 2000)\),求出\(\sum\limits_{i=1}^n\sum\limi ...

  3. C# ABP源码详解 之 BackgroundJob,后台工作(一)

    本文归属作者所有,转发请注明本文链接. 1. 前言 ABP的BackgroundJob,用来处理耗时的操作.比如客户端上传文件,我们要把文件(Excel)做处理,这耗时的操作我们应该放到后台工作者去做 ...

  4. CentOS 7 安装 .Net Core 2.0 详细步骤

    轰轰烈烈的Core 热潮,从部署环境开始.参照了网上不少前辈的教程,也遇到不少的坑,这边做个完整的笔记. 一.构建.Net core 2的应用程web发布,因为是用来测试centos上的core 环境 ...

  5. Ajax事件,方法

    1\ready:事件:使用ready()来使函数在文档加载后可用 $(document).ready(funcation(){ 函数体 }) 2\click事件:当单机元素时,使用 3\focus事件 ...

  6. Aspose.Cells API 中文版文档 下载

    链接: https://pan.baidu.com/s/19foJyWgPYvA7eIqEHJ_IdA 密码: yxun

  7. 功率因数cosφ仪表盘

    一.截图 二.说明 本篇博客主要是有三个亮点: ① 刻度标注在仪表盘标线外 ② 仪表盘存在两个刻度值,分别是(正)0.5~1 和(负)-1~-0.5 ③ 仪表盘内标注,分别是“超前”和“滞后” 三.代 ...

  8. 禁用 Gnome Shell 默认的 Ubuntu Dock 和 Ubuntu AppIndicators 扩展

    以前折腾的时候禁用过,现在已经忘记目录了,结果今天手贱把系统从 18.04 升级到了 18.10 ,很多东西都要重新搞过,而且用惯了 mac 已经不熟悉 linux 上瞎折腾的那一套了,简直坑爹.. ...

  9. python之变量与常量

    变量:把程序运行过程中产生的值,暂时存储在内存,方便后面的程序调用. 被引号括起来的内容是字符串,原样输出.#单行注释 用来标注代码信息,特点:被注释的内容不会被执行.Ctrl + /'''内容''' ...

  10. Flutter 布局(六)- SizedOverflowBox、Transform、CustomSingleChildLayout详解

    本文主要介绍Flutter布局中的SizedOverflowBox.Transform.CustomSingleChildLayout三种控件,详细介绍了其布局行为以及使用场景,并对源码进行了分析. ...