title: Spark: Get top N by key
body: <p>Say I have a PairRDD as such (Obviously much more data in real life, assume millions of records): </p>
  
  <pre><code>val scores = sc.parallelize(Array(
        ("a", 1),  
        ("a", 2), 
        ("a", 3), 
        ("b", 3), 
        ("b", 1), 
        ("a", 4),  
        ("b", 4), 
        ("b", 2)
  ))
  </code></pre>
  
  <p>What is the most efficient way to generate a RDD with the top 2 scores per key?</p>
  
  <pre><code>val top2ByKey = ...
  res3: Array[(String, Int)] = Array((a,4), (a,3), (b,4), (b,3))
  </code></pre>