ハドゥープのマップリデュースの使い方は?

HadoopのMapReduceを使用するには、以下の手順に従う必要があります。

  1. Map関数の定義:Map関数とは、入力データをキーと値のペアに分割するプロセスです。入力データをどのようにキーと値のペアに変換するかを定義するために、Map関数を記述する必要があります。
  2. Reduce関数の定義:Reduce関数は、Map関数の出力されたキーと値を処理するプロセスです。Map関数の出力されたキーと値を処理する方法を定義するために、Reduce関数を作成する必要があります。
  3. MapReduceジョブの構成:MapReduceジョブの各種パラメーターを設定するために、Hadoopの設定ファイルを使用する必要があります。入力パス、出力パス、Map関数、Reduce関数などのパラメーターを設定してください。
  4. MapReduceジョブを実行するには、Hadoopのコマンドラインツールやプログラミングインターフェースを使用してジョブを提出および実行できます。

以下是一个使用Hadoop MapReduce的示例代码:

import 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.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

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 itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.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();
    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(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}

このサンプルコードは簡単な単語カウントプログラムです。入力ファイル内の各単語をキーと値の組に分割し、それぞれの単語の出現回数をカウントします。最後に、各単語とその出現回数を出力します。

Hadoopのコマンドラインツールを使用してこのコードをJARファイルにパッケージ化し、次のコマンドを使用してMapReduceジョブを提出して実行できます。

hadoop jar WordCount.jar WordCount input output

WordCountは、JARファイルの名前であり、inputは入力ファイルのパス、outputは出力ファイルのパスです。

MapReduceジョブを実行する前には、Hadoopクラスタのインストールと設定が必要であり、またクラスタが稼働していることを確認してください。

bannerAds