【Data Algorithms_Recipes for Scaling up with Hadoop and Spark】Chapter3 Top 10 NonUniqueList

:scala版

package com.bbw5.dataalgorithms.spark

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import java.util.PriorityQueue

/**
 * Assumption: for all input (K, V), K's are non-unique.
 * This class implements Top-N design pattern for N > 0.
 * The main assumption is that for all input (K, V)'s, K's
 * are non-unique. It means that you will find entries like
 * (A, 2), ..., (A, 5),...
 *
 * This is a general top-N algorithm which will work unique
 * and non-unique keys.
 *
 * This class may be used to find bottom-N as well (by
 * just keeping N-smallest elements in the set.
 *
 *  Top-10 Design Pattern: “Top Ten” Structure
 *
 *  1. map(input) => (K, V)
 *
 *  2. reduce(K, List<V1, V2, ..., Vn>) => (K, V),
 *                where V = V1+V2+...+Vn
 *     now all K's are unique
 *
 *  3. Find Top-N using the following high-level Spark API:
 *     java.util.List<T> takeOrdered(int N, java.util.Comparator<T> comp)
 *     Returns the first N elements from this RDD as defined by the specified
 *     Comparator[T] and maintains the order.
 * cat id,cat name,cat weight
 * 1,cat1,13
 * 2,cat2,10
 * 3,cat3,14
 * 4,cat4,13
 * 5,cat5,20
 * 6,cat6,24
 * 7,cat7,13
 * 8,cat8,10
 * 9,cat9,24
 * 10,cat10,13
 * 11,cat11,30
 * 12,cat12,14
 * @author babaiw5
 *
 */
object SparkTop10UsingTakeOrdered {
  def main(args: Array[String]) {
    val sparkConf = new SparkConf().setAppName("SparkTop10UsingTakeOrdered")
    val sc = new SparkContext(sparkConf)

    val filename = "G:/temp/data/top1.txt"
    val textFile = sc.textFile(filename)

    val topN = 5
    val topNRDD = textFile.map(_.split(",")).map(d =>
      ((d(0), d(1)), d(2).toInt)).reduceByKey((a, b) => a + b).
      takeOrdered(topN)(Ordering.by[((String, String), Int), Int](-_._2))
      
    topNRDD.foreach(println)
    
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值