簡體   English   中英

使用ReduceByKey對值列表進行分組

[英]Using ReduceByKey to group list of values

我想將每個鍵的值列表進行分組,並且正在執行以下操作:

sc.parallelize(Array(("red", "zero"), ("yellow", "one"), ("red", "two"))).groupByKey().collect.foreach(println)

(red,CompactBuffer(zero, two))
(yellow,CompactBuffer(one))

但是我注意到Databricks的博客文章,建議不要對大型數據集使用groupByKey。

避免使用GroupByKey

有沒有辦法使用reduceByKey達到相同的結果?

我試過了,但它是在串聯所有值。 順便說一句,就我而言,鍵和值都是字符串類型。

sc.parallelize(Array(("red", "zero"), ("yellow", "one"), ("red", "two"))).reduceByKey(_ ++ _).collect.foreach(println)

(red,zerotwo)
(yellow,one)

使用aggregateByKey

 sc.parallelize(Array(("red", "zero"), ("yellow", "one"), ("red", "two")))
.aggregateByKey(ListBuffer.empty[String])(
        (numList, num) => {numList += num; numList},
         (numList1, numList2) => {numList1.appendAll(numList2); numList1})
.mapValues(_.toList)
.collect()

scala> Array[(String, List[String])] = Array((yellow,List(one)), (red,List(zero, two)))

這個答案對細節aggregateByKey此鏈接背后使用可變數據集的理由ListBuffer

編輯:

Is there a way to achieve the same result using reduceByKey?

上面的實際上在性能上更差,請查看@ zero323的評論以獲取詳細信息。

sc.parallelize(Array(("red", "zero"), ("yellow", "one"), ("red", "two")))
.map(t => (t._1,List(t._2)))
.reduceByKey(_:::_)
.collect()
Array[(String, List[String])] = Array((red,List(zero, two)), (yellow,List(one)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM