数据清洗(ETL)

运行核心业务MapReduce程序之前,往往要先对数据进行清洗,清理掉不符合用户要求的数据。清理的过程往往只需要运行Mapper程序,不需要运行Reduce程序。

1.需求

去除日志中字段个数小于等于11的日志。

1)期望输出数据

每行字段长度都大于11。

2.需求分析

需要在Map阶段对输入的数据根据规则进行过滤清洗。

3.实现代码

(1)编写Mapper类

package com.etl;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class ETLMapper extends Mapper {
    private Counter pass;
    private Counter fail;


    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        pass = context.getCounter("ETL","Pass");
        fail = context.getCounter("ETl","Fail");
    }

    /**
     * 判读日志是否学院清洗
     *
     * @param key
     * @param value
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //获取一行数据
        String line = value.toString();
        String[] split = line.split(" ");
        //只有日志长度大于11的才保留
        if (split.length > 11) {
            context.write(value,NullWritable.get());
            pass.increment(1);
        }else {
            fail.increment(1);
        }
    }
}

(2)编写Driver类

package com.etl;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


import java.io.IOException;

public class ETLDriver {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Job job = Job.getInstance(new Configuration());

        job.setJarByClass(ETLDriver.class);
        job.setMapperClass(ETLMapper.class);
        //不需要reduce阶段
        job.setNumReduceTasks(0);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);

        FileInputFormat.setInputPaths(job, new Path("D:\\input\\*"));
        FileOutputFormat.setOutputPath(job, new Path("D:\\output"));
        boolean b = job.waitForCompletion(true);

        System.exit(b ? 0 : 1);
    }
}

你可能感兴趣的:(etl,mapreduce,hadoop)