資料清洗(ETL)
- 簡介
- 1)需求
- 2)需求分析
- 3)實作代碼
- (1)撰寫 WebLogMapper 類
- (2)撰寫 WebLogDriver 類
簡介
“ETL,是英文 Extract-Transform-Load 的縮寫,用來描述將資料從來源端經過抽取(Extract)、轉換(Transform)、加載(Load)至目的端的程序,
ETL 一詞較常用在資料倉庫,但其物件并不限于資料倉庫.
在運行核心業務 MapReduce 程式之前,往往要先對資料進行清洗,清理掉不符合用戶要求的資料,清理的程序往往只需要運行 Mapper 程式,不需要運行 Reduce 程式,
1)需求
去除日志中欄位個數小于等于 11 的日志,
(1)輸入資料

(2)期望輸出資料
每行欄位長度都大于 11,
2)需求分析
需要在 Map 階段對輸入的資料根據規則進行過濾清洗,
3)實作代碼
(1)撰寫 WebLogMapper 類
package com.zs.mapreduce.etl;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class WebLogMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// 1. 獲取一行
String line = value.toString();
// 2.ETL
boolean result = parseLog(line, context);
if (!result) {
return;
}
// 3.寫出
context.write(value, NullWritable.get());
}
private boolean parseLog(String line, Context context) {
// 切割
String[] fields = line.split(" ");
// 判斷一下日志的長度是否大于11
if (fields.length > 11) {
return true;
} else {
return false;
}
}
}
(2)撰寫 WebLogDriver 類
package com.zs.mapreduce.etl;
import com.zs.mapreduce.outputformat.LogDriver;
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 WebLogDriver {
public static void main(String[] args) throws Exception {
// 輸入輸出路徑需要根據自己電腦上實際的輸入輸出路徑設定
args = new String[] { "D:\\software\\hadoop\\input\\inputlog", "D:\\software\\hadoop\\output\\outputetl" };
// 1 獲取 job 資訊
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
// 2 加載 jar 包
job.setJarByClass(LogDriver.class);
// 3 關聯 map
job.setMapperClass(WebLogMapper.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 提交
boolean b = job.waitForCompletion(true);
System.exit(b ? 0 : 1);
}
}
加油!
感謝!
努力!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/301703.html
標籤:其他
