Hadoop基礎(二十八):資料清洗(ETL)(一)簡單解析版
阿新 • • 發佈:2020-07-19
資料清洗案例實操-簡單解析版
在執行核心業務MapReduce程式之前,往往要先對資料進行清洗,清理掉不符合使用者要求的資料。清理的過程往往只需要執行Mapper程式,不需要執行Reduce程式。
1.需求
去除日誌中欄位長度小於等於11的日誌。
(1)輸入資料
(2)期望輸出資料
每行欄位長度都大於11。
2.需求分析
需要在Map階段對輸入的資料根據規則進行過濾清洗。
3.實現程式碼
(1)編寫LogMapper類
package com.atguigu.mapreduce.weblog; import java.io.IOException; import org.apache.hadoop.io.LongWritable;View Codeimport org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class LogMapper extends Mapper<LongWritable, Text, Text, NullWritable>{ Text k = new Text(); @Override protected void map(LongWritable key, Text value, Context context) throwsIOException, InterruptedException { // 1 獲取1行資料 String line = value.toString(); // 2 解析日誌 boolean result = parseLog(line,context); // 3 日誌不合法退出 if (!result) { return; } // 4 設定key k.set(line);// 5 寫出資料 context.write(k, NullWritable.get()); } // 2 解析日誌 private boolean parseLog(String line, Context context) { // 1 擷取 String[] fields = line.split(" "); // 2 日誌長度大於11的為合法 if (fields.length > 11) { // 系統計數器 context.getCounter("map", "true").increment(1); return true; }else { context.getCounter("map", "false").increment(1); return false; } } }
(2)編寫LogDriver類
package com.atguigu.mapreduce.weblog; 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; public class LogDriver { public static void main(String[] args) throws Exception { // 輸入輸出路徑需要根據自己電腦上實際的輸入輸出路徑設定 args = new String[] { "e:/input/inputlog", "e:/output1" }; // 1 獲取job資訊 Configuration conf = new Configuration(); Job job = Job.getInstance(conf); // 2 載入jar包 job.setJarByClass(LogDriver.class); // 3 關聯map job.setMapperClass(LogMapper.class); // 4 設定最終輸出型別 job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); // 設定reducetask個數為0 job.setNumReduceTasks(0); // 5 設定輸入和輸出路徑 FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); // 6 提交 job.waitForCompletion(true); } }