spark cogroup算子

本文通过一个具体的示例,详细对比了Spark中Cogroup与Join算子的不同之处,特别是在处理具有多个值的键时,Cogroup如何返回键与值的可迭代集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

java

 1 /** 
 2  *cogroup与join算子不同的是如果rdd中的一个key,对应多个value,则返回<Iterable<key>,Iterable<value>>
 3  *@author Tele
 4  */
 5 public class CogroupDemo {
 6     private static SparkConf conf = new SparkConf().setMaster("local").setAppName("congroupdemo");
 7     private static JavaSparkContext jsc = new JavaSparkContext(conf);
 8     public static void main(String[] args) {
 9         //每个学生有多门成绩
10         List<Tuple2<Integer,String>> studentList = Arrays.asList(
11                                                     new Tuple2<Integer,String>(1,"tele"), 
12                                                     new Tuple2<Integer,String>(1,"xx"), 
13                                                     new Tuple2<Integer,String>(2,"yeye"), 
14                                                     new Tuple2<Integer,String>(3,"wyc")
15                                                    );
16 
17         List<Tuple2<Integer,Integer>> scoreList = Arrays.asList(
18                                                   new Tuple2<Integer,Integer>(1,100),
19                                                   new Tuple2<Integer,Integer>(1,110),
20                                                   new Tuple2<Integer,Integer>(1,120),
21                                                   new Tuple2<Integer,Integer>(2,90),
22                                                   new Tuple2<Integer,Integer>(2,60),
23                                                   new Tuple2<Integer,Integer>(2,50),
24                                                   new Tuple2<Integer,Integer>(3,70),
25                                                   new Tuple2<Integer,Integer>(3,70)
26                                                   );
27         
28         JavaPairRDD<Integer, String> studentRDD = jsc.parallelizePairs(studentList);
29         JavaPairRDD<Integer, Integer> scoreRDD = jsc.parallelizePairs(scoreList);
30         
31         JavaPairRDD<Integer, Tuple2<Iterable<String>, Iterable<Integer>>> result = studentRDD.cogroup(scoreRDD);
32         result.foreach(new VoidFunction<Tuple2<Integer,Tuple2<Iterable<String>,Iterable<Integer>>>>() {
33             
34             private static final long serialVersionUID = 1L;
35 
36             @Override
37             public void call(Tuple2<Integer, Tuple2<Iterable<String>, Iterable<Integer>>> t) throws Exception {
38                 System.out.println("学号:" + t._1);
39                 System.out.println("姓名:" + t._2._1);
40                 System.out.println("成绩:" + t._2._2);
41                 
42             /*    System.out.print("成绩:[");
43                 t._2._2.forEach(i->System.out.print(i + ","));
44                 System.out.println("]");
45                 System.out.println("====================");*/
46                 
47             }
48         });
49         
50         jsc.close();
51     }
52 }

scala

 1 object CogroupDemo {
 2     def main(args: Array[String]): Unit = {
 3         val conf = new SparkConf().setMaster("local").setAppName("cogroupdemo");
 4         val sc = new SparkContext(conf);
 5         
 6         val studentArr = Array((1,"tele"),(2,"yeye"),(3,"wyc"));
 7         val scoreArr = Array((1,100),(1,200),(2,80),(2,300),(3,100));
 8         
 9         val studentRDD = sc.parallelize(studentArr,1);
10         val scoreRDD = sc.parallelize(scoreArr,1);
11         
12         val result = studentRDD.cogroup(scoreRDD);
13         result.foreach(t=>{
14           println("学号:" + t._1);
15           println("姓名:" + t._2._1.mkString(" "));
16           println("成绩:" + t._2._2.mkString(","));
17           println("============");
18         })
19     }
20 }

 

转载于:https://www.cnblogs.com/tele-share/p/10268576.html

### Spark Core 算子概述 Spark Core 中的算子分为两大类:Transformation 和 Action。其中,Transformation 是一种惰性操作(Lazy Evaluation),只有当遇到 Action 类型的操作时才会真正触发计算。 #### 一、Transformation 算子 以下是常见的 Transformation 算子及其功能: 1. **map(func)** 对 RDD 的每一个元素应用函数 `func` 并返回一个新的 RDD[^4]。 2. **flatMap(func)** 类似于 map,但是会将结果扁平化处理,适用于输入为集合的情况。 3. **filter(func)** 返回一个新的 RDD,该 RDD 包含满足条件的原 RDD 元素。 4. **groupByKey()** 将键值对形式的数据按 key 进行分组,返回的结果是一个新的 RDD[(K, Iterable[V])] 形式的数据集。 5. **reduceByKey(func)** 针对键值对类型的 RDD,在相同 key 下通过指定的 func 函数聚合 value 值[^3]。 6. **join(otherDataset, [numPartitions])** 执行两个具有相同 Key 数据集之间的内连接操作。 7. **cogroup(otherDataset, [numPartitions])** 多个数据源按照相同的 Key 聚合到一起。 8. **cartesian(otherDataset)** 计算当前 RDD 和其他 RDD 的笛卡尔积。 9. **union(otherDataset)** 合并两个 RDD 成为一个新 RDD。 10. **distinct([numPartitions])** 删除重复项后的 RDD。 --- #### 二、Action 算子 以下是常见的 Action 算子及其功能: 1. **reduce(func)** 使用给定的函数 `func` 来聚集整个 RDD 的所有元素[^1]。 2. **collect()** 将分布式存储的 RDD 收集到 Driver 上形成数组。 3. **count()** 统计 RDD 中的元素总数。 4. **first()** 获取 RDD 中的第一个元素。 5. **take(n)** 取出前 n 个元素作为数组返回。 6. **takeOrdered(n)(implicit ord: Ordering[T])** 按照某种顺序取出前 n 个元素。 7. **saveAsTextFile(path)** 将 RDD 存储为文本文件。 8. **foreach(func)** 对 RDD 的每个元素逐一调用传入的函数 `func`[^2]。 9. **aggregate(zeroValue)(seqOp, combOp)** 提供更灵活的方式来进行聚合运算,允许定义不同的分区内和分区间逻辑。 10. **fold(zeroValue)(op)** 功能类似于 reduce,但提供了初始值 zeroValue。 11. **countByValue() / countByKey()** 分别用于统计单个值或者键对应的数量。 --- #### 三、代码示例 以下是一些典型算子的实际应用场景代码片段: ```scala // 创建一个简单的 RDD val rdd = sc.parallelize(Array(1, 2, 3, 4)) // 使用 map 算子实现平方变换 rdd.map(x => x * x).collect() // 使用 filter 实现筛选偶数 rdd.filter(_ % 2 == 0).collect() // 使用 reduce 计算总和 rdd.reduce((a, b) => a + b) // 使用 foreach 输出每个元素 rdd.foreach(num => println(s"Number is $num")) ``` 上述代码展示了如何利用基本的 Transformation 和 Action 算子完成简单任务。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值