【大数据学习 | Spark-Core】关于distinct算子

只有shuffle类的算子能够修改分区数量,这些算子不仅仅存在自己的功能,比如分组算子groupBy,它的功能是分组但是却可以修改分区。

而这里我们要讲的distinct算子也是一个shuffle类的算子。即可以修改分区。

Scala 复制代码
scala> val arr = Array(1,1,2,2,3,3,4,4,5,5,6,6)
arr: Array[Int] = Array(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6)

scala> val rdd = sc.makeRDD(arr)
rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[19] at makeRDD at <console>:26

scala> rdd.distinct
res29: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[22] at distinct at <console>:26

scala> res29.collect
res30: Array[Int] = Array(1, 2, 3, 4, 5, 6)   

去重使用方式很简单。

但是原理却不简单。

思考一下怎么进行数据去重的?

这个同sql和mr是一样,都是分组完毕取出key的值。(即先groupBy,再map)

Scala 复制代码
scala> arr
res31: Array[Int] = Array(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6)

scala> sc.makeRDD(arr)
res32: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[23] at makeRDD at <console>:27

scala> res32.groupBy(t=> t)
res33: org.apache.spark.rdd.RDD[(Int, Iterable[Int])] = ShuffledRDD[25] at groupBy at <console>:26

scala> res33.map(_._1).collect
res34: Array[Int] = Array(1, 2, 3, 4, 5, 6)

distinct的底层实现是通过分组实现,分组存在shuffle,所以可以修改分区数量,所以切分阶段

能够修改分区数量的算子必须存在shuffle。但是如果人为不去设定分区数量,下游的分区数量和上游相同。

可以修改分区数量

Scala 复制代码
scala> arr
res35: Array[Int] = Array(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6)

scala> sc.makeRDD(arr,3)
res36: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[27] at makeRDD at <console>:27

scala> res36.distinct(6)
res37: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[30] at distinct at <console>:26

scala> res37.partitions.size
res38: Int = 6

scala> res36.distinct(2)
res39: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[33] at distinct at <console>:26

scala> res39.partitions.size
res40: Int = 2

distinct 可以增加也可以减少分区数量

相关推荐
点赋科技35 分钟前
沙市区举办资本市场赋能培训会 点赋科技分享智能消费新实践
大数据·人工智能
YSGZJJ1 小时前
股指期货技术分析与短线操作方法介绍
大数据·人工智能
Doker 多克1 小时前
Flink CDC —部署模式
大数据·flink
Guheyunyi1 小时前
监测预警系统重塑隧道安全新范式
大数据·运维·人工智能·科技·安全
懒羊羊大王呀1 小时前
Ubuntu20.04中 Redis 的安装和配置
linux·redis
Channing Lewis2 小时前
如果科技足够发达,是否还需要维持自然系统(例如生物多样性)中那种‘冗余’和‘多样性’,还是可以只保留最优解?
大数据·人工智能·科技
禺垣2 小时前
区块链技术概述
大数据·人工智能·分布式·物联网·去中心化·区块链
John Song3 小时前
Redis 集群批量删除key报错 CROSSSLOT Keys in request don‘t hash to the same slot
数据库·redis·哈希算法
IvanCodes3 小时前
七、Sqoop Job:简化与自动化数据迁移任务及免密执行
大数据·数据库·hadoop·sqoop