Write WordCount and hadoopwordcount in Hadoop

Source: Internet
Author: User

Write WordCount and hadoopwordcount in Hadoop

This article is published on my blog.

I have talked about Hadoop environment setup and HDFS operations several times before. continue today. There is an example of WordCount in Hadoop source code, but today we will implement a better understanding of this Mapper and Reducer. If you have any questions, please correct them.

Let's sort out our ideas. For custom er and Reducer, We need to overwrite its map and reduce functions first, then, follow the relevant steps, such as setting the input file directory, the input file formatting class, setting custom er, partition, sorting, grouping, conventions, setting custom CER, and so on. Here we use spaces to separate the input file (or tabs). below is the custom Mapper class MyMapper:

import java.io.IOException;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Mapper;import org.apache.hadoop.mapreduce.Mapper.Context;public class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {        @Override    protected void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException {        String[] splied = value.toString().split(" ");        for (int i = 0; i < splied.length; i++) {            String lineWord = splied[i];            context.write(new Text(lineWord), new LongWritable(1));        }    }}

Here I chose a new API, and the relevant libraries are basically at org. apache. hadoop. in mapreduce, the old API is in org. apache. hadoop. this is also true for some reference libraries in mapred. Custom MyMapper is a generic inherited Mapper, and the key \ value parameter is an internal Hadoop type. It does not support the basic java type. Here, we need to note why we do not select the Basic java type, the reason is that no additional operations are required, and serialization and deserialization are required to improve its performance. Therefore, the hadoop type is added to discard the Basic java type. The conversion between hadoop key \ value and java basic types is also very simple. If the conversion from java basic type to hadoop key \ value, you can directly add a new parameter, use the get method to convert the key/value type of hadoop to the Basic java type! For example:

LongWritable lw = new LongWritable(1L);long temp = lw.get();

Next we will continue to look at the custom CER class MyReduce:

import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.Reducer;import org.apache.hadoop.mapreduce.Reducer.Context;public class MyReduce extends Reducer<Text, LongWritable, Text, LongWritable> {    @Override    protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {        long count = 0L;        for(LongWritable value: values) {            count += value.get();        }        context.write(key, new LongWritable(count));    }}

This is similar to the above. Let's take a look at how the main method is executed!

Import org. apache. hadoop. conf. configuration; import org. apache. hadoop. fs. fileSystem; import org. apache. hadoop. fs. path; import org. apache. hadoop. io. longWritable; import org. apache. hadoop. io. text; import org. apache. hadoop. mapreduce. inputFormat; import org. apache. hadoop. mapreduce. job; import org. apache. hadoop. mapreduce. lib. input. fileInputFormat; import org. apache. hadoop. mapreduce. lib. input. textInputFormat; import org. apache. hadoop. mapreduce. lib. output. fileOutputFormat; import org. apache. hadoop. mapreduce. lib. output. textOutputFormat; import org. apache. hadoop. mapreduce. lib. partition. hashPartitioner; import com.sun.org. apache. xpath. internal. axes. hasPositionalPredChecker; public class Test {static final String OUTPUT_DIR = "hdfs: // hadoop-master: 9000/mapreduce/output/"; static final String INPUT_DIR = "hdfs: // hadoop-master: 9000/mapreduce/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 (Text. class); job. setMapOutputValueClass (LongWritable. class); // 4 partition job. setPartitionerClass (HashPartitioner. class); job. setNumReduceTasks (1); // 5 sort group // 6 is set in custom Reduce and key value type job. setReducerClass (MyReduce. class); job. setOutputKeyClass (Text. 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 ));}}}

The output directory of the last execution is output first. Then follow the steps below:

1. set the input file directory; 2. input File formatting class; 3. set the custom er and its key value type. 4. partition; 5. sort; 6. group; 7. protocol; 8. set the custom CER and its key value type. 9. set the output directory. 10. code is submitted to JobTracker.

Of course, some of this process can be omitted, such as the output file formatting class. In this example, we can conclude that, since you can set custom Mapper and custom Reducer, you should also be able to set custom input file formatting classes and partitions, sorting, grouping, and conventions, there will be relevant notes in the future. Here is just a simple example. Compile a file as follows and upload it to hdfs: // hadoop-master: 9000/mapreduce/input/test.txt:

luoliang measura asura.com luoliangme

Then execute the main function and output a file similar to part-* in the hdfs: // hadoop-master: 9000/mapreduce/output/directory. You can run the following command to view the file:

hadoop fs -text /output/part-*

The output is as follows:

asura 1asura.com 1luoliang 2me 2

Now the file is output and the comparison is correct, but the brain is still blank and I don't know how to do it, so this is about the principle of mapreduce, I will also talk about the principle below: From the Code submitted to JobTracker, it will get the file from the specified input file path, multiple files and files under the level-2 Directory are supported. The HDFS api is used for obtaining the files here! After all the files are read, they are split into InputSplit Based on the specified size, and the split key value FileInputSplit (for example, <0, "luoliang me" >,< 13, "asura asura.com luoliang">) is converted to RecordReader (for example, <"luoliang", 1>, <"luoliang", 1> ), after all the conversions are completed, the map function will call each one. The map function writes the data to Mapper. in the Context, the data is partitioned, sorted, and grouped, and then shuffle is used to reach the reduce end. The output quantity of each map is equal to the input quantity of reduce. The data arriving at the reduce end has undergone a qualitative change, instead of the key value data, which is similar to <"luoliang", {1, 1}>, this is what we need to obtain the total number of iterations and output it to the specified directory after calculation in the context of the write. The number of map function calls is different from the number of reduce function calls because of repeated words. This is actually a custom reduce, but it is not necessary because the data is normalized on the map end if it is used to calculate the problem of similar averages, although the transfer time and processing time are reduced, performance improvement may affect the final result. Therefore, this Protocol can only be used based on actual conditions. As for this shuffle step, you need to take a look.

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.