Spark SQL 抽样函数 ——TABLESAMPLE 的坑点
最近需要实现一段 Spark SQL 逻辑,对数据集进行抽样指定的行数。
由于数据集较大,刚开始的逻辑是,取窗口函数随机排序后 row_number 的前 n 行。但运行速度较慢,所以想起了 TABLESAMLE 函数,支持直接取 Rows, 尝试后发现速度特别快,基本上几秒内就完成对亿级数据的采样。所以好奇就去查看文档和代码逻辑。
The
TABLESAMPLEstatement is used to sample the table. It supports the following sampling methods:
TABLESAMPLE(xROWS): Sample the table down to the given number of rows.TABLESAMPLE(xPERCENT): Sample the table down to the given percentage. Note that percentages are defined as a number between 0 and 100.TABLESAMPLE(BUCKETxOUT OFy): Sample the table down to axout ofyfraction.Note:
TABLESAMPLEreturns the approximate number of rows or fraction requested.
文档中没有对实现逻辑有过多的说明,所以去代码中找问题。
源码中,匹配 SampleByRowsContext 时,调用的方法是 Limit(expression(ctx.expression), query),也就是说和 limit rows 是一个逻辑。
而 SampleByPercentileContext 实现的才是随机采样。
所以,如果对抽样的随机性有要求,还是老老实实用 SampleByPercentileContext,或者窗口函数。
附 相关代码:
/**
* Add a [[Sample]] to a logical plan.
*
* This currently supports the following sampling methods:
* - TABLESAMPLE(x ROWS): Sample the table down to the given number of rows.
* - TABLESAMPLE(x PERCENT) [REPEATABLE (y)]: Sample the table down to the given percentage with
* seed 'y'. Note that percentages are defined as a number between 0 and 100.
* - TABLESAMPLE(BUCKET x OUT OF y) [REPEATABLE (z)]: Sample the table down to a 'x' divided by
* 'y' fraction with seed 'z'.
*/
private def withSample(ctx: SampleContext, query: LogicalPlan): LogicalPlan = withOrigin(ctx) {
// Create a sampled plan if we need one.
def sample(fraction: Double, seed: Long): Sample = {
// The range of fraction accepted by Sample is [0, 1]. Because Hive's block sampling
// function takes X PERCENT as the input and the range of X is [0, 100], we need to
// adjust the fraction.
val eps = RandomSampler.roundingEpsilon
validate(fraction >= 0.0 - eps && fraction <= 1.0 + eps,
s"Sampling fraction ($fraction) must be on interval [0, 1]",
ctx)
Sample(0.0, fraction, withReplacement = false, seed, query)
}
if (ctx.sampleMethod() == null) {
throw QueryParsingErrors.emptyInputForTableSampleError(ctx)
}
val seed = if (ctx.seed != null) {
ctx.seed.getText.toLong
} else {
(math.random() * 1000).toLong
}
ctx.sampleMethod() match {
case ctx: SampleByRowsContext =>
Limit(expression(ctx.expression), query)
case ctx: SampleByPercentileContext =>
val fraction = ctx.percentage.getText.toDouble
val sign = if (ctx.negativeSign == null) 1 else -1
sample(sign * fraction / 100.0d, seed)
case ctx: SampleByBytesContext =>
val bytesStr = ctx.bytes.getText
if (bytesStr.matches("[0-9]+[bBkKmMgG]")) {
throw QueryParsingErrors.tableSampleByBytesUnsupportedError("byteLengthLiteral", ctx)
} else {
throw QueryParsingErrors.invalidByteLengthLiteralError(bytesStr, ctx)
}
case ctx: SampleByBucketContext if ctx.ON() != null =>
if (ctx.identifier != null) {
throw QueryParsingErrors.tableSampleByBytesUnsupportedError(
"BUCKET x OUT OF y ON colname", ctx)
} else {
throw QueryParsingErrors.tableSampleByBytesUnsupportedError(
"BUCKET x OUT OF y ON function", ctx)
}
case ctx: SampleByBucketContext =>
sample(ctx.numerator.getText.toDouble / ctx.denominator.getText.toDouble, seed)
}
}
Spark SQL 抽样函数 ——TABLESAMPLE 的坑点的更多相关文章
- Spark SQL 自定义函数类型
Spark SQL 自定义函数类型 一.spark读取数据 二.自定义函数结构 三.附上长长的各种pom 一.spark读取数据 前段时间一直在研究GeoMesa下的Spark JTS,Spark J ...
- Spark SQL 用户自定义函数UDF、用户自定义聚合函数UDAF 教程(Java踩坑教学版)
在Spark中,也支持Hive中的自定义函数.自定义函数大致可以分为三种: UDF(User-Defined-Function),即最基本的自定义函数,类似to_char,to_date等 UDAF( ...
- 详解Spark sql用户自定义函数:UDF与UDAF
UDAF = USER DEFINED AGGREGATION FUNCTION Spark sql提供了丰富的内置函数供猿友们使用,辣为何还要用户自定义函数呢?实际的业务场景可能很复杂,内置函数ho ...
- Spark学习之路(十一)—— Spark SQL 聚合函数 Aggregations
一.简单聚合 1.1 数据准备 // 需要导入spark sql内置的函数包 import org.apache.spark.sql.functions._ val spark = SparkSess ...
- Spark 系列(十一)—— Spark SQL 聚合函数 Aggregations
一.简单聚合 1.1 数据准备 // 需要导入 spark sql 内置的函数包 import org.apache.spark.sql.functions._ val spark = SparkSe ...
- 小白学习Spark系列四:RDD踩坑总结(scala+spark2.1 sql常用方法)
初次尝试用 Spark+scala 完成项目的重构,由于两者之前都没接触过,所以边学边用的过程大多艰难.首先面临的是如何快速上手,然后是代码调优.性能调优.本章主要记录自己在项目中遇到的问题以及解决方 ...
- Spark注册UDF函数,用于DataFrame DSL or SQL
import org.apache.spark.sql.SparkSession import org.apache.spark.sql.functions._ object Test2 { def ...
- Spark SQL 函数全集
org.apache.spark.sql.functions是一个Object,提供了约两百多个函数. 大部分函数与Hive的差不多. 除UDF函数,均可在spark-sql中直接使用. 经过impo ...
- Spark SQL内置函数
Spark SQL内置函数官网API:http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.fun ...
- Spark Sql的UDF和UDAF函数
Spark Sql提供了丰富的内置函数供猿友们使用,辣为何还要用户自定义函数呢?实际的业务场景可能很复杂,内置函数hold不住,所以spark sql提供了可扩展的内置函数接口:哥们,你的业务太变态了 ...
随机推荐
- 摆脱鼠标系列 - vscode 新建终端 默认最大化显示
摆脱鼠标系列 - vscode 新建终端 默认最大化显示 实现 搜索 opens max 改成 always
- centos 添加 公钥,root不用输入密码 ssh-keygen
centos 添加 公钥,root不用输入密码 ssh-keygen -t rsa -C "yourEmail" 一通回车后,生成 C:\Users\Reciter/.ssh/id ...
- docker 资料整理
docker 资料整理 基础概念 docker deamon 守护系统:简单理解就是docker的软件系统,管控这容器的开关. docker容器:从镜像启动到内存中形成动态运行,从编程角度,如果镜像是 ...
- Dreamweaver基础教程:学习JavaScript
目录 简介 用法 输出 语法 字面量 变量 操作符 语句 关键字 注释 数据类型 函数 函数表达式 Function() 构造函数 自调用函数 箭头函数 arguments 对象 使用构造函数调用函数 ...
- makefile 编写要点
PS:要转载请注明出处,本人版权所有. PS: 这个只是基于<我自己>的理解, 如果和你的原则及想法相冲突,请谅解,勿喷. 前置说明 本文作为本人csdn blog的主站的备份.(Bl ...
- linux系统必备软件
linux系统必备软件 需要配置好epel源 必须安装的工具 tree vim wget bash-completion bash-completion-extras lrzsz net-tools ...
- JavaScript实现防抖与节流
1. 引言 有这么一种场景:某个页面表单按钮设置了点击提交事件,有时因为网络不好,点击后后台服务端很久才返回信息,然而用户因等待许久已经多次点击导致多次发送数据,实际上服务器只需要一次发送的数据即可 ...
- 记一次 .NET某游戏后端API服务 CPU爆高分析
一:背景 1. 讲故事 前几天有位朋友找到我,说他们的API服务程序跑着跑着CPU满了降不下去,让我帮忙看下怎么回事,现在貌似民间只有我一个人专注dump分析,还是申明一下我dump分析是免费的,如果 ...
- Scala 不可变Map
1 package chapter07 2 3 object Test08_ImmutableMap { 4 def main(args: Array[String]): Unit = { 5 // ...
- #线段树分治,背包#CF601E A Museum Robbery
题目 有 \(n\) 个展品正在被展览,每一个展品都有一价值 \(v\) 个和一个混乱度 \(w\) ,现在有 \(m\) 次操作: 1 \(v\) \(w\) :加入一个新的展品,价值为\(v\), ...