天天看点

Spark基本的RDD算子之groupBy,groupByKey,mapValues

1. groupby

def groupBy[K: ClassTag](f: T => K): RDD[(K, Iterable[T])]
def groupBy[K: ClassTag](f: T => K, numPartitions: Int): RDD[(K, Iterable[T])]
def groupBy[K: ClassTag](f: T => K, p: Partitioner): RDD[(K, Iterable[T])]           

groupBy算子接收一个函数,这个函数返回的值作为key,然后通过这个key来对里面的元素进行分组。

val a = sc.parallelize(1 to 9, 3)
a.groupBy(x => { if (x % 2 == 0) "even" else "odd" }).collect
//返回的even或者odd字符串作为key来group RDD里面的值,
res42: Array[(String, Seq[Int])] = Array((even,ArrayBuffer(2, 4, 6, 8)), (odd,ArrayBuffer(1, 3, 5, 7, 9)))           

2. groupbykey

def groupByKey(): RDD[(K, Iterable[V])]
def groupByKey(numPartitions: Int): RDD[(K, Iterable[V])]
def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])]
           

这个算子和group类似,不过和它不同的是他不接收一个函数,而是直接将键值对类型的数据的key作为group的key 值。同样的,他也可以接收其他参数比如说partitioner

val a = sc.parallelize(List("dog", "tiger", "lion", "cat", "spider", "eagle"), 2)
val b = a.keyBy(_.length) //将字符串的长度作为key值。
b.groupByKey.collect //根据相同key值来进行group操作

res11: Array[(Int, Seq[String])] = Array((4,ArrayBuffer(lion)), (6,ArrayBuffer(spider)), (3,ArrayBuffer(dog, cat)), (5,ArrayBuffer(tiger, eagle)))
           

3.mapValues

同基本转换操作中的map,只不过mapValues是针对[K,V]中的V值进行map操作。

val a = sc.parallelize(List("dog", "tiger", "lion", "cat", "panther", " eagle"), 2)  
val b = a.map(x => (x.length, x))  
b.mapValues("x" + _ + "x").collect  



//结果 
Array( 
(3,xdogx), 
(5,xtigerx), 
(4,xlionx), 
(3,xcatx), 
(7,xpantherx), 
(5,xeaglex) 
)           

继续阅读