tutorial spark org examples example scala hadoop apache-spark mapreduce apache-spark-sql

scala - spark - Usar ReduceByKey para agrupar la lista de valores



spark java hadoop (1)

Use 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)))

Consulte esta respuesta para conocer los detalles en aggregateByKey , este enlace para la justificación del uso de un conjunto de datos mutable ListBuffer .

EDITAR:

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

Lo anterior es en realidad peor en rendimiento, por favor vea los comentarios de @ zero323 para más detalles.

Quiero agrupar la lista de valores por clave y estaba haciendo algo como esto:

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

Pero noté una publicación de blog de Databricks y estoy recomendando no usar groupByKey para grandes conjuntos de datos.

Evitar GroupByKey

¿Hay alguna manera de lograr el mismo resultado usando reduceByKey?

Intenté esto pero está concatenando todos los valores. Por cierto, para mi caso, tanto la clave como el valor son tipo de cadena.

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