Skip to content

Instantly share code, notes, and snippets.

@kzk
Created November 23, 2010 16:27
Show Gist options
  • Save kzk/712029 to your computer and use it in GitHub Desktop.
Save kzk/712029 to your computer and use it in GitHub Desktop.
package net.kzk9;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
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.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;
public class WordCount {
// Mapperの実装
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
// Reducerの実装
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable value = new IntWritable(0);
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable value : values)
sum += value.get();
value.set(sum);
context.write(key, value);
}
}
public static void main(String[] args) throws Exception {
// 設定情報の読み込み
Configuration conf = new Configuration();
// 引数のパース
GenericOptionsParser parser = new GenericOptionsParser(conf, args);
args = parser.getRemainingArgs();
// ジョブの作成
Job job = new Job(conf, "wordcount");
job.setJarByClass(WordCount.class);
// Mapper/Reducerに使用するクラスを指定
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
// ジョブ中の各種型を設定
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// 入力/出力フォーマットを設定
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setNumReduceTasks(1);
// 入力/出力パスを設定
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// ジョブをJobTrackerにサブミット
boolean success = job.waitForCompletion(true);
System.out.println(success);
}
}
@javadAli
Copy link

Great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment