2.0 数据排序
"数据排序"是许多实际任务执行时要完成的第一项工作,比如学生成绩评比、数据建立索引等。这个实例和数据去重类似,都是先对原始数据进行初步处理,为进一步的数据操作打好基础。
2.1 实例描述
输入文件中的每行内容均为一个数字,即一个数据。要求在输出中每行有两个间隔的数字,其中,第一个代表原始数据在原始数据集中的位次,第二个代表原始数据。
a.txt
7
4
3
b.txt
4
2
样例输出:
1 2
2 3
3 4
4 7
2.2 设计思路
仅仅要求对输入数据进行排序,熟悉MapReduce过程的读者会很快想到在MapReduce过程中就有排序,是否可以利用这个默认的排序,而不需要自己再实现具体的排序呢?答案是肯定的。
首先需要了解它的默认排序规则。它是按照key值进行排序的,如果key为封装int的IntWritable类型,那么MapReduce按照数字大小对key排序,如果key为封装为String的Text类型,那么MapReduce按照字典顺序对字符串排序。
输出的key(即代码中的linenum)是一个全局变量,它统计当前key的位次。需要注意的是这个程序中没有配置Combiner,也就是在MapReduce过程中不使用Combiner。这主要是因为使用map和reduce就已经能够完成任务了。
2.3 程序代码
程序代码如下所示:
package test;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
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;
import org.apache.hadoop.util.GenericOptionsParser;
public class Sort{
public static class Map extends Mapper<Object, Text, IntWritable, NullWritable>{
private static IntWritable data = new IntWritable();
protected void map(Object key, Text value, Context context)
throws java.io.IOException ,InterruptedException {
//设置数据
data.set(Integer.parseInt(value.toString()));
context.write(data, NullWritable.get());
};
}
public static class Reduce extends Reducer<IntWritable, NullWritable, IntWritable, IntWritable>{
private static IntWritable lineNum = new IntWritable(1);
protected void reduce(IntWritable key, Iterable<NullWritable> values, Context context)
throws java.io.IOException ,InterruptedException {
context.write(lineNum, key);
lineNum.set(lineNum.get() + 1);
};
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf,args).getRemainingArgs();
if(otherArgs.length != 2){
System.err.println("Usage: Data Sort!");
System.exit(2);
}
Job job = new Job(conf, "Data Sort");
job.setJarByClass(Sort.class);
//设置Map和Reduce
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
//设置Map的输入和输出类,默认不是这个,否则提示类型Unmismattch
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(NullWritable.class);
//设置Reduce端的输入和输出类
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(IntWritable.class);
//设置输入和输出目录
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 :1);
}
}
2.4 准备数据,上传到hdfs的/input目录下
2.5 myeclipse设置程序的参数 /input /output ,运行程序
2.6 输出结果:
1 2
2 3
3 4
4 7
over