spark reducebykey计算多个value的值?如图

Yt_Sports 2016-04-09 11:49:43
...全文
5052 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
xxbb339 2019-04-25
  • 打赏
  • 举报
回复
基本思路: num 10 20 转成(num, (10, 20)) key为num 然后按照key进行求和, (key, (10+10,20+20) map(x=>(x.1,(x.2, x.3))).reduceBykey((s, h)=>(s._1+h._1, s._2+h._2))
  • 打赏
  • 举报
回复
引用 5 楼 止鱼 的回复:
.reduceByKey((x,y)=> (x._1+x._2,y._1+y._2), 10)
写错了,应该是: .reduceByKey((x,y)=>(x._1+y._1,x._2+y._2)) 楼上是对的
  • 打赏
  • 举报
回复
.reduceByKey((x,y)=> (x._1+x._2,y._1+y._2), 10)
夏末的初雪 2018-02-23
  • 打赏
  • 举报
回复
.reduceByKey((x,y)=>(x._1+y._1,x._2+y._2))
gikod 2016-05-16
  • 打赏
  • 举报
回复
用不着字符串拼接,先用map转换一下类型就好
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
闸北米 2016-05-13
  • 打赏
  • 举报
回复
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]
鹏89 2016-05-12
  • 打赏
  • 举报
回复
引用 楼主 Yt_Sports 的回复:
reducebykey 只能是key-value的形式,你这里是三元tuple了,你可以先处理一行之后再reducebykey

1,258

社区成员

发帖
与我相关
我的任务
社区描述
Spark由Scala写成,是UC Berkeley AMP lab所开源的类Hadoop MapReduce的通用的并行计算框架,Spark基于MapReduce算法实现的分布式计算。
社区管理员
  • Spark
  • shiter
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧