`

[Hadoop] TopK的一个简单实现

阅读更多

题外话:

《Hadoop in Action》 是一本非常不错的交Hadoop的入门书,而且建议看英文版。此书作者的英文表达非常简单易懂。相信有一定英文阅读能力的同学直接用英文版就能非常容易的上手~

 

 

进入正题。 这个题目是《Hadoop in Action》 上面的一道题目,求出Top K的值。

我自己随便弄了一个输入文件:

g	445
a	1117
b	222
c	333
d	444
e	123
f	345
h	456

 

 

讲讲我的思路:

对于Top K的问题,首先要在每个block/分片之中找到这部分的Top K。并且由于只能输出一次,所以输出的工作需要在cleanup方法之中进行。为了简单,使用的是java之中的TreeMap,因为这个数据结构天生就带有排序功能。 而Reducer的工作流程跟Map其实是完全一致的,只是光Map一步还不够,所以只能再加一个Reduce步骤。

 

最终输出的格式为如下:(K=2)

1117    a
456    g

所以需要使用map。 如果只需要输出大小的话,直接使用TreeSet会更高效一点。

 

下面是实现的代码:

package hadoop_in_action_exersice;

import java.io.IOException;
import java.util.TreeMap;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class TopK {

	public static final int K = 2;
	
	public static class KMap extends Mapper<LongWritable, Text, IntWritable, Text> {
		
		TreeMap<Integer, String> map = new TreeMap<Integer, String>(); 
		
		public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
			
			String line = value.toString();
			if(line.trim().length() > 0 && line.indexOf("\t") != -1) {
				
				String[] arr = line.split("\t", 2);
				String name = arr[0];
				Integer num = Integer.parseInt(arr[1]);
				map.put(num, name);
				
				if(map.size() > K) {
					map.remove(map.firstKey());
				}
			}
		}

		@Override
		protected void cleanup(
				Mapper<LongWritable, Text, IntWritable, Text>.Context context)
				throws IOException, InterruptedException {
			
			for(Integer num : map.keySet()) {
				context.write(new IntWritable(num), new Text(map.get(num)));
			}
			
		}
		
	}
	
	
	public static class KReduce extends Reducer<IntWritable, Text, IntWritable, Text> {
		
		TreeMap<Integer, String> map = new TreeMap<Integer, String>();
		
		public void reduce(IntWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
				
			map.put(key.get(), values.iterator().next().toString());
			if(map.size() > K) {
				map.remove(map.firstKey());
			}
		}

		@Override
		protected void cleanup(
				Reducer<IntWritable, Text, IntWritable, Text>.Context context)
				throws IOException, InterruptedException {
			for(Integer num : map.keySet()) {
				context.write(new IntWritable(num), new Text(map.get(num)));
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Configuration conf = new Configuration();
		try {
			Job job = new Job(conf, "my own word count");
			job.setJarByClass(TopK.class);
			job.setMapperClass(KMap.class);
			job.setCombinerClass(KReduce.class);
			job.setReducerClass(KReduce.class);
			job.setOutputKeyClass(IntWritable.class);
			job.setOutputValueClass(Text.class);
			FileInputFormat.setInputPaths(job, new Path("/home/hadoop/DataSet/Hadoop/WordCount-Result"));
			FileOutputFormat.setOutputPath(job, new Path("/home/hadoop/DataSet/Hadoop/TopK-output1"));
			System.out.println(job.waitForCompletion(true));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
}

 

分享到:
评论

相关推荐

    论文研究-一种基于Hadoop的高效[K]-Medoids并行算法.pdf

    以及在大数据环境下所面临的内存容量和CPU处理速度的瓶颈问题,从改进初始中心选择方案和中心替换策略入手,利用Hadoop分布式计算平台结合基于Top [K]的并行随机采样策略,实现了一种高效稳定的[K]-Medoids并行算法...

    基于MapReduce方法统计服务器日志topk数据.zip

    人工智能-hadoop

    《数据算法Hadoop Spark大数据处理技巧》PDF 带目录!!

    目录 第1章二次排序:简介 19 第2章二次排序:详细示例 42 第3章 Top 10 列表 54 第4章左外连接 96 第5章反转排序 127 第6章移动平均 137 第7章购物篮分析 155 第8章共同好友 182 第9章使用MapReduce实现推荐引擎 ...

    Hadoop-Cube-MRCube

    MRCube 在这个项目中,我实现了MRCube算法,该算法在Arnab Nandi,丛瑜,Philip Bohannon,...考虑一个仓库:(城市,州,国家,日,月,年,销售) ,其中: (城市,州,国家/地区) :位置维度 (日,月,年)

    第七章-《大数据导论》大数据处理平台.pdf

    数据复制多份存放不同节点以增加可用性和可靠性 特点:高容错性 + 高扩展性 Apache Hadoop Apache软件基金会下面的一个开源项目 一个分布式系统基础框架 HDFS: Hadoop分布式文件系统,负责数据存储 MapReduce:一种...

    大数据培训课程安排.pdf

    ⼤数据培训课程安排 ⼤数据发展如⽕如荼,近年来,许多⼩伙伴都加⼊了⼤数据学习的⼤军,是⾃学还是参加专业的⼤...化、CDH简介、环境搭建)、扩展(MAP 端优化,COMBINER 使⽤⽅法见,TOP K,SQOOP导出,其它虚拟机VM的快

    Hive用户指南

    2.9.2 Top k 27 2.9.3 REGEX Column Specification 27 3. Hive Select 27 3.1 Group By 28 3.2 Order /Sort By 28 4. Hive Join 29 5. HIVE参数设置 31 6. HIVE UDF 33 6.1 基本函数 33 6.1.1 关系操作符 33 6.1.2 ...

    Learning Apache Mahout(PACKT,2015)

    It implements machine learning algorithms on top of distributed processing platforms such as Hadoop and Spark. Starting with the basics of Mahout and machine learning, you will explore prominent ...

    spark-streaming-bench:spark-streaming-bench

    微型工作台字数演员字数HDFS字数卡夫卡字数TopK(待办事项) HDFSTopK 卡夫卡托普依赖库kafka-clients-0.8.2.1.jar kafka_2.10-0.8.2.1.jar 指标核心2.2.0.jar spark-assembly-1.3.0-hadoop2.4.0.jar spark-streaming-...

    分布式数据仓库Hive大全

    2.9.2 Top k 27 2.9.3 REGEX Column Specification 27 3. Hive Select 27 3.1 Group By 28 3.2 Order /Sort By 28 4. Hive Join 29 5. HIVE参数设置 31 6. HIVE UDF 33 6.1 基本函数 33 6.1.1 关系操作符 33 6.1.2 ...

    平板显示发展史

    关于一个选择器XML的小程序 C++控制台计算器(能识别括号) Java面试宝典 VC写的蝴蝶会动的时钟 清华大学C语言课件【超详细_很强大】 Struts,Hibernate,Spring集成开发宝典.pdf asp.net mvc教程 jquery-ui-1.9.2....

    sigmod2011全部论文(2)

    一个包放不下,一共分成了3个包,包含百余篇论文,朋友们可以挑选自己感兴趣的部分下载,我尽量把文章目录写得明白一些。 这是第二部分。 Nearest Keyword Search in XML Documents (Page 589) Yufei Tao (Chinese ...

    Handbook of Big Data Technologies

    2 A Top-K Entity Augmentation System 3 DrillBeyond -- Processing Open World SQL 4 Summary and Future Work Pattern Matching Over Linked Data Streams 1 Overview 2 Linked Data Dissemination System 3 ...

    sigmod2011全部论文(3)

    一个包放不下,一共分成了3个包,包含百余篇论文,朋友们可以挑选自己感兴趣的部分下载,我尽量把文章目录写得明白一些。 这是第三部分 Emerging Trends in the Enterprise Data Analytics: Connecting Hadoop and ...

Global site tag (gtag.js) - Google Analytics