大数据Spark(八十):Action行动算子fold和aggregate使用案例

文章目录

Action行动算子fold和aggregate使用案例

一、fold使用案例

二、aggregate使用案例


Action行动算子fold和aggregate使用案例

一、fold使用案例

fold用于对RDD中的元素进行聚合操作,最终返回一个结果。类似reduce算子,但与reduce不同的是其可以对每个分区中的数据提供一个初始值,让分区中的数据与该初始值进行聚合,最终该初始值还会与各个分区的结果再次聚合。

fold的函数签名如下:

Scala 复制代码
def fold(zeroValue: T)(op: (T, T) => T): T
  • zeroValue:聚合操作的初始值,类型为 T。
  • op:用于合并元素的二元操作函数。

fold的工作原理:在每个分区内,fold 使用初始值 zeroValue 和二元操作函数 op,将该分区内的所有元素进行聚合。在所有分区内的聚合完成后,fold 将各分区的结果与初始值 zeroValue 一起,使用相同的二元操作函数 op 进行全局聚合,得到最终结果。

Java代码:

java 复制代码
SparkConf conf = new SparkConf().setMaster("local").setAppName("FoldTest");
JavaSparkContext sc = new JavaSparkContext(conf);

JavaRDD<String> rdd = sc.parallelize(Arrays.asList("a","b","c","d","e","f"), 3);
rdd.mapPartitionsWithIndex(new Function2<Integer, Iterator<String>, Iterator<String>>() {
    @Override
    public Iterator<String> call(Integer index, Iterator<String> iter) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        while (iter.hasNext()) {
            String next = iter.next();
            list.add("rdd partition index: " + index + " current value: " + next);
        }
        return list.iterator();
    }
},true).foreach(x-> System.out.println(x));

/**
 * 0号分区:a b
 * 1号分区:c d
 * 2号分区:e f
 *
 * 0号分区:hello~a~b
 * 1号分区:hello~c~d
 * 2号分区:hello~e~f
 *
 * 最终结果:hello~hello~a~b~hello~c~d~hello~e~f
 */
String str = rdd.fold("hello", new Function2<String, String, String>() {
    @Override
    public String call(String v1, String v2) throws Exception {
        return v1 + "~" + v2;
    }
});

System.out.println(str);
sc.stop();

Scala代码:

Scala 复制代码
val conf = new SparkConf().setMaster("local").setAppName("FoldTest")
val sc = new SparkContext(conf)

val rdd: RDD[String] = sc.parallelize(List("a", "b", "c", "d", "e", "f"), 3)
rdd.mapPartitionsWithIndex((index, iter) => {
  val list = new ListBuffer[String]()
  while (iter.hasNext) {
    list.append(s"rdd partition index: $index ,current value: ${iter.next()}")
  }
  list.iterator
}).foreach(println)

/**
 * 0号分区:a b
 * 1号分区:c d
 * 2号分区:e f
 * map端聚合:
 * 0号分区:hello~a~b
 * 1号分区:hello~c~d
 * 2号分区:hello~e~f
 *
 * 最终结果:hello~hello~a~b~hello~c~d~hello~e~f
 */
val result: String = rdd.fold("hello")((v1, v2) => {
  v1 + "~" + v2
})

println(result)

sc.stop()

二、aggregate使用案例

aggregate用于对RDD中的元素进行聚合操作,最终返回一个结果。与 fold 和 reduce 等算子不同,aggregate 允许用户分别定义分区内和分区间的聚合函数,提供了更大的灵活性。

aggregate函数签名如下:

Scala 复制代码
def aggregate[U: ClassTag](zeroValue: U)(seqOp: (U, T) => U, combOp: (U, U) => U): U
  • zeroValue:聚合操作的初始值,类型为 U。
  • seqOp:分区内的聚合函数,用于将分区内的元素与累加器进行合并,类型为 (U, T) => U。
  • combOp:分区间的聚合函数,用于将不同分区的累加器结果进行合并,类型为 (U, U) => U

aggregate工作原理:在每个分区内,使用初始值 zeroValue 和函数 seqOp,将该分区内的所有元素进行聚合。在所有分区内的聚合完成后,使用初始值 zeroValue 和函数 combOp,将各分区的结果进行全局聚合,得到最终结果。

Java代码:

java 复制代码
SparkConf conf = new SparkConf().setMaster("local").setAppName("AggregateTest");
JavaSparkContext sc = new JavaSparkContext(conf);

JavaRDD<String> rdd = sc.parallelize(Arrays.asList("a","b","c","d","e","f"), 3);
rdd.mapPartitionsWithIndex(new Function2<Integer, Iterator<String>, Iterator<String>>() {
    @Override
    public Iterator<String> call(Integer index, Iterator<String> iter) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        while (iter.hasNext()) {
            String next = iter.next();
            list.add("rdd partition index: " + index + " current value: " + next);
        }
        return list.iterator();
    }
},true).foreach(x-> System.out.println(x));

/**
 * 0号分区:a b
 * 1号分区:c d
 * 2号分区:e f
 *
 * map端聚合:
 * 0号分区:hello~a~b
 * 1号分区:hello~c~d
 * 2号分区:hello~e~f
 *
 * 最终结果:hello@hello~a~b@hello~c~d@hello~e~f
 */
String result = rdd.aggregate("hello", new Function2<String, String, String>() {

    @Override
    public String call(String s1, String s2) throws Exception {
        return s1 + "~" + s2;
    }
}, new Function2<String, String, String>() {
    @Override
    public String call(String s1, String s2) throws Exception {
        return s1 + "@" + s2;
    }
});

System.out.println(result);
sc.stop();

Scala代码:

Scala 复制代码
val conf = new SparkConf().setMaster("local").setAppName("FoldTest")
val sc = new SparkContext(conf)

val rdd: RDD[String] = sc.parallelize(List("a", "b", "c", "d", "e", "f"), 3)
rdd.mapPartitionsWithIndex((index, iter) => {
  val list = new ListBuffer[String]()
  while (iter.hasNext) {
    list.append(s"rdd partition index: $index ,current value: ${iter.next()}")
  }
  list.iterator
}).foreach(println)

val result: String = rdd.aggregate("hello")(
  (v1, v2) => {
    v1 + "~" + v2
  },
  (v1, v2) => {
    v1 + "@" + v2
  }
)

println(result)
sc.stop()

  • 📢博客主页:https://lansonli.blog.csdn.net
  • 📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
  • 📢本文由 Lansonli 原创,首发于 CSDN博客🙉
  • 📢停下休息的时候不要忘了别人还在奔跑,希望大家抓紧时间学习,全力奔赴更美好的生活✨
相关推荐
九河云3 小时前
5秒开服,你的应用部署还卡在“加载中”吗?
大数据·人工智能·安全·机器学习·华为云
Gain_chance3 小时前
36-学习笔记尚硅谷数仓搭建-DWS层数据装载脚本
大数据·数据仓库·笔记·学习
每日新鲜事4 小时前
热销复盘:招商林屿缦岛203套售罄背后的客户逻辑分析
大数据·人工智能
AI架构全栈开发实战笔记5 小时前
Eureka 在大数据环境中的性能优化技巧
大数据·ai·eureka·性能优化
AI架构全栈开发实战笔记5 小时前
Eureka 对大数据领域服务依赖关系的梳理
大数据·ai·云原生·eureka
自挂东南枝�5 小时前
政企舆情大数据服务平台的“全域洞察中枢”
大数据
weisian1516 小时前
Elasticsearch-1--什么是ES?
大数据·elasticsearch·搜索引擎
LaughingZhu6 小时前
Product Hunt 每日热榜 | 2026-02-08
大数据·人工智能·经验分享·搜索引擎·产品运营
玄同7656 小时前
Git常用命令指南
大数据·git·elasticsearch·gitee·github·团队开发·远程工作
瑞华丽PLM8 小时前
电子行业国产PLM系统功能差异化对比表
大数据·plm·国产plm·瑞华丽plm·瑞华丽