如何使用hadoop在Mapper中对齐

时间:2015-10-29 08:52:47

标签: hadoop

下面的源代码:

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);
      }
     */     

            String delimeter = " ";
            String[] temp;
            String token = value.toString();
            temp = token.split(delimeter);
            for (int i = 0; i < temp.length; i++) {
               for(int j=0;j < temp.length;j++){
                   word.set(temp[i]+","+temp[j]);
                   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);
  }
}

我为了我们的目的重写了WordCountv1.0版本

专注于地图功能

思考: 如果输入数据为a b c d 我将它们撕成a ,b ,c ,d

并为结果执行单词align:aa,ab ,ac ,ad,ba,bb,bc,bd ....

并给它一个字数1

context.write(word, one); 

并将其丢弃以计算计数

但它不起作用,我应该如何更改我的代码?

1 个答案:

答案 0 :(得分:0)

只需声明

的变量字即可

private Text word;

而不是

  private Text word = new Text();

并更改for循环,如下所示: -

String delimeter = " ";
            String[] temp;
            String token = value.toString();
            temp = token.split(delimeter);
            for (int i = 0; i < temp.length; i++) {
               for(int j=0;j < temp.length;j++){
                 word = new Text(temp[i]+temp[j]);
                 context.write(word, one);
               }
            }