不一样的map和reduce操作:

来自需求:对数据进行map reduceByKey ,sortByKey操作,但是要进行运算的是hash值,但是还有其他的字段需要保留,以便进行后续的join等操作。这时候,可以考虑拼接的方法,在hash值后面用下划线等拼接id等其他的数据,但是记得顺序才行,然后这样的话 进行map,reduceByKey等算子操作的时候,仍能得到想要的结果,最后sortByKey等操作也没什么问题,只不过传送的数据,一次拼接传递过去。

论坛的神回复,可以参考下。

scala版本的

scala> val cm = c.map(e => (e._1, (e._2, 0)))

cm: org.apache.spark.rdd.RDD[(String, (Int, Int))] = MapPartitionsRDD[25] at map at <console>:23
 
scala> val cr = cm.reduceByKey((e1, e2) => (e1._1 + e2._1, e1._1/2 + e2._1/2))
cr: org.apache.spark.rdd.RDD[(String, (Int, Int))] = ShuffledRDD[26] at reduceByKey at <console>:25
 
scala> val cz = cr.map(e => (e._1, e._2._1, e._2._2))
cz: org.apache.spark.rdd.RDD[(String, Int, Int)] = MapPartitionsRDD[27] at map at <console>:27
 
scala> cz.collect
res15: Array[(String, Int, Int)] = Array((b,3,1), (a,6,2), (c,1,0))
 
scala> val c = sc.parallelize(List(("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("c", 1)))

c: org.apache.spark.rdd.RDD[(String, Int)] = ParallelCollectionRDD[28] at parallelize at <console>:21


java版本的:

JavaPairRDD<String, String> rdd1 = lines.mapToPair(new PairFunction<String, String, String>() {

@Override
public Tuple2<String, String> call(String arg0) throws Exception {
String temp = arg0.split(" ")[0];
String temp2 = arg0.split(" ")[1];
String temp3 = arg0.split(" ")[2];
return new Tuple2<String, String>(temp, temp2 + "-" + temp3 );

}
});

JavaPairRDD<String, String> rdd2 = rdd1.reduceByKey(new Function2<String, String, String>() {

@Override
public String call(String arg0, String arg1) throws Exception {
int a = Integer.parseInt(arg0.split("-")[0]);
int a2 = Integer.parseInt(arg1.split("-")[0]);
String aa = String.valueOf(a+a2);
int b = Integer.parseInt(arg0.split("-")[1]);
int b2 = Integer.parseInt(arg1.split("-")[1]);
String bb = String.valueOf(b+b2);
return aa + "-" + bb;
}
});

JavaRDD<String> rdd3 = rdd2.map(new Function<Tuple2<String,String>, String>() {

@Override
public String call(Tuple2<String, String> arg0) throws Exception {
String lines = arg0._1() + " " + arg0._2.split("-")[0] + " " + arg0._2.split("-")[1];
return lines;
}
});

System.out.println(rdd3.collect());

输入
num 10 20
num 11 22
name 22 33
cmj 332 21
输出
[cmj 332 21, num 21 42, name 22 33]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mtj66

看心情

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值