全部博文(136)
分类: 云计算
2011-03-11 09:51:58
from
Hadoop 0.21 Documentation
The Hadoop Documentation provides the information you need to get started using Hadoop, the Hadoop Distributed File System (HDFS), and Hadoop on Demand (HOD).
MapReduce Tutorial
This document comprehensively describes all user-facing facets of the Hadoop MapReduce framework and serves as a tutorial.
Ensure that Hadoop is installed, configured and is running. More details:
Note that the combine phrase may run zero or more times in this process.
(1) Compile WordCount.java and create a jar:
$ cat hadoopjar(2) Sample text-files as input:
$ ls input(3) Run the application:
$ bin/hadoop jar wordcount_jar/wordcount.jar org.myorg.WordCount input output(4) Output:
$ cat output/part-r-00000Here, myarchive.zip will be placed and unzipped into a directory by the name "myarchive.zip".
For example,
hadoop jar hadoop-examples.jar wordcountHere, the files dir1/dict.txt and dir2/dict.txt can be accessed by tasks using the symbolic names dict1 and dict2 respectively. And the archive mytar.tgz will be placed and unarchived into a directory by the name tgzdir.
This section describes the operation of the WordCount application shown earlier in this tutorial.
The Mapper implementation (lines 16-30), via the map method (lines 21-29), processes one line at a time, as provided by the specified TextInputFormat. It then splits the line into tokens separated by whitespaces, via theStringTokenizer, and emits a key-value pair of <
For the given sample input the first map emits:
The second map emits:
WordCount also specifies a combiner (line 54). Hence, the output of each map is passed through the local combiner (which is same as the Reducer as per the job configuration) for local aggregation, after being sorted on the keyss.
The output of the first map:
The output of the second map:
The Reducer implementation (lines 32-43), via the reduce method (lines 34-42) just sums up the values, which are the occurence counts for each key (i.e. words in this example).
Thus the output of the job is:
The run method specifies various facets of the job, such as the input/output paths (passed via the command line), key/value types, input/output formats etc., in the Job. It then calls the Job.waitForCompletion() (line 63) to submit the job to Hadoop and monitor its progress.
This section provides a reasonalbe amout of detail on every user-facing aspect of the MapReduce framework. This should help users implement, configure and tune their jobs in a fine-grained manner.
Applications typically extend the Mapper and Reducer classes to provide the map and reduce methods. Thsese form the core of the job.
Mapper maps input key/value pairs to a set of intermediate key/value pairs. Maps are the individual tasks that transform input records into intermediate records. The Hadoop MapReduce framewrok spawns one map task for eachInputSplit generated by the InputFormat for the job.
An InputSplit is a logical representation of a unit of input work for a map task; e.g., a filename and a byte range within that file to process. The InputFormat is responsible for enumerating the InputSplits, and producting aRecordReader which will turn those logical work units into actual physical input records.
(1) The Context object allows the mapper to interact with the rest of the Hadoop system. It includes configuration data for the job, as well as interfaces which allow it to emit output. The getConfiguration() method returns aConfiguration which contains configuration data for your program. You can set arbitrary (key, value) pairs of configuration data in your Job, e.g. with Job.getConfiguration().set("myKey", "myval"), and then retrieve this data in your mapper with Context.getConfiguration().get("myKey"). This sort of functionality is typically done in the Mapper's setup() method.
(2) The Mapper.run() method then calls map(KeyInType, ValInType, Context) for each key/value pair in the InputSplit for that task. Note that in the WordCount program's map() method, we then emit our output data via theContext argument, using its write() method.
(3) Applications can then override the Mapper's Cleanup() method to perform any required teardown operations.
(4) Output pairs are collected with calls to Context.write(KeyOutType, ValOutType).
(5) Applications can also use the Context to report progress, set application-level status messages and update Counters, or just indicate that they are alive.
(6) All intermediate values associated with a given output key are subsequently grouped by the framework, and passed to the Reducer(s) to determine the final output. Users can control the grouping by specifying a Comparator viaJob.setGroupingComparatorClass(class).
(7) The Mapper outputs are sorted and partitioned per Reducer. The total number of partitions is the same as the number of reduce tasks for the job. Users can control which keys (and hence records) go to which Reducer by implementing a custom Partitioner.
(8) Users can optionally specify a combiner, via Job.setCombinerClass(Class), to perform local aggregation of the intermediate outputs, which helps to cut down the amount of data transferred from the Mapper to the Reducer.
(9) The intermediate, sorted outputs are always stored in a simle (key-len, key, value-len, value) format. Applications can control if, and how, the intermediate outputs are to be compressed and the CompressionCodec to be used via the Job.
How Many Maps?
Reducer reduces a set of intermediate values which share a key to a (usually smaller) set of values. The number of reduces for the job is set by the user via Job.setNumReduceTasks(int).
The API of Reducer is very similar to that of Mapper; there's a run() method that receives a Context containing the job's configuration as well as interfacing methods that return data from the reducer itself back to the framework. Therun() method calls setup() once, reduce() once for each key associated with the reduce task, and cleanup() once at the end. Each of these methods can access the job's configuration data by using Context.getconfiguration().
The heart of Reducer is its reduce() method. This is called once per key; they second argument is an Iterable which returns all the values associated with that key. The Reducer should emit its final output (key, value) pairs with theContext.write() method. It may emit 0, 1, or more (key, value) pairs for each input.
Reducer has 3 primary phases: shuffle, sort and reduce.
The shuffle and sort phase occur simultaneously; while map-outputs are being fetched they are merged.
If equivalence rules for grouping the intermediate keys are required to be different from those for grouping keys before reduction, then one may specify a Comarator via Job.setGroupingComparatorClass(Class). Since this can be used to control how intermediate keys are grouped, these can be used in conjunction to simulate secondary sort on values.
The output of the reduce task is typically written to the FileSystem via Context.write(ReduceKeyType, ReduceOutValType).
Applications can use the Context to report progress, set application-level status messages and update counters, or just indicate that they are alive.
The output of the Reducer is not sorted.
The right number of reduces seems to be 0.95 or 1.75 multiplied by (
With 0.95 all of the reduces can launch immediately and start transfering map outputs as the maps finish. With 1.75 the faster nodes will finish their first round of reduces and launch a second wave of reduces doing a much better job of load balancing.
Increasing the number of reduces increases the framework overhead, but increases load balancing and lowers the cost of failures.
The scaling factors above are slightly less than whole numbers to reserve a few reduce slots in the framework for speculative-tasks and failed tasks.
It is legal to set the number of reduce-tasks to zero if no reduction is desired.
In this case the outputs of the map-tasks go directly to the FileSystem, into the output path set by setOutputPath(Path). The framework does not sort the map-outputs before writing them out to the FileSystem..
While applications iterate through the values for a given key, it is possible to mark the current position and later reset the iterator to this position and continue the iteration process. The corresponding methods are mark() and reset().
mark() and reset() can be called any number of times during the iteration cycle. The reset() method will reset the iterator to the last record before a call to the previous mark().
This functionality is avaiable only with the new context based reduce iterator.
Partitioner partitions the key space.
Partitioner controls the partitioning of the keys of the intermediate map-outputs. The key (or a subset of the key) is used to derive the partition, typically by a hash function. The total number of partitions is the same as the number of reduce tasks for the job. Hence this controls which of the m reduce tasks the intermediate key (and hence the record) is sent to for the reduction.
HashPatitioner is the default Partitioner.
Via the mapper or reducer's Context, MapReduce applications can report progress, set application-level status messages and update Counters.
Mapper and Reducer implementations can use the Context to report progress or just indicate that they are alive.
In scenarios where the application takes a significant amount of time to process individual key/value pairs, this is crucial since the framework might assume that the task has time-out and kill that task. Another way to avoid this is to set the configuration parameter mapreduce.task.timeout to a high-enough value (or even set it to zero for no time-outs).
Applications can also update Counters using the Context.
Hadoop MapReduce comes bundled with a library of generally useful mappers, reducers, and partitioners in the org.apache.hadoop.mapreduce.lib package.
The Job represents a MapReduce job configuration. The actual state for this object is written to an underlying instance of Configuration.
Job is the primary interface for a user to describe a MapReduce job to the Hadoop framework for execution.
The Job is typically used to specify the Mapper, combiner (if any), Partitioner, Reducer, InputFormat, OutputFormat and OutputCommitter implementations. Job also indicates the set of input files (setInputPaths(Job, Path…))/*addInputPath(Job,Path))* and (setInputPaths(Job, String)*/*(addInputPaths(Job,String)) and where the output files should be written (setOutputPath(Path)).
Of course, users can use Job.getConfiguration() to get access to the underlying configuration state, and can then use set(String, String)/get(String,String) to set/get arbitrary parameters needed by applications. However, use theDistributedCache for large amounts of (read-only) data.
The TaskTracker executes the Mapper/Reducer task as a child process in a separate jvm.
The child-task inherits the environment of the parent TaskTracker. The user can specify additional
The Job is the primary interface by which user-job interacts with the JobTracker.
Job provides facilities to submit jobs, track their progress, access component-tasks' reports and logs, get the MapReduce cluster's status information and so on.
The job submission process involves:
Normally the user creates the application, describes various facets of the job via Job, and then uses the waitForCompletion() method to submit the job and monitor its progress.
InputFormat describes the input-specification for a MapReduce job.
The MapReduce framework relies on the InputFormat of the job to:
The default behavior of file-based InputFormat implementations, typically sub-classes of FileInputFormat, is to split the input into logical InputSplit instances based on the total size, in bytes, of the input files. However, theFileSystem blocksize of the input files is treated as an upper bound for input splits. A lower bound on the split size can be set via mapreduce.input.fileinputformat.split.minsize.
TextInputFormat is the default InputFormat.
If TextInputFormat is the InputFormat for a given job, the framework detects input-files with the .gz extensions and automatically decompresses them using the appropriate CompressionCodec. However, it must be noted that compressed files with the above extensions cannot be split and each compressed file is processed in its entirety by a single mapper.
InputSplit represents the data to be processed by an individual Mapper.
Typically InputSplit presents a byte-oriented view of the input, and it is the responsibility of RecordReader to process and present a record-oriented view.
FileSplit is the default InputSplit. It sets mapreduce.map.input.file to the path of the input file for the logical split.
RecordReader reads
Typically the RecordReader converts the byte-oriented view of the input, provided by the InputSplit, and presents a record-oriented to the Mapper implementations for processing. RecordReader thus assumes the responsibility of processing record boundaries and presents the tasks with keys and values.
OutputFormat describes the output-specification for a MapReduce job.
The MapReduce framework relies on the OutputFormat of the job to:
TextOutputFormat is the default OutputFormat.
RecodWriter writes the output
The Tool interface supports the handling of generaic Hadoop command-line options.
IsolationRunner is a utility to help debug MapReduce programs.
Profiling is a utility to get a representative (2 or 3) sample of build-in java profiler for a sample of maps and reduces.
Here is a more complete WordCount which uses many of the features provided by the MapReduce framework we dicussed so far.
This example needs the HDFS to be up and running, especially for the DistributedCache-related features. Hence it only works with a pseudo-distributed (Single Node Setup) or fully-distributed (Cluster Setup) Hadoop installtation.
Sample text-files as input:
$ bin/hadoop fs -ls /user/joe/wordcount/input/Run the application:
$ bin/hadoop jar /user/joe/wordcount.jar org.myorg.WordCount2 /user/joe/wordcount/input /user/joe/wordcount/outputOutput:
$ bin/hadoop fs -cat /user/joe/wordcount/output/part-r-00000Notice that the inputs differ from the first version we looked at, and how they affect the outputs.
Now, lets plug-in a pattern-file which lists the word-patterns to be ignored, via the DistributedCache.
$ hadoop fs -cat /user/joe/wordcount/patterns.txtRun it again, this time with more options:
$ bin/hadoop jar /user/joe/wordcount.jar org.myorg.WordCount2 -Dwordcount.case.sensitive=true /user/joe/wordcount/input /user/joe/wordcount/output -skip /user/joe/wordcount/patterns.txtAs expected, the output:
$ bin/hadoop fs -cat /user/joe/wordcount/output/part-r-00000Run it once more, this time switch-off case-sensitivity:
$ bin/hadoop jar /user/joe/wordcount.jar org.myorg.WordCount2 -Dwordcount.case.sensitive=false /user/joe/wordcount/input /user/joe/wordcount/output -skip /user/joe/wordcount/patterns.txtSure enough, the output:
$ bin/hadoop fs -cat /user/joe/wordcount/output/part-r-00000
The second version of WordCount improves upon the previous one by using some features offered by the MapReduce framework:
-Demonstrates how the DistributedCache can be used to distribute read-only data needed by the jobs. Here it allows the user to specify word-patterns to skip while counting (line 119).
Date: 2011-03-10 14:55:39 EST
HTML generated by org-mode 7.4 in emacs 23