Hadoop对文本文件的快速全局排序
一、背景
Hadoop中实现了用于全局排序的InputSampler类和TotalOrderPartitioner类,调用示例是org.apache.hadoop.examples.Sort。
但是当我们以Text文件作为输入时,结果并非按Text中的string列排序,而且输出结果是SequenceFile。
原因:
1) hadoop在处理Text文件时,key是行号LongWritable类型,InputSampler抽样的是key,TotalOrderPartitioner也是用key去查找分区。这样,抽样得到的partition文件是对行号的抽样,结果自然是根据行号来排序。
2)大数据量时,InputSampler抽样速度会非常慢。比如,RandomSampler需要遍历所有数据,IntervalSampler需要遍历文件数与splits数一样。SplitSampler效率比较高,但它只抽取每个文件前面的记录,不适合应用于文件内有序的情况。
二、功能
1. 实现了一种局部抽样方法PartialSampler,适用于输入数据各文件是独立同分布的情况
2. 使RandomSampler、IntervalSampler、SplitSampler支持对文本的抽样
3. 实现了针对Text文件string列的TotalOrderPartitioner
三、实现
public K[] getSample(InputFormat<K,V> inf, JobConf job) throws IOException {
InputSplit[] splits = inf.getSplits(job, job.getNumMapTasks());
ArrayList<K> samples = new ArrayList<K>(numSamples);
Random r = new Random();
long seed = r.nextLong();
r.setSeed(seed);
LOG.debug("seed: " + seed);
// 对splits【0】抽样
for (int i = 0; i < 1; i++) {
System.out.println("PartialSampler will getSample splits["+i+"]");
RecordReader<K,V> reader = inf.getRecordReader(splits[i], job,
Reporter.NULL);
K key = reader.createKey();
V value = reader.createValue();
while (reader.next(key, value)) {
if (r.nextDouble() <= freq) {
if (samples.size() < numSamples) {
// 选择value中的第一列抽样
Text value0 = new Text(value.toString().split("\t")[0]);
samples.add((K) value0);
} else {
// When exceeding the maximum number of samples, replace a
// random element with this one, then adjust the frequency
// to reflect the possibility of existing elements being
// pushed out
int ind = r.nextInt(numSamples);
if (ind != numSamples) {
Text value0 = new Text(value.toString().split("\t")[0]);
samples.set(ind, (K) value0);
}
freq *= (numSamples - 1) / (double) numSamples;
}
key = reader.createKey();
}
}
reader.close();
}
return (K[])samples.toArray();
}
记录采样的具体过程如下:
从指定分区中取出一条记录,判断得到的随机浮点数是否小于等于采样频率freq
如果大于则放弃这条记录;
如果小于,则判断当前的采样数是否小于最大采样数,
如果小于则这条记录被选中,被放进采样集合中;
否则从【0,numSamples】中选择一个随机数,如果这个随机数不等于最大采样数numSamples,则用这条记录替换掉采样集合随机数对应位置的记录,同时采样频率freq减小变为freq*(numSamples-1)/numSamples。
然后依次遍历分区中的其它记录。
note:
1)PartialSampler只适用于输入数据各文件是独立同分布的情况。
2)自带的三种Sampler通过修改samples.add(key)为samples.add((K) value0); 也可以实现对第一列的抽样。
2. TotalOrderPartitioner
TotalOrderPartitioner主要改进了两点:
1)读partition时指定keyClass为Text.class
因为partition文件中的key类型为Text
在configure函数中,修改:
//Class<K> keyClass = (Class<K>)job.getMapOutputKeyClass();
Class<K> keyClass = (Class<K>)Text.class;
2)查找分区时,改用value查
public int getPartition(K key, V value, int numPartitions) {
Text value0 = new Text(value.toString().split("\t")[0]);
return partitions.findPartition((K) value0);
}
3. Sort
1)设置InputFormat、OutputFormat、OutputKeyClass、OutputValueClass、MapOutputKeyClass
2)初始化InputSampler对象,抽样
3)partitionFile通过CacheFile传给TotalOrderPartitioner,执行MapReduce任务
Class<? extends InputFormat> inputFormatClass = TextInputFormat.class;
Class<? extends OutputFormat> outputFormatClass = TextOutputFormat.class;
Class<? extends WritableComparable> outputKeyClass = Text.class;
Class<? extends Writable> outputValueClass = Text.class; jobConf.setMapOutputKeyClass(LongWritable.class); // Set user-supplied (possibly default) job configs
jobConf.setNumReduceTasks(num_reduces); jobConf.setInputFormat(inputFormatClass);
jobConf.setOutputFormat(outputFormatClass); jobConf.setOutputKeyClass(outputKeyClass);
jobConf.setOutputValueClass(outputValueClass); if (sampler != null) {
System.out.println("Sampling input to effect total-order sort...");
jobConf.setPartitionerClass(TotalOrderPartitioner.class);
Path inputDir = FileInputFormat.getInputPaths(jobConf)[0];
inputDir = inputDir.makeQualified(inputDir.getFileSystem(jobConf));
//Path partitionFile = new Path(inputDir, "_sortPartitioning");
TotalOrderPartitioner.setPartitionFile(jobConf, partitionFile);
InputSampler.<K,V>writePartitionFile(jobConf, sampler); URI partitionUri = new URI(partitionFile.toString() + "#" + "_sortPartitioning");
DistributedCache.addCacheFile(partitionUri, jobConf);
DistributedCache.createSymlink(jobConf);
} FileSystem hdfs = FileSystem.get(jobConf);
hdfs.delete(outputpath);
hdfs.close(); System.out.println("Running on " +
cluster.getTaskTrackers() +
" nodes to sort from " +
FileInputFormat.getInputPaths(jobConf)[0] + " into " +
FileOutputFormat.getOutputPath(jobConf) +
" with " + num_reduces + " reduces.");
Date startTime = new Date();
System.out.println("Job started: " + startTime);
jobResult = JobClient.runJob(jobConf);
三、执行
usage:
hadoop jar yitengfei.jar com.yitengfei.Sort [-m <maps>] [-r <reduces>]
[-splitRandom <double pcnt> <numSamples> <maxsplits> | // Sample from random splits at random (general)
-splitSample <numSamples> <maxsplits> | // Sample from first records in splits (random data)
-splitInterval <double pcnt> <maxsplits>] // Sample from splits at intervals (sorted data)
-splitPartial <double pcnt> <numSamples> <maxsplits> | // Sample from partial splits at random (general) ]
<input> <output> <partitionfile>
Example:
hadoop jar yitengfei.jar com.yitengfei.Sort -r 10 -splitPartial 0.1 10000 10 /user/rp-rd/yitengfei/sample/input /user/rp-rd/yitengfei/sample/output /user/rp-rd/yitengfei/sample/partition
四、性能
200G输入数据,15亿条url,1000个分区,排序时间只用了6分钟
Hadoop对文本文件的快速全局排序的更多相关文章
- 一起学Hadoop——TotalOrderPartitioner类实现全局排序
Hadoop排序,从大的范围来说有两种排序,一种是按照key排序,一种是按照value排序.如果按照value排序,只需在map函数中将key和value对调,然后在reduce函数中在对调回去.从小 ...
- 三种方法实现Hadoop(MapReduce)全局排序(1)
我们可能会有些需求要求MapReduce的输出全局有序,这里说的有序是指Key全局有序.但是我们知道,MapReduce默认只是保证同一个分区内的Key是有序的,但是不保证全局有序.基于此,本文提供三 ...
- MapReduce TotalOrderPartitioner 全局排序
我们知道Mapreduce框架在feed数据给reducer之前会对map output key排序,这种排序机制保证了每一个reducer局部有序,hadoop 默认的partitioner是Has ...
- Mapreduce的排序(全局排序、分区加排序、Combiner优化)
一.MR排序的分类 1.部分排序:MR会根据自己输出记录的KV对数据进行排序,保证输出到每一个文件内存都是经过排序的: 2.全局排序: 3.辅助排序:再第一次排序后经过分区再排序一次: 4.二次排序: ...
- 大数据mapreduce全局排序top-N之python实现
a.txt.b.txt文件如下: a.txt hadoop hadoop hadoop hadoop hadoop hadoop hadoop hadoop hadoop hadoop hadoop ...
- MapReduce怎么优雅地实现全局排序
思考 想到全局排序,是否第一想到的是,从map端收集数据,shuffle到reduce来,设置一个reduce,再对reduce中的数据排序,显然这样和单机器并没有什么区别,要知道mapreduce框 ...
- VMware 克隆linux后找不到eth0(学习hadoop,所以想快速搭建一个集群)
发生情况: 由于在学习hadoop,所以想快速搭建一个集群出来.所以直接在windows操作系统上用VMware安装了CentOS操作系统,配置好hadoop开发环境后,采用克隆功能,直接克 ...
- java写hadoop全局排序
前言: 一直不会用java,都是streaming的方式用C或者python写mapper或者reducer的可执行程序.但是有些情况,如全排序等等用streaming的方式往往不好处理,于是乎用原生 ...
- 基于Hadoop 2.6.0运行数字排序的计算
上个博客写了Hadoop2.6.0的环境部署,下面写一个简单的基于数字排序的小程序,真正实现分布式的计算,原理就是对多个文件中的数字进行排序,每个文件中每个数字占一行,排序原理是按行读取后分块进行排序 ...
随机推荐
- apache common-io.jar FileUtils
//复制文件 void copyFile(File srcFile, File destFile) //将文件内容转化为字符串 String readFileToString(File file ...
- My_Plan part1 小结
数位DP AC十道题目以上 成就达成 八月份!三个月!想想就令人兴奋呢 开始写总结啦 貌似简单的数位DP只需要改改模板就可以啦 就按照我的做题顺序开始总结吧 先是学习了一发模板:http://www. ...
- json的数据格式(仔细查看)
1.json对象就是jsonObject,jsonobject里可以放入很多键值对,并以逗号为分隔符. jsonObject里还可以嵌套JsonObject对象,或者数组信息作为value,数组作为k ...
- Java并发:Callable、Future和FutureTask
Java并发编程:Callable.Future和FutureTask 在前面的文章中我们讲述了创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这2种方式都有一 ...
- 漫谈C语言及如何学习C语言
抄自:http://my.oschina.net/apeng/blog/137911 目录:[ - ] 为什么要学习C语言? C语言学习方法 1,参考书籍 2,动手实验环境搭建 3,网络资源 附录 一 ...
- Arcgis Engine最短路径分析
ArcEngine 最短路径分析(源码) using System; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ESRI ...
- 机器学习 —— 概率图模型(Homework: Representation)
前两周的作业主要是关于Factor以及有向图的构造,但是概率图模型中还有一种更强大的武器——双向图(无向图.Markov Network).与有向图不同,双向图可以描述两个var之间相互作用以及联系. ...
- C++仿函数(functor)详解
C++仿函数(functor)详解 所谓的仿函数(functor),是通过重载()运算符模拟函数形为的类. 因此,这里需要明确两点: 1 仿函数不是函数,它是个类: 2 仿函数重载了()运算符,使得它 ...
- android rabbitMQ
http://www.cnblogs.com/wufawei/archive/2012/03/31/2427823.html http://www.raywenderlich.com/5527/get ...
- C# 控件双缓冲控制 ControlStyles 枚举详解
ControlStyles 枚举 .NET Framework 4 指定控件的样式和行为. 此枚举有一个 FlagsAttribute 特性,通过该特性可使其成员值按位组合. 命名空间: Sy ...