MR案例:路径过滤PathFilter

问题描述:现有一批cookie日志,按照日期进行存放,如目录 “dir/2015-08-08” 下存放2015-08-08这一天的所有cookie。而目录 “/2015-08-08/” 下又根据数据文件名称的不同存放不同项目的cookie,如 “project-flag-cookie” 文件中存放的是 flag 项目相关的cookie。

实际需求:统计出某一天属于项目A的唯一cookie数是多少?(唯一cookie是指去重)

1.自定义PathFilter类由于项目是根据文件名字来区分,所以就要把文件名不符合条件的过滤掉。

//Job配置文件设置
FileInputFormat.setInputPathFilter(job, CookieFilter.class);  

//自定义PathFilter类
public class CookieFilter implements PathFilter{

    @Override
    public boolean accept(Path path) {

        if (StringUtils.split(path.getName(), StringUtils.ESCAPE_CHAR, '-')[1].equals("A") {
            return true;
        }
        return false;
    }
}

2.去重并计数

Class Map extends Mapper<Longwritable, Text, Text, IntWritable>

    method map(){
        
         context.write( cookie , new IntWritable(1)); //Key:cookie     Value:1
    }

Class Reduce extends Reducer<Text, IntWritable, Text, IntWritable>

    method reduce(){

            for(IntWritable i : v2s){

                 Sum += i.set();

                 context.write(cookie , Sum); //Key:cookie     Value:Sum
             }
    }

2.HDFS中的文件名通配与过滤

hdfs通配符和Linux的相一致。若存在如下目录:

/test/in/logs/2015/08/07/log-A-2015080701
/test/in/logs/2015/08/07/log-A-2015080702
/test/in/logs/2015/08/07/log-A-2015080703
/test/in/logs/2015/08/08/log-A-2015080801 /test/in/logs/2015/08/08/log-A-2015080802

1).只处理log-A-2015080701和log-A-2015080702两个文件.
  ①输入路径指定"/test/in/logs/2015/08/07/log-A-201508070{1,2}"

  ②自定义PathFilter类,重写其中的accept()方法

2).处理全部文件.

  输入路径指定"/test/in/logs/2015/08/*/*"

posted @ 2015-08-20 15:57  skyl夜  阅读(892)  评论(0编辑  收藏  举报