Hadoop mapreduce custom sorting WritableComparable, hadoopmapreduce

Source: Internet
Author: User

Hadoop mapreduce custom sorting WritableComparable, hadoopmapreduce

This article is published on my blog.

I continued to write exercise questions today. I had a slight understanding of the partition last time. Now I want to write a sorting example based on the partition, sorting, grouping, and conventions, well, start now!

Speaking of sorting, we can view the LongWritable type definition in the WordCount example in the hadoop source code, which implements the abstract interface WritableComparable. The Code is as follows:

public interface WritableComparable<T> extends Writable, Comparable<T> {}public interface Writable {  void write(DataOutput out) throws IOException;  void readFields(DataInput in) throws IOException;}

The Writable abstract interface defines the write and readFields methods, respectively writing data streams and reading data streams. Comparable has a compareTo method definition comparison. The built-in type of hadoop has the function of comparing the size, so how can it sort the output of this built-in type as the map end? Let's first look at the source code of MapTask of map task class, there is a built-in MapOutputBuffer class, and there is a sorting field under the spill accounting comment:

private final IndexedSorter sorter;

This field is composed:

sorter = ReflectionUtils.newInstance(job.getClass("map.sort.class", QuickSort.class, IndexedSorter.class), job);

It can be seen that this sorting algorithm can be specified in the configuration file, but the default is quick sorting. There are several important internal methods for this QuickSort:

public void sort(final IndexedSortable s, int p, int r,final Progressable rep);private static void sortInternal(final IndexedSortable s, int p, int r,final Progressable rep, int depth);

When passing the IndexSortable parameter, the current MapOutputBuffer is used for transmission, because this MapOutputBuffer also inherits IndexedSortable. in this way, the compare method in the MapOutputBuffer class will be used for comparison in QuickSort sorting sort. You can refer to the following source code:

    public int compare(int i, int j) {      final int ii = kvoffsets[i % kvoffsets.length];      final int ij = kvoffsets[j % kvoffsets.length];      // sort by partition      if (kvindices[ii + PARTITION] != kvindices[ij + PARTITION]) {        return kvindices[ii + PARTITION] - kvindices[ij + PARTITION];      }      // sort by key      return comparator.compare(kvbuffer,          kvindices[ii + KEYSTART],          kvindices[ii + VALSTART] - kvindices[ii + KEYSTART],          kvbuffer,          kvindices[ij + KEYSTART],          kvindices[ij + VALSTART] - kvindices[ij + KEYSTART]);    }

However, in this method, comparator is determined by the node "mapred. output. key. comparator. class" by default. You can also view the source code:

  public RawComparator getOutputKeyComparator() {    Class<? extends RawComparator> theClass = getClass("mapred.output.key.comparator.class",            null, RawComparator.class);    if (theClass != null)      return ReflectionUtils.newInstance(theClass, this);    return WritableComparator.get(getMapOutputKeyClass().asSubclass(WritableComparable.class));  }

That is to associate the sorting and comparison methods! Now we can follow the LongWritable idea to implement custom types and read, write, and compare them. Write the code below to deepen the memory. Since the data is sorted, we prepare the data. There are two columns of data that need to be sorted in ascending order of the first column and the second in descending order:

1    21    13    03    22    21    2

First custom type SortAPI:

Public class SortAPI implements WritableComparable <SortAPI> {/*** first column data */public Long first;/*** second column data */public Long second; public SortAPI () {} public SortAPI (long first, long second) {this. first = first; this. second = second;}/*** sorting is here when: this. first-o. first> 0 ascending, less than 0 reverse */@ Override public int compareTo (SortAPI o) {long mis = (this. first-o. first); if (mis! = 0) {return (int) mis;} else {return (int) (this. second-o. second) ;}@ Override public void write (DataOutput out) throws IOException {out. writeLong (first); out. writeLong (second) ;}@ Override public void readFields (DataInput in) throws IOException {this. first = in. readLong (); this. second = in. readLong () ;}@ Override public int hashCode () {return this. first. hashCode () + this. second. hashCode () ;}@ Override public boolean equals (Object obj) {if (obj instanceof SortAPI) {SortAPI o = (SortAPI) obj; return this. first = o. first & this. second = o. second;} return false ;}@ Override public String toString () {return "first:" + this. first + "second:" + this. second ;}}

This type of rewriting includes compareTo (SortAPI o), write (DataOutput out), and readFields (DataInput in). Since there are comparisons, We must overwrite hashCode () and equals (Object obj) methods. Do not forget this! It is also necessary to read and write data in sequence in the write method and readFields method: write the fields first and read the fields first. The compareTo (SortAPI o) method returns integer values greater than 0, 0, and smaller than 0, indicating greater than, equal to, or less. As for how to judge whether two rows of data are equal, you can take a look at the logic for comparison between unequal rows.

Below is a custom Mapper, Reducer class, and main function:

public class MyMapper extends Mapper<LongWritable, Text, SortAPI, LongWritable> {            @Override    protected void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException {        String[] splied = value.toString().split("\t");        try {            long first = Long.parseLong(splied[0]);            long second = Long.parseLong(splied[1]);            context.write(new SortAPI(first,second), new LongWritable(1));        } catch (Exception e) {            System.out.println(e.getMessage());        }    }}
public class MyReduce extends Reducer<SortAPI, LongWritable, LongWritable, LongWritable> {    @Override    protected void reduce(SortAPI key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {        context.write(new LongWritable(key.first), new LongWritable(key.second));    }    }
Static final String OUTPUT_DIR = "hdfs: // hadoop-master: 9000/sort/output/"; static final String INPUT_DIR = "hdfs: // hadoop-master: 9000/sort/input/test.txt "; public static void main (String [] args) throws Exception {Configuration conf = new Configuration (); Job job = new Job (conf, Test. class. getSimpleName (); deleteOutputFile (OUTPUT_DIR); // 1 set the input directory FileInputFormat. setInputPaths (job, INPUT_DIR); // 2 sets the input formatting class job. setInputFormatClass (TextInputFormat. class); // 3 set the custom er and key-value type job. setMapperClass (MyMapper. class); job. setMapOutputKeyClass (SortAPI. class); job. setMapOutputValueClass (LongWritable. class); // 4 partition job. setPartitionerClass (HashPartitioner. class); job. setNumReduceTasks (1); // 5 sorting group // 6 is set in a certain Reduce and key value type job. setReducerClass (MyReduce. class); job. setOutputKeyClass (LongWritable. class); job. setOutputValueClass (LongWritable. class); // 7 set the output directory FileOutputFormat. setOutputPath (job, new Path (OUTPUT_DIR); // 8 submit the job. waitForCompletion (true);} static void deleteOutputFile (String path) throws Exception {Configuration conf = new Configuration (); FileSystem fs = FileSystem. get (new URI (INPUT_DIR), conf); if (fs. exists (new Path (path) {fs. delete (new Path (path ));}}

In this way, you can directly run and view the results in eclipse:

1       11       22       23       03       2

If the result is correct, what should I do if I need to reverse the first column to the second column in ascending order? I only need to modify compareTo (SortAPI o ):

    @Override    public int compareTo(SortAPI o) {        long mis = (this.first - o.first) * -1 ;        if(mis != 0 ){            return (int)mis;        }        else{            return (int)(this.second - o.second);        }    }

The result is as follows:

3       03       22       21       11       2

Correct.

Leave a small question: when is the compareTo (SortAPI o) method called? How many times have it been called in total?

First come here this time. Keep recording!


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.