Created
March 22, 2019 12:29
-
-
Save explicite/fba856d882f8f71c2d9e626d48a4b55b to your computer and use it in GitHub Desktop.
reduce by key on DS in Spark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def reduceBy[A, B](merge: (A, A) => A)( | |
by: A => B | |
)(ds: Dataset[A])(implicit session: SparkSession, encoderA: Encoder[A], encoderB: Encoder[B]): Dataset[A] = { | |
def reducePartition(iter: Iterator[A]): Iterator[A] = { | |
iter.toList | |
.groupBy(by) | |
.mapValues(values => values.reduce(merge)) | |
.values | |
.toIterator | |
} | |
ds.mapPartitions(reducePartition) | |
.groupByKey(by) | |
.reduceGroups(merge) | |
.map { case (_, updates) => updates } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment