MapReduce之倒排索引

文件:
a.txt
welcome tom
welcome tomm
welcome kitty
welcome james
welcome tom
b.txt
welcome james
welcome tom
welcome kitty
c.txt
welcome tom
welcome tomm
welcome james

static {
        System.setProperty("hadoop.home.dir","E:/x3/hadoop-2.9.2");
    }
//map
public static class MyMapper extends Mapper<LongWritable,Text,Text,Text>{
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] split = value.toString().split("\t");
        //获取文件名
        String name = ((FileSplit) context.getInputSplit()).getPath().getName();
       for (String str : split){
           context.write(new Text(str),new Text(name+"->1"));
       }
    }
}

//reduce
public static class MyReduce extends Reducer<Text,Text,Text,Text>{
    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        //<welcome,"a->1,b->1">
        HashMap<String, Integer> map = new HashMap<>();
        for(Text value:values){
            String[] split = value.toString().split("->");
            //判断集合中是否有值
            if(map.get(split[0])==null){
                map.put(split[0],Integer.parseInt(split[1]));
            }else{
                map.put(split[0],map.get(split[0])+1);
            }
        }
        //<welcome,[a->2,b->1]>
        StringBuffer stringBuffer = new StringBuffer();
        //遍历map集合
        for(Map.Entry<String,Integer> mm : map.entrySet()){
            stringBuffer.append(mm.getKey()).append("->").append(mm.getValue());
            stringBuffer.append(",");
        }
        String substring = stringBuffer.substring(0, stringBuffer.length() - 1);
        context.write(key,new Text(substring));

    }
}


public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

    Configuration conf = new Configuration();
    Job job = Job.getInstance(conf, "daopai");

    FileInputFormat.addInputPaths(job,args[0]);

    job.setMapperClass(MyMapper.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(Text.class);

    job.setReducerClass(MyReduce.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);

    FileOutputFormat.setOutputPath(job,new Path(args[1]));

    boolean result = job.waitForCompletion(true);
    System.out.println(result);
}

最终结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值