- Start the HDFS services:
bashstart-dfs.sh
- Start the YARN services:
bashstart-yarn.sh
Step 6: Write a MapReduce Program
- Create your MapReduce program. Here’s a basic WordCount program (in Java):
javaimport org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.util.GenericOptionsParser;
import java.io.IOException;
import java.util.StringTokenizer;
public class WordCount {
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer tokenizer = new StringTokenizer(value.toString());
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
GenericOptionsParser parser = new GenericOptionsParser(conf, args);
String[] remainingArgs = parser.getRemainingArgs();
if (remainingArgs.length != 2) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(remainingArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(remainingArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
Step 7: Compile and Build the Program
Compile your Java program and create a .jar
file.
bashjavac -classpath $(hadoop classpath) -d /path/to/output/WordCountClasses WordCount.java jar -cvf wordcount.jar -C /path/to/output/WordCountClasses/ .
Step 8: Run the MapReduce Program
- Upload input files to HDFS:
bashhdfs dfs -mkdir /input
hdfs dfs -put /local/path/to/input_file /input
- Run the program:
bashhadoop jar wordcount.jar WordCount /input /output
- View the output:
bashhdfs dfs -cat /output/part-r-00000
Step 9: Stop Hadoop
When done, stop Hadoop services:
bashstop-yarn.sh stop-dfs.sh
No comments:
Post a Comment