MapReduceプログラムを作成する基本的な手順は次のとおりです:

  1. Mapperインターフェースを実装したクラスを作成し、mapメソッドをオーバーライドします。mapメソッドは、キーと値のペアを受け取り、入力データを処理して中間のキーと値のペアとして出力します。
public class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public 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);
        }
    }
}
  1. Reducerインターフェースを実装したクラスを作成し、reduceメソッドをオーバーライドしてください。reduceメソッドは、中間のキーと値を入力として受け取り、キーに基づいてデータを集計し、最終的な結果のキーと値として出力します。
public class MyReducer 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);
    }
}
  1. MapReduceジョブの関連パラメータを設定する構成オブジェクトを作成します。
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
  1. 入力データのパスと出力結果のパスを指定してください。
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
  1. MapperとReducerのクラスを設定してください。
job.setMapperClass(MyMapper.class);
job.setCombinerClass(MyReducer.class);
job.setReducerClass(MyReducer.class);
  1. 最終結果のキーと値のペアのタイプを設定します。
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
  1. マップリデュースのジョブを提出してください。
System.exit(job.waitForCompletion(true) ? 0 : 1);

以上はMapReduceプログラムを書く基本的なステップです。具体的な要件に応じて、MapperやReducerのロジックを拡張や修正することができます。

bannerAds