hadoop 数据排序

来源:互联网 发布:淘宝快递单模板 编辑:程序博客网 时间:2024/06/02 04:28

1、输入

file1.txt

23
8
24
34
234234
3
5
6
5
5

file2.txt

123
2
4
45678
56
78
102
56
23
99999
99
999

2、问题、思路

问题:

将上面两个文件,排序,结果要求:每行两个数 第一个是序号,第二个是数值

思路:

map阶段进行取词,reduce接受到的数据已经是有序的(hadoop已排好),那么reduce需要计数

3、代码

package smiple;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.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 {// map将输入中的value化成IntWritable类型,作为输出的keypublic static class MyMap extends Mapper<Object, Text, IntWritable, IntWritable> {private static IntWritable data = new IntWritable();// 实现map函数public void map(Object key, Text value, Context context)throws IOException, InterruptedException {String line = value.toString();data.set(Integer.parseInt(line));context.write(data, new IntWritable(1));}}/** * reduce将输入中的key复制到输出数据的key上, * 然后根据输入的value-list中元素的个数决定key的输出次数 * 用全局linenum来代表key的位次 * @author allen * */public static class MyReduce extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {private static IntWritable linenum = new IntWritable(1);// 实现reduce函数public void reduce(IntWritable key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {for (IntWritable val : values) {context.write(linenum, key);linenum = new IntWritable(linenum.get() + 1);}}}public static void main(String[] args) throws Exception {Configuration conf = new Configuration();//conf.set("mapred.job.tracker", "ip:端口");String[] ioArgs = new String[] { "hdfs://ip:端口/mr/sort/sort_in", "hdfs://ip:端口/mr/sort/sort_out" };String[] otherArgs = new GenericOptionsParser(conf, ioArgs).getRemainingArgs();if (otherArgs.length != 2) {System.err.println("Usage: Data Sort <in> <out>");System.exit(2);}Job job = new Job(conf, "Data Sort");job.setJarByClass(Sort.class);// 设置Map和Reduce处理类job.setMapperClass(MyMap.class);job.setReducerClass(MyReduce.class);// 设置输出类型job.setOutputKeyClass(IntWritable.class);job.setOutputValueClass(IntWritable.class);// 设置输入和输出目录FileInputFormat.addInputPath(job, new Path(otherArgs[0]));FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));System.exit(job.waitForCompletion(true) ? 0 : 1);}}


4、结果

1 2
2 3
3 4
4 5
5 5
6 5
7 6
8 8
9 23
10 23
11 24
12 34
13 56
14 56
15 78
16 99
17 102
18 123
19 999
20 45678
21 99999
22 234234


声明: 参考 http://www.cnblogs.com/xia520pi/archive/2012/06/04/2534533.html


5 0
原创粉丝点击