Hadoop Streaming

Hadoop streaming is a utility that comes with the Hadoop distribution. The utility allows you to create and run Map/Reduce jobs with any executable or script as the mapper and/or the reducer. For example:

How Streaming Works

In the above example, both the mapper and the reducer are executables that read the input from stdin (line by line) and emit the output to stdout. The utility will create a Map/Reduce job, submit the job to an appropriate cluster, and monitor the progress of the job until it completes.

When an executable is specified for mappers, each mapper task will launch the executable as a separate process when the mapper is initialized. As the mapper task runs, it converts its inputs into lines and feed the lines to the stdin of the process. In the meantime, the mapper collects the line oriented outputs from the stdout of the process and converts each line into a key/value pair, which is collected as the output of the mapper. By default, the prefix of a line up to the first tab character is the key and the rest of the line (excluding the tab character) will be the value. If there is no tab character in the line, then entire line is considered as key and the value is null. However, this can be customized by setting -inputformat command option, as discussed later.

When an executable is specified for reducers, each reducer task will launch the executable as a separate process then the reducer is initialized. As the reducer task runs, it converts its input key/values pairs into lines and feeds the lines to the stdin of the process. In the meantime, the reducer collects the line oriented outputs from the stdout of the process, converts each line into a key/value pair, which is collected as the output of the reducer. By default, the prefix of a line up to the first tab character is the key and the rest of the line (excluding the tab character) is the value. However, this can be customized by setting -outputformat command option, as discussed later.

This is the basis for the communication protocol between the Map/Reduce framework and the streaming mapper/reducer.

User can specify stream.non.zero.exit.is.failure as true or false to make a streaming task that exits with a non-zero status to be Failure or Success respectively. By default, streaming tasks exiting with non-zero status are considered to be failed tasks.

Streaming Command Options

Streaming supports streaming command options as well as generic command options. The general command line syntax is shown below.

You can specify stream.non.zero.exit.is.failure as true or false to make a streaming task that exits with a non-zero status to be Failure or Success respectively. By default, streaming tasks exiting with non-zero status are considered to be failed tasks.

Packaging Files With Job Submissions

You can specify any executable as the mapper and/or the reducer. The executables do not need to pre-exist on the machines in the cluster; however, if they don’t, you will need to use “-file” option to tell the framework to pack your executable files as a part of job submission. For example:

The above example specifies a user defined Python executable as the mapper. The option “-file myPythonScript.py” causes the python executable shipped to the cluster machines as a part of job submission.

In addition to executable files, you can also package other auxiliary files (such as dictionaries, configuration files, etc) that may be used by the mapper and/or the reducer. For example:

The class you supply for the input format should return key/value pairs of Text class. If you do not specify an input format class, the TextInputFormat is used as the default. Since the TextInputFormat returns keys of LongWritable class, which are actually not part of the input data, the keys will be discarded; only the values will be piped to the streaming mapper.

The class you supply for the output format is expected to take key/value pairs of Text class. If you do not specify an output format class, the TextOutputFormat is used as the default.

Setting Environment Variables

To set an environment variable in a streaming command use:

-cmdenv EXAMPLE_DIR=/home/example/dictionaries/

Generic Command Options

Streaming supports streaming command options as well as generic command options. The general command line syntax is shown below.

Specifying Map-Only Jobs

Often, you may want to process input data using a map function only. To do this, simply set mapreduce.job.reduces to zero. The Map/Reduce framework will not create any reducer tasks. Rather, the outputs of the mapper tasks will be the final output of the job.

-D mapreduce.job.reduces=0

To be backward compatible, Hadoop Streaming also supports the “-reducer NONE” option, which is equivalent to “-D mapreduce.job.reduces=0”.

Specifying the Number of Reducers

Customizing How Lines are Split into Key/Value Pairs

As noted earlier, when the Map/Reduce framework reads a line from the stdout of the mapper, it splits the line into a key/value pair. By default, the prefix of the line up to the first tab character is the key and the rest of the line (excluding the tab character) is the value.

However, you can customize this default. You can specify a field separator other than the tab character (the default), and you can specify the nth (n >= 1) character rather than the first character in a line (the default) as the separator between the key and value. For example:

In the above example, “-D stream.map.output.field.separator=.” specifies “.” as the field separator for the map outputs, and the prefix up to the fourth “.” in a line will be the key and the rest of the line (excluding the fourth “.”) will be the value. If a line has less than four “.“s, then the whole line will be the key and the value will be an empty Text object (like the one created by new Text(””)).

Similarly, you can use “-D stream.reduce.output.field.separator=SEP” and “-D stream.num.reduce.output.fields=NUM” to specify the nth field separator in a line of the reduce outputs as the separator between the key and the value.

Similarly, you can specify “stream.map.input.field.separator” and “stream.reduce.input.field.separator” as the input separator for Map/Reduce inputs. By default the separator is the tab character.

Working with Large Files and Archives

The -files and -archives options allow you to make files and archives available to the tasks. The argument is a URI to the file or archive that you have already uploaded to HDFS. These files and archives are cached across jobs. You can retrieve the host and fs_port values from the fs.default.name config variable.

Note: The -files and -archives options are generic options. Be sure to place the generic options before the command options, otherwise the command will fail.

Making Files Available to Tasks

The -files option creates a symlink in the current working directory of the tasks that points to the local copy of the file.

In this example, Hadoop automatically creates a symlink named testfile.txt in the current working directory of the tasks. This symlink points to the local copy of testfile.txt.

Making Archives Available to Tasks

The -archives option allows you to copy jars locally to the current working directory of tasks and automatically unjar the files.

In this example, Hadoop automatically creates a symlink named testfile.jar in the current working directory of tasks. This symlink points to the directory that stores the unjarred contents of the uploaded jar file.

-archives hdfs://host:fs_port/user/testfile.jar

User can specify a different symlink name for -archives using #.

-archives hdfs://host:fs_port/user/testfile.tgz#tgzdir

In this example, the input.txt file has two lines specifying the names of the two files: cachedir.jar/cache.txt and cachedir.jar/cache2.txt. “cachedir.jar” is a symlink to the archived directory, which has the files “cache.txt” and “cache2.txt”.

More Usage Examples

Hadoop Partitioner Class

Hadoop has a library class, KeyFieldBasedPartitioner, that is useful for many applications. This class allows the Map/Reduce framework to partition the map outputs based on certain key fields, not the whole keys. For example:

Here, -D stream.map.output.field.separator=. and -D stream.num.map.output.key.fields=4 are as explained in previous example. The two variables are used by streaming to identify the key/value pair of mapper.

The map output keys of the above Map/Reduce job normally have four fields separated by “.”. However, the Map/Reduce framework will partition the map outputs by the first two fields of the keys using the -D mapred.text.key.partitioner.options=-k1,2 option. Here, -D map.output.key.field.separator=. specifies the separator for the partition. This guarantees that all the key/value pairs with the same first two fields in the keys will be partitioned into the same reducer.

This is effectively equivalent to specifying the first two fields as the primary key and the next two fields as the secondary. The primary key is used for partitioning, and the combination of the primary and secondary keys is used for sorting. A simple illustration is shown here:

Output of map (the keys)

11.12.1.2
11.14.2.3
11.11.4.1
11.12.1.1
11.14.2.2

Partition into 3 reducers (the first 2 fields are used as keys for partition)

The map output keys of the above Map/Reduce job normally have four fields separated by “.”. However, the Map/Reduce framework will sort the outputs by the second field of the keys using the -D mapreduce.partition.keycomparator.options=-k2,2nr option. Here, -n specifies that the sorting is numerical sorting and -r specifies that the result should be reversed. A simple illustration is shown below:

Output of map (the keys)

11.12.1.2
11.14.2.3
11.11.4.1
11.12.1.1
11.14.2.2

Sorting output for the reducer (where second field used for sorting)

11.14.2.3
11.14.2.2
11.12.1.2
11.12.1.1
11.11.4.1

Hadoop Aggregate Package

Hadoop has a library package called Aggregate. Aggregate provides a special reducer class and a special combiner class, and a list of simple aggregators that perform aggregations such as “sum”, “max”, “min” and so on over a sequence of values. Aggregate allows you to define a mapper plugin class that is expected to generate “aggregatable items” for each input key/value pair of the mappers. The combiner/reducer will aggregate those aggregatable items by invoking the appropriate aggregators.

Hadoop Field Selection Class

Hadoop has a library class, FieldSelectionMapReduce, that effectively allows you to process text data like the unix “cut” utility. The map function defined in the class treats each input key/value pair as a list of fields. You can specify the field separator (the default is the tab character). You can select an arbitrary list of fields as the map output key, and an arbitrary list of fields as the map output value. Similarly, the reduce function defined in the class treats each input key/value pair as a list of fields. You can select an arbitrary list of fields as the reduce output key, and an arbitrary list of fields as the reduce output value. For example:

The option “-D mapreduce.fieldsel.map.output.key.value.fields.spec=6,5,1-3:0-” specifies key/value selection for the map outputs. Key selection spec and value selection spec are separated by “:”. In this case, the map output key will consist of fields 6, 5, 1, 2, and 3. The map output value will consist of all fields (0- means field 0 and all the subsequent fields).

The option “-D mapreduce.fieldsel.reduce.output.key.value.fields.spec=0-2:5-” specifies key/value selection for the reduce outputs. In this case, the reduce output key will consist of fields 0, 1, 2 (corresponding to the original fields 6, 5, 1). The reduce output value will consist of all fields starting from field 5 (corresponding to all the original fields).

Frequently Asked Questions

How do I use Hadoop Streaming to run an arbitrary set of (semi) independent tasks?

Often you do not need the full power of Map Reduce, but only need to run multiple instances of the same program - either on different parts of the data, or on the same data, but with different parameters. You can use Hadoop Streaming to do this.

How do I process files, one per map?

As an example, consider the problem of zipping (compressing) a set of files across the hadoop cluster. You can achieve this by using Hadoop Streaming and custom mapper script:

Generate a file containing the full HDFS path of the input files. Each map task would get one file name as input.

Create a mapper script which, given a filename, will get the file to local disk, gzip the file and put it back in the desired output directory.

(boolean) ‘slowmatch’ - Toggle to look for begin and end characters, but within CDATA instead of regular tags. Defaults to false.

(integer) ‘lookahead’ - Maximum lookahead bytes to sync CDATA when using ‘slowmatch’, should be larger than ‘maxrec’. Defaults to 2*‘maxrec’.

(integer) ‘maxrec’ - Maximum record size to read between each match during ‘slowmatch’. Defaults to 50000 bytes.

How do I update counters in streaming applications?

A streaming process can use the stderr to emit counter information. reporter:counter:<group>,<counter>,<amount> should be sent to stderr to update the counter.

How do I update status in streaming applications?

A streaming process can use the stderr to emit status information. To set a status, reporter:status:<message> should be sent to stderr.

How do I get the Job variables in a streaming job’s mapper/reducer?

See Configured Parameters. During the execution of a streaming job, the names of the “mapred” parameters are transformed. The dots ( . ) become underscores ( _ ). For example, mapreduce.job.id becomes mapreduce_job_id and mapreduce.job.jar becomes mapreduce_job_jar. In your code, use the parameter names with the underscores.

What do I do if I get a “error=7, Argument list too long”

The job copies the whole configuration to the environment. If the job is processing a large number of input files adding the job configuration to the environment could cause an overrun of the environment. The job configuration copy in the environment is not essential for running the job and can be truncated by setting:

-D stream.jobconf.truncate.limit=20000

By default the values are not truncated (-1). Zero (0) will only copy the names and not values. For almost all cases 20000 is a safe value that will prevent the overrun of the environment.