score:31

Accepted answer

following your code:

val bykey = x.map({case (id,uri,count) => (id,uri)->count})

you could do:

val reducedbykey = bykey.reducebykey(_ + _)

scala> reducedbykey.collect.foreach(println)
((a,d),1)
((a,b),2)
((c,b),1)

pairrddfunctions[k,v].reducebykey takes an associative reduce function that can be applied to the to type v of the rdd[(k,v)]. in other words, you need a function f[v](e1:v, e2:v) : v . in this particular case with sum on ints: (x:int, y:int) => x+y or _ + _ in short underscore notation.

for the record: reducebykey performs better than groupbykey because it attemps to apply the reduce function locally before the shuffle/reduce phase. groupbykey will force a shuffle of all elements before grouping.

score:0

the syntax is below:

reducebykey(func: function2[v, v, v]): javapairrdd[k, v],

which says for the same key in an rdd it takes the values (which will be definitely of same type) performs the operation provided as part of function and returns the value of same type as of parent rdd.

score:6

your origin data structure is: rdd[(string, string, int)], and reducebykey can only be used if data structure is rdd[(k, v)].

val kv = x.map(e => e._1 -> e._2 -> e._3) // kv is rdd[((string, string), int)]
val reduced = kv.reducebykey(_ + _)       // reduced is rdd[((string, string), int)]
val kv2 = reduced.map(e => e._1._1 -> (e._1._2 -> e._2)) // kv2 is rdd[(string, (string, int))]
val grouped = kv2.groupbykey()            // grouped is rdd[(string, iterable[(string, int)])]
grouped.foreach(println)

Related Query

More Query from same tag