推荐看两篇博客:
http://blog.csdn.net/cnweike/article/details/6954364
需求:::::
要说明这个思想,考虑计算一年中最高气温的MapReduce程序。如果我们将值安排为降序,那么我们就不需要通过迭代来找出最大值——我们仅仅是拿出第一个值来,而忽略掉剩下的。(这个方法可能不是解决这个问题的最有效的方式,但是它说明了二次排序的工作方式)
要达到这个目的,我们将我们键修改成一个组合体:年份和温度的结合。我们想要按照年份(升序),然后按照温度(降序)排序:
1900 35C
1900 34C
1900 34C
...
1901 36C
1901 35C
如果我们仅仅是修改了键,这不会起到任何的帮助,因为同样的年份将不会(通常情况下)进入到相同的reducer中,因为它们有着不同的键。对于实例,(1900, 35)和(1900, 34)将会进入到不同的reducer中。通过将键的年份设置一个分区器,我们可以保证相同年份的记录将进入到相同的reducer中。然而,这还是达不到我们的目标。一个分区器只是保证一个reducer接收到一个年份的所有的记录;它不能改变reducer在这个分区里通过key来做分组的事实:
谜题最后的部分是控制分组的设置。如果我们通过键的年份部分进行分组,然后我们将看到一年的所有记录出现在一个reduce组中。既然它们是按照温度降序排列的,那么第一个就是最大温度:
做一个总结,这里有一个获得通过值排序的效果的方法:
代码;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.StringTokenizer;
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.RawComparator;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.util.GenericOptionsParser;
/**
* This is an example Hadoop Map/Reduce application.
* It reads the text input files that must contain two integers per a line.
* The output is sorted by the first and second number and grouped on the
* first number.
*
* To run: bin/hadoop jar build/hadoop-examples.jar secondarysort
* <i>in-dir</i> <i>out-dir</i>
*/
public class SecondarySort {
/**
* Define a pair of integers that are writable.
* They are serialized in a byte comparable format.
*/
public static class IntPair implements WritableComparable<IntPair> {
private int first = 0;
private int second = 0;
/**
* Set the left and right values.
*/
public void set(int left, int right) {
first = left;
second = right;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
/**
* Read the two integers.
* Encoded as: MIN_VALUE -> 0, 0 -> -MIN_VALUE, MAX_VALUE-> -1
*/
@Override
public void readFields(DataInput in) throws IOException {
first = in.readInt() + Integer.MIN_VALUE;
second = in.readInt() + Integer.MIN_VALUE;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(first - Integer.MIN_VALUE);
out.writeInt(second - Integer.MIN_VALUE);
}
@Override
public int hashCode() {
return first * 157 + second;
}
@Override
public boolean equals(Object right) {
if (right instanceof IntPair) {
IntPair r = (IntPair)right;
return r.first == first && r.second == second;
} else {
return false;
}
}
/** A Comparator that compares serialized IntPair. */
public static class Comparator extends WritableComparator {
public Comparator() {
super(IntPair.class);
}
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
return compareBytes(b1, s1, l1, b2, s2, l2);
}
}
static { // register this comparator
WritableComparator.define(IntPair.class, new Comparator());
}
@Override
public int compareTo(IntPair o) {
if (first != o.first) {
return first < o.first ? -1 : 1;
} else if (second != o.second) {
return second < o.second ? -1 : 1;
} else {
return 0;
}
}
}
/**
* Partition based on the first part of the pair.
*/
public static class FirstPartitioner extends Partitioner<IntPair, IntWritable> {
@Override
public int getPartition(IntPair key, IntWritable value, int numPartitions) {
return Math.abs(key.getFirst() * 127) % numPartitions;
}
}
/**
* Compare only the first part of the pair, so that reduce is called once
* for each value of the first part.
想明白了为啥需要分组了
因为map的键还是IntPari,所以相同的年份和温度的还是不会去一个reduce中,
所以我们自定义了分组,这样同一年的都进入一个reduce了。
而且我们定义了分组的排序的策略了,就是按照年份来分组的
键和值得排序是根据IntPari中的equase方法和hashcode 还有compareTo 方法决定了
*/public static class FirstGroupingComparator implements RawComparator<IntPair> {
@Override
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
return WritableComparator.compareBytes(b1, s1, Integer.SIZE / 8, b2, s2, Integer.SIZE / 8);
}
@Override
public int compare(IntPair o1, IntPair o2) {
int l = o1.getFirst();
int r = o2.getFirst();
return l == r ? 0 : (l < r ? -1 : 1);
}
}
public static void main(String[] args) { }
/**
* Read two integers from each line and generate a key, value pair
* as ((left, right), right).
*/
public static class MapClass extends Mapper<LongWritable, Text, IntPair, IntWritable> {
private final IntPair key = new IntPair();
private final IntWritable value = new IntWritable();
@Override
public void map(LongWritable inKey, Text inValue, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(inValue.toString());
int left = 0;
int right = 0;
if (itr.hasMoreTokens()) {
left = Integer.parseInt(itr.nextToken());
if (itr.hasMoreTokens()) {
right = Integer.parseInt(itr.nextToken());
}
key.set(left, right);
value.set(right);
context.write(key, value);
}
}
}
/**
* A reducer class that just emits the sum of the input values.
*/
public static class Reduce extends Reducer<IntPair, IntWritable, Text, IntWritable> {
private static final Text SEPARATOR = new Text("------------------------------------------------");
private final Text first = new Text();
@Override
public void reduce(IntPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
context.write(SEPARATOR, null);
first.set(Integer.toString(key.getFirst()));
for (IntWritable value : values) {
context.write(first, value);
}
}
}
// 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: secondarysort <in> <out>");
// System.exit(2);
// }
// Job job = Job.getInstance(conf, "secondary sort");
// job.setJarByClass(SecondarySort.class);
// job.setMapperClass(MapClass.class);
// job.setReducerClass(Reduce.class);
//
// // group and partition by the first int in the pair
// job.setPartitionerClass(FirstPartitioner.class);
// job.setGroupingComparatorClass(FirstGroupingComparator.class);
//
// // the map output is IntPair, IntWritable
// job.setMapOutputKeyClass(IntPair.class);
// job.setMapOutputValueClass(IntWritable.class);
//
// // the reduce output is Text, IntWritable
// job.setOutputKeyClass(Text.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);
// }
}