Take the top N after groupBy and treat them as RDD

I want to get the top Nelements after groupByKey RDDand convert the type topNPerGroup(below) to RDD[(String, Int)]where the List[Int]values ​​areflatten

data -

val data = sc.parallelize(Seq("foo"->3, "foo"->1, "foo"->2,
                              "bar"->6, "bar"->5, "bar"->4))

The top Nelements for each group are calculated as:

val topNPerGroup: RDD[(String, List[Int]) = data.groupByKey.map { 
   case (key, numbers) => 
       key -> numbers.toList.sortBy(-_).take(2)
}

Result

(bar,List(6, 5))
(foo,List(3, 2))

which was printed

topNPerGroup.collect.foreach(println)

If I have reached, topNPerGroup.collect.foreach(println)will generate ( expected result! )

(bar, 6)
(bar, 5)
(foo, 3)
(foo, 2)
+4
source share
3 answers

Your question is a bit confusing, but I think it does what you are looking for:

val flattenedTopNPerGroup = 
    topNPerGroup.flatMap({case (key, numbers) => numbers.map(key -> _)})

and in repl it gives what you want:

flattenedTopNPerGroup.collect.foreach(println)
(foo,3)
(foo,2)
(bar,6)
(bar,5)
+4
source

, , K , (key: Int, (domain: String, count: Long)). , - / groupByKey, .

(K, V) (K, Iterable). . , (, ) , reduceByKey combByKey .

, Iterable (K, Iterable<V>) , > 1 , N .

, . , combByKey , .

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._

object TopNForKey {

  var SampleDataset = List(
    (1, ("apple.com", 3L)),
    (1, ("google.com", 4L)),
    (1, ("stackoverflow.com", 10L)),
    (1, ("reddit.com", 15L)),
    (2, ("slashdot.org", 11L)),
    (2, ("samsung.com", 1L)),
    (2, ("apple.com", 9L)),
    (3, ("microsoft.com", 5L)),
    (3, ("yahoo.com", 3L)),
    (3, ("google.com", 4L)))

  //sort and trim a traversable (String, Long) tuple by _2 value of the tuple
  def topNs(xs: TraversableOnce[(String, Long)], n: Int) = {
    var ss = List[(String, Long)]()
    var min = Long.MaxValue
    var len = 0
    xs foreach { e =>
      if (len < n || e._2 > min) {
        ss = (e :: ss).sortBy((f) => f._2)
        min = ss.head._2
        len += 1
      }
      if (len > n) {
        ss = ss.tail
        min = ss.head._2
        len -= 1
      }
    }
    ss
  }

  def main(args: Array[String]): Unit = {

    val topN = 2
    val sc = new SparkContext("local", "TopN For Key")
    val rdd = sc.parallelize(SampleDataset).map((t) => (t._1, t._2))

    //use combineByKey to allow spark to partition the sorting and "trimming" across the cluster
    val topNForKey = rdd.combineByKey(
      //seed a list for each key to hold your top N with your first record
      (v) => List[(String, Long)](v),
      //add the incoming value to the accumulating top N list for the key
      (acc: List[(String, Long)], v) => topNs(acc ++ List((v._1, v._2)), topN).toList,
      //merge top N lists returned from each partition into a new combined top N list
      (acc: List[(String, Long)], acc2: List[(String, Long)]) => topNs(acc ++ acc2, topN).toList)

    //print results sorting for pretty
    topNForKey.sortByKey(true).foreach((t) => {
      println(s"key: ${t._1}")
      t._2.foreach((v) => {
        println(s"----- $v")
      })

    })

  }

}

rdd...

(1, List(("google.com", 4L),
         ("stackoverflow.com", 10L))
(2, List(("apple.com", 9L),
         ("slashdot.org", 15L))
(3, List(("google.com", 4L),
         ("microsoft.com", 5L))

https://www.mail-archive.com/user@spark.apache.org/msg16827.html

fooobar.com/questions/1566064/...

http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.rdd.PairRDDFunctions

+6

Spark 1.4.0 .

https://github.com/apache/spark/commit/5e6ad24ff645a9b0f63d9c0f17193550963aa0a7

BoundedPriorityQueue aggregateByKey

def topByKey(num: Int)(implicit ord: Ordering[V]): RDD[(K, Array[V])] = {
  self.aggregateByKey(new BoundedPriorityQueue[V](num)(ord))(
    seqOp = (queue, item) => {
      queue += item
    },
    combOp = (queue1, queue2) => {
      queue1 ++= queue2
    }
  ).mapValues(_.toArray.sorted(ord.reverse))  // This is an min-heap, so we reverse the order.
}
+5
source

All Articles