How to get Filename/File Contents as key/value input for MAP when running a Hadoop MapReduce Job?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In the context of Hadoop MapReduce, processing files and their contents efficiently as key/value pairs is crucial for many big data applications. This article will elaborate on how to get the filename and file contents as key/value input for a MapReduce job, utilizing the Hadoop API, and will also include a practical example.
Understanding Hadoop MapReduce InputFormats
Hadoop MapReduce uses InputFormats to define how input files are split and read. Each InputFormat provides implementations for:
InputSplit: Logical representation of data split.RecordReader: Process to read the input split data into key/value pairs.
The default InputFormat in Hadoop is TextInputFormat, which treats each line of input files as a separate record. It assigns the byte offset as the key and the line content as the value, and does not provide the file name in the key. To include the file name, you must use or customize an InputFormat.
Customizing InputFormat to Include Filename
To retrieve both the filename and its contents as key/value pairs, you will have to implement a custom InputFormat. Here's how to do it:
1. Custom InputFormat Class
Create a custom class that extends FileInputFormat<KEYOUT, VALUEOUT>, overriding the createRecordReader method. This method should return a new instance of your custom RecordReader.
2. Custom RecordReader Class
Develop a RecordReader class that can read the input splits and process files to emit filename as key and content as value.
3. Configuring Job to Use Custom InputFormat
In your MapReduce driver code, set the InputFormat class to your custom class:
Key Benefits and Points
| Feature | Description |
| File as Key | Easily identify the source file in map/reduce tasks. |
| Customizability | Flexibility in processing file content beyond line-wise. |
| Efficiency | Process each file only once without redundant I/O. |
| Scalability | Suitable for expanding datasets and larger applications. |
Conclusion
Implementing a custom InputFormat and RecordReader for processing filenames along with their contents as key/value pairs can be highly beneficial. This approach allows for more effective data processing pipelines, providing context (file metadata) alongside data (content), indispensable for many analytical and data transformation tasks in big data platforms like Hadoop.

