7 RDD常用算子(2)(rd算法)
itomcoil 2025-07-02 21:22 11 浏览
filter()
def filter(f: T => Boolean): RDD[T]
函数说明
将数据根据指定的规则进行筛选过滤,符合规则的数据保留,不符合规则的数据丢弃。当数据进行筛选过滤后,分区不变,但是分区内的数据可能不均衡,生产环境下,可能会出现数据倾斜。
object RDD_Transform_filter {
def main(args: Array[String]): Unit = {
// Step1: 准备环境
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
// Step2: 算子 filter
val rdd = sc.makeRDD(List(1, 2, 3, 4))
val filterRDD = rdd.filter(num => num % 2 != 0)
filterRDD.collect.foreach(println)
// Step3: 关闭环境
sc.stop()
}
}
输出结果:
1
3
应用场景,日志过滤。
object RDD_Transform_filter_LogFilter {
def main(args: Array[String]): Unit = {
// Step1: 准备环境
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
// Step2: 算子 groupBy
val rdd = sc.textFile("datas/apache.log")
var timeRDD = rdd.filter(
line => {
val data = line.split(" ")
val time = data(3)
time.startsWith("17/May/2023")
}
).collect().foreach(println)
// Step3: 关闭环境
sc.stop()
}
}
日志内容:
https://gitee.com/wuji1626/bigdata/blob/master/datas/apache.log
输出结果:
220.181.108.112 - - 17/May/2023:02:04:48 +0800 "GET / HTTP/1.1" 200 9603 www.sohu.com
220.181.108.112 - - 17/May/2023:01:04:58 +0800 "GET / HTTP/1.1" 200 9603 www.iqiyi.com
220.181.108.112 - - 17/May/2023:12:04:58 +0800 "GET / HTTP/1.1" 200 9603 www.163.com
sample()
函数签名
def sample(
withReplacement: Boolean,
fraction: Double,
seed: Long = Utils.random.nextLong): RDD[T]
)
参数说明:
抽取数据不放回(伯努利算法)伯努利算法:又叫 0、1 分布。例如扔硬币,要么正面,要么反面。
具体实现:根据种子和随机算法算出一个数和第二个参数设置几率比较,小于第二个参数要,大于不
要
- withReplacement:boolean,抽取的数据不放回,false;
- fraction:Double,抽取的几率,范围在[0,1]之间,0:全不取;1:全取;
- seed:Long,随机数种子。
抽取数据放回(泊松算法)
- withReplacement:boolean,抽取的数据是否放回,true:放回;false:不放回;
- fraction:Double,重复数据的几率,范围大于等于 0.表示每一个元素被期望抽取到的次数,但实际的抽取次数可能远大于期望值;
- seed:Long,随机数种子。
def sample(
withReplacement: Boolean,
fraction: Double,
seed: Long = Utils.random.nextLong): RDD[T]
)
def sample(
withReplacement: Boolean,
fraction: Double,
seed: Long = Utils.random.nextLong): RDD[T] = {
require(fraction >= 0,
s"Fraction must be nonnegative, but got ${fraction}")
withScope {
require(fraction >= 0.0, "Negative fraction value: " + fraction)
if (withReplacement) {
new PartitionwiseSampledRDD[T, T](this, new PoissonSampler[T](fraction), true, seed)
} else {
new PartitionwiseSampledRDD[T, T](this, new BernoulliSampler[T](fraction), true, seed)
}
}
}
函数说明
根据指定的规则从数据集中抽取数据。
object RDD_Transform_sample {
def main(args: Array[String]): Unit = {
// Step1: 准备环境
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
// Step2: 算子 filter
val rdd = sc.makeRDD(List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
println(rdd.sample(
withReplacement = false,
0.4,
1
).collect().mkString(","))
// Step3: 关闭环境
sc.stop()
}
}
输出结果:
2,5,6,8
sample() 算子源码如下,
- 当 withReplacement 为 false 时,会使用 BernoulliSampler() 贝努力(伯努利)算法选取样本,贝努力算法相当于抛硬币,将符合人头或字的数字作为样本返回。
- 当 withReplacement 为 true 时,会使用 PoissonSampler() 离散概率分布算法生成样本。
应用场景:在产生数据倾斜时使用。在 shuffle 的情况下,数据可能出现倾斜,通过 sample() 算子获取一定数量的数据样本观察其中的某些 key 值是否重复的比例过高,如果反复取 sample 对应的 key 都有重复值较多的情况,就说明该 key 可能引起数据倾斜,需要加以处理。
distinct()
函数签名
def distinct()(implicit ord: Ordering[T] = null): RDD[T]
def distinct(numPartitions: Int)(implicit ord: Ordering[T] = null): RDD[T]
函数说明
将数据集中数据去重。
object RDD_Transform_distinct {
def main(args: Array[String]): Unit = {
// Step1: 准备环境
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
// Step2: 算子 distinct
val rdd = sc.makeRDD(List(1, 2, 3, 4, 1, 2, 3, 4))
val distinctRDD = rdd.distinct()
distinctRDD.collect.foreach(println)
// Step3: 关闭环境
sc.stop()
}
}
输出结果:
1
2
3
4
Scala 集合的 distinct 方法,其中通过 HashSet 的方法识别重复值。
default Repr distinct() {
boolean isImmutable = this instanceof scala.collection.immutable.Seq;
if (isImmutable && this.lengthCompare(1) <= 0) {
return this.repr();
} else {
Builder b = this.newBuilder();
HashSet seen = new HashSet();
Iterator it = this.iterator();
boolean different = false;
...
}
RDD 的去重方式,主要看 partitioner 部分,由于 partitioner 默认为 null,因此主要逻辑体现在下述代码行:
case _ => map(x => (x, null)).reduceByKey((x, _) => x, numPartitions).map(_._1)
以数组 List(1, 2, 3, 4, 1, 2, 3, 4) 为例:
- map(x => (x, null)):将数组变为:(1, null),(2, null),(3, null),(4, null),(1, null),(2, null),(3, null),(4, null) 的 tuple 数组;
- reduceByKey((x, _) => x, numPartitions):对 tuple 数组做聚合 (1, null),(1, null),聚合后,key 不变,(null,null),取第一个值,即 null,所以聚合后的结果:(1, null),(2, null),(3, null),(4, null);
- map(_._1):只保留 tuple 中的第一个元素,(1, null),(2, null),(3, null),(4, null) 变回 1, 2, 3, 4。
distinct() 算子的完整源码如下:
def distinct(numPartitions: Int)(implicit ord: Ordering[T] = null): RDD[T] = withScope {
def removeDuplicatesInPartition(partition: Iterator[T]): Iterator[T] = {
// Create an instance of external append only map which ignores values.
val map = new ExternalAppendOnlyMap[T, Null, Null](
createCombiner = _ => null,
mergeValue = (a, b) => a,
mergeCombiners = (a, b) => a)
map.insertAll(partition.map(_ -> null))
map.iterator.map(_._1)
}
partitioner match {
case Some(_) if numPartitions == partitions.length =>
mapPartitions(removeDuplicatesInPartition, preservesPartitioning = true)
case _ => map(x => (x, null)).reduceByKey((x, _) => x, numPartitions).map(_._1)
}
}
coalesce()
函数签名
def coalesce(numPartitions: Int, shuffle: Boolean = false,
partitionCoalescer: Option[PartitionCoalescer] = Option.empty)
(implicit ord: Ordering[T] = null)
: RDD[T]
函数说明
根据数据量缩减分区,用于大数据集过滤后,提高小数据集的执行效率当 spark 程序中,存在过多的小任务的时候,可以通过 coalesce 方法,收缩合并分区,减少分区的个数,减小任务调度成本。
object RDD_Transform_coalesce {
def main(args: Array[String]): Unit = {
// Step1: 准备环境
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
// Step2: 算子 distinct
val rdd = sc.makeRDD(List(1, 2, 3, 4), numSlices = 4)
val coalesceRDD = rdd.coalesce(2)
coalesceRDD.saveAsTextFile("output")
// Step3: 关闭环境
sc.stop()
}
}
生成的分区文件:
[1,2] [3,4]
如果原始数据与分区数据调整成下述的方式,数组有 6 个元素,变化前 3 个分区,变化后 2 个分区。
object RDD_Transform_coalesce {
def main(args: Array[String]): Unit = {
// Step1: 准备环境
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
// Step2: 算子 coalesce
val rdd = sc.makeRDD(List(1, 2, 3, 4, 5, 6), numSlices = 3)
val coalesceRDD = rdd.coalesce(2)
coalesceRDD.saveAsTextFile("output")
// Step3: 关闭环境
sc.stop()
}
}
默认情况下,coalesce() 算子不打乱原始分区,如下图所示,coalesce() 采用的是整个分区合并的方式。
可以通过指定 shuffle 参数的方式,显式让 shuffle 执行。
val coalesceRDD = rdd.coalesce(2, shuffle = true)
指定 shuffle 参数后,分区随机进行打散:
[1,2] [3,4] [5,6] => [1,4,5] [2,3,6]
如果需要扩展分区,可以使用 coalesce() 进行分区扩展,如果不指定 shuffle = true,将无效,只有指定 shuffle = true 才能实现分区扩大。
repartition()
为让 coalesce() 功能更明确,只作为分区缩减,专门增加 repartition() 算子,进行分区扩展。
函数签名
def repartition(numPartitions: Int)(implicit ord: Ordering[T] = null): RDD[T]
函数说明
该操作内部其实执行的是 coalesce 操作,参数 shuffle 的默认值为 true。无论是将分区数多的 RDD 转换为分区数少的 RDD,还是将分区数少的 RDD 转换为分区数多的 RDD,repartition 操作都可以完成,因为无论如何都会经 shuffle 过程。
查看 repartion() 源代码,发现底层就是调用 coalesce() 算子,并默认指定 shuffle = ture。
def repartition(numPartitions: Int)(implicit ord: Ordering[T] = null): RDD[T] = withScope {
coalesce(numPartitions, shuffle = true)
}
sortBy()
根据指定规则对数据进行排序。
函数签名
def sortBy[K](
f: (T) => K,
ascending: Boolean = true,
numPartitions: Int = this.partitions.length)
(implicit ord: Ordering[K], ctag: ClassTag[K]): RDD[T]
函数说明
该操作用于排序数据。在排序之前,可以将数据通过 f 函数进行处理,之后按照 f 函数处理的结果进行排序,默认为升序排列。排序后新产生的 RDD 的分区数与原 RDD 的分区数一致。中间存在 shuffle 的过程。
object RDD_Transform_sortBy {
def main(args: Array[String]): Unit = {
// Step1: 准备环境
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
// Step2: 算子 sortBy
val rdd = sc.makeRDD(List(6, 2, 4, 5, 3, 1), numSlices = 2)
val sortRDD = rdd.sortBy(num => num)
sortRDD.collect().foreach(println)
// Step3: 关闭环境
sc.stop()
}
}
数据的顺序:[6, 2, 4] [5, 3, 1] => [1, 2, 3] [4, 5, 6]
从结果知:sortBy() 算子要进行 shuffle。
应用场景,对 tuple 进行排序。
object RDD_Transform_sortBy_tuple {
def main(args: Array[String]): Unit = {
// Step1: 准备环境
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
val sc = new SparkContext(sparkConf)
// Step2: 算子 sortBy
val rdd = sc.makeRDD(List(("1",1),("11",2),("2",3)), numSlices = 2)
val sortRDD = rdd.sortBy(t=> t._1)
sortRDD.collect().foreach(println)
// Step3: 关闭环境
sc.stop()
}
}
默认会按照字典序进行排序:
(1,1)
(11,2)
(2,3)
若不想按字典序排列,可以进行数据类型转换:
val sortRDD = rdd.sortBy(t=> t._1.toInt)
输出结果:
(1,1)
(2,3)
(11,2)
sortBy() 默认为升序,第二个方式可以改变排序方式:
val sortRDD = rdd.sortBy(t=> t._1,ascending = false)
输出结果,按字典序降序:
(2,3)
(11,2)
(1,1)
相关推荐
- selenium(WEB自动化工具)
-
定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...
- 开发利器丨如何使用ELK设计微服务中的日志收集方案?
-
【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...
- 高并发系统设计:应对每秒数万QPS的架构策略
-
当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...
- 2025 年每个 JavaScript 开发者都应该了解的功能
-
大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...
- JavaScript Array 对象
-
Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...
- Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战
-
刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...
- 动力节点最新JavaScript教程(高级篇),深入学习JavaScript
-
JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...
- 一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code
-
当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...
- 「晚安·好梦」努力只能及格,拼命才能优秀
-
欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...
- JavaScript 中 some 与 every 方法的区别是什么?
-
大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...
- 10个高效的Python爬虫框架,你用过几个?
-
小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...
- 12个高效的Python爬虫框架,你用过几个?
-
实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...
- pip3 install pyspider报错问题解决
-
运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...
- PySpider框架的使用
-
PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...
- 「机器学习」神经网络的激活函数、并通过python实现激活函数
-
神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...
- 一周热门
- 最近发表
- 标签列表
-
- ps图案在哪里 (33)
- super().__init__ (33)
- python 获取日期 (34)
- 0xa (36)
- super().__init__()详解 (33)
- python安装包在哪里找 (33)
- linux查看python版本信息 (35)
- python怎么改成中文 (35)
- php文件怎么在浏览器运行 (33)
- eval在python中的意思 (33)
- python安装opencv库 (35)
- python div (34)
- sticky css (33)
- python中random.randint()函数 (34)
- python去掉字符串中的指定字符 (33)
- python入门经典100题 (34)
- anaconda安装路径 (34)
- yield和return的区别 (33)
- 1到10的阶乘之和是多少 (35)
- python安装sklearn库 (33)
- dom和bom区别 (33)
- js 替换指定位置的字符 (33)
- python判断元素是否存在 (33)
- sorted key (33)
- shutil.copy() (33)