Histogram in Spark (1)

Spark’s DoubleRDDFunctions provide a histogram function for RDD[Double]. However there are no histogram function for RDD[String]. Here is a quick exercise for doing it. We will use immutable Map in this exercise.

Create a dummy RDD[String] and apply the aggregate method to calculate histogram

1
2
3
4
5
scala> val d = sc.parallelize(( 1 to 10 ).map( _ % 3 ).map( "val" + _ .toString))
scala> d.aggregate(Map[String,Int]())(
      | (m,c) = >m.updated(c,m.getOrElse(c, 0 )+ 1 ),
      | (m,n) = >(m / : n){ case (map,(k,v)) = >map.updated(k,v+map.getOrElse(k, 0 ))}
      | )

The 2nd function of aggregate method is to merge 2 maps. We can actually define a Scala function

1
2
3
scala> def mapadd[T](m : Map[T,Int],n : Map[T,Int]) = {
      | (m / : n){ case (map,(k,v)) = >map.updated(k,v+map.getOrElse(k, 0 ))}
      | }

It combine the histogram on the different partitions together

1
2
scala> mapadd(Map( "a" -> 1 , "b" -> 2 ),Map( "a" -> 2 , "c" -> 1 ))
res 3 : scala.collection.mutable.Map[String,Int] = Map(b -> 2 , a -> 3 , c -> 1 )

Use mapadd we can rewrite the aggregate step

1
2
3
4
scala> d.aggregate(Map[String,Int]())(
      | (m,c) = >m.updated(c,m.getOrElse(c, 0 )+ 1 ),
      | mapadd( _ , _ )
      | )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值