Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

自定義 Hadoop 輸入切割:改分隔符與按主鍵分塊的 InputFormat 實作

Hadoop 會先對原始輸入檔案做切割,再把每個 split 交給 mapper 處理。FileInputFormat 是所有以檔案為資料源的 InputFormat 實作的基類,它保存作為 job 輸入的所有檔案,並實作了計算 splits 的方法;至於如何取得記錄,則交由不同子類實作。

FileInputFormat 只切分比 HDFS block 大的檔案,因此小於 block 的檔不會被切分——這也是 Hadoop 處理大檔案比處理大量小檔案更有效率的原因。

Hadoop 預設的 InputFormat 是 TextInputFormat,它重寫了 createRecordReader 與 isSplitable,使用的 reader 是 LineRecordReader,即以回車鍵(CR = 13)或換行符(LF = 10)作為行分隔符。

但多數情況下,回車或換行並不能滿足需求。使用者輸入時很可能打出這兩個字符,因此實務上通常會改用不可見字符作為行分隔符,這時就得自寫 InputFormat。更棘手的情況是分隔符不是單一字符而是字串;還有一種場景是輸入檔的主鍵 key 本身已排好序,Hadoop 只需把相同 key 的記錄聚成一個邏輯塊處理,相當於省掉 mapper 直接進 reduce,InputFormat 的邏輯最為複雜,但並非不可實作。

1、改變一條記錄的分隔符

1)自定義 InputFormat,繼承 FileInputFormat,重寫 createRecordReader;若不需分片或要改變分片方式,則重寫 isSplitable:

public class FileInputFormatB extends FileInputFormat<LongWritable, Text> {

@Override

public RecordReader<LongWritable, Text> createRecordReader( InputSplit split, TaskAttemptContext context) {
return new SearchRecordReader("\b");

}

@Override
protected boolean isSplitable(FileSystem fs, Path filename) {
// 輸入文件不分片
return false;
}
}

2)關鍵在於定義新的 RecordReader,支援自訂分隔符。標紅處即與 Hadoop 預設 LineRecordReader 不同的地方。

public class IsearchRecordReader extends RecordReader<LongWritable, Text> {
private static final Log LOG = LogFactory.getLog(IsearchRecordReader.class);

private CompressionCodecFactory compressionCodecs = null;
private long start;
private long pos;
private long end;
private LineReader in;
private int maxLineLength;
private LongWritable key = null;
private Text value = null;
//行分隔符,即一條記錄的分隔符
private byte[] separator = {'\b'};
private int sepLength = 1;

‍ public IsearchRecordReader(){
}
public IsearchRecordReader(String seps){
this.separator = seps.getBytes();
sepLength = separator.length;
}

public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException {
FileSplit split = (FileSplit) genericSplit;
Configuration job = context.getConfiguration();
this.maxLineLength = job.getInt("mapred.linerecordreader.maxlength", Integer.MAX_VALUE);

this.start = split.getStart();
this.end = (this.start + split.getLength());
Path file = split.getPath();
this.compressionCodecs = new CompressionCodecFactory(job);
CompressionCodec codec = this.compressionCodecs.getCodec(file);

// open the file and seek to the start of the split
FileSystem fs = file.getFileSystem(job);
FSDataInputStream fileIn = fs.open(split.getPath());
boolean skipFirstLine = false;
if (codec != null) {
this.in = new LineReader(codec.createInputStream(fileIn), job);
this.end = Long.MAX_VALUE;
} else {
if (this.start != 0L) {
skipFirstLine = true;
this.start -= sepLength;
fileIn.seek(this.start);
}
this.in = new LineReader(fileIn, job);
}
if (skipFirstLine) { // skip first line and re-establish "start".
int newSize = in.readLine(new Text(), 0, (int) Math.min( (long) Integer.MAX_VALUE, end - start));

if(newSize > 0){
start += newSize;
}
}

this.pos = this.start;
}

public boolean nextKeyValue() throws IOException {
if (this.key == null) {
this.key = new LongWritable();
}
this.key.set(this.pos);
if (this.value == null) {
this.value = new Text();
}
int newSize = 0;
while (this.pos < this.end) {
newSize = this.in.readLine(this.value, this.maxLineLength, Math.max(
(int) Math.min(Integer.MAX_VALUE, this.end - this.pos), this.maxLineLength));

if (newSize == 0) {
break;
}
this.pos += newSize;
if (newSize < this.maxLineLength) {
break;
}

LOG.info("Skipped line of size " + newSize + " at pos " + (this.pos - newSize));
}

if (newSize == 0) {
//讀下一個buffer
this.key = null;
this.value = null;
return false;
}
//讀同一個buffer的下一個記錄
return true;
}

public LongWritable getCurrentKey() {
return this.key;
}

public Text getCurrentValue() {
return this.value;
}

public float getProgress() {
if (this.start == this.end) {
return 0.0F;
}
return Math.min(1.0F, (float) (this.pos - this.start) / (float) (this.end - this.start));
}

public synchronized void close() throws IOException {
if (this.in != null)
this.in.close();
}

}

3)重寫所需的 LineReader 可作為內部類。特別需要注意的是,檔案是按固定大小 buffer 讀取的,必定會遇到一條完整記錄被切成兩半、甚至分隔符本身也被切開的情況,這兩種都必須做拼接處理。

public class LineReader {
//回車鍵(hadoop默認)
//private static final byte CR = 13;
//換行符(hadoop默認)
//private static final byte LF = 10;

//按buffer進行文件讀取
private static final int DEFAULT_BUFFER_SIZE = 32 * 1024 * 1024;
private int bufferSize = DEFAULT_BUFFER_SIZE;
private InputStream in;
private byte[] buffer;
private int bufferLength = 0;
private int bufferPosn = 0;

LineReader(InputStream in, int bufferSize) {
this.bufferLength = 0;
this.bufferPosn = 0;

this.in = in;
this.bufferSize = bufferSize;
this.buffer = new byte[this.bufferSize];
}

public LineReader(InputStream in, Configuration conf) throws IOException {
this(in, conf.getInt("io.file.buffer.size", DEFAULT_BUFFER_SIZE));
}

public void close() throws IOException {
in.close();
}

public int readLine(Text str, int maxLineLength) throws IOException {
return readLine(str, maxLineLength, Integer.MAX_VALUE);
}

public int readLine(Text str) throws IOException {
return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE);
}

//以下是需要改寫的部分_start,核心代碼

public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException{
str.clear();
Text record = new Text();
int txtLength = 0;
long bytesConsumed = 0L;
boolean newline = false;
int sepPosn = 0;

do {
//已經讀到buffer的末尾了,讀下一個buffer
if (this.bufferPosn >= this.bufferLength) {
bufferPosn = 0;
bufferLength = in.read(buffer);

//讀到文件末尾了,則跳出,進行下一個文件的讀取
if (bufferLength <= 0) {
break;
}
}

int startPosn = this.bufferPosn;
for (; bufferPosn < bufferLength; bufferPosn ++) {
//處理上一個buffer的尾巴被切成了兩半的分隔符(如果分隔符中重復字符過多在這裡會有問題)
if(sepPosn > 0 && buffer[bufferPosn] != separator[sepPosn]){
sepPosn = 0;
}

//遇到行分隔符的第一個字符
if (buffer[bufferPosn] == separator[sepPosn]) {
bufferPosn ++;
int i = 0;

//判斷接下來的字符是否也是行分隔符中的字符
for(++ sepPosn; sepPosn < sepLength; i ++, sepPosn ++){

//buffer的最後剛好是分隔符,且分隔符被不幸地切成了兩半
if(bufferPosn + i >= bufferLength){
bufferPosn += i - 1;
break;
}

//一旦其中有一個字符不相同,就判定為不是分隔符
if(this.buffer[this.bufferPosn + i] != separator[sepPosn]){
sepPosn = 0;
break;
}
}

//的確遇到了行分隔符
if(sepPosn == sepLength){
bufferPosn += i;
newline = true;
sepPosn = 0;
break;
}
}
}


int readLength = this.bufferPosn - startPosn;

bytesConsumed += readLength;
//行分隔符不放入塊中
//int appendLength = readLength - newlineLength;
if (readLength > maxLineLength - txtLength) {
readLength = maxLineLength - txtLength;
}
if (readLength > 0) {
record.append(this.buffer, startPosn, readLength);
txtLength += readLength;

//去掉記錄的分隔符
if(newline){
str.set(record.getBytes(), 0, record.getLength() - sepLength);
}
}

} while (!newline && (bytesConsumed < maxBytesToConsume));

if (bytesConsumed > (long)Integer.MAX_VALUE) {
throw new IOException("Too many bytes before newline: " + bytesConsumed);
}

return (int) bytesConsumed;
}

//以下是需要改寫的部分_end

//以下是hadoop-core中LineReader的源碼_start

public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException{
str.clear();
int txtLength = 0;
int newlineLength = 0;
boolean prevCharCR = false;
long bytesConsumed = 0L;
do {
int startPosn = this.bufferPosn;
if (this.bufferPosn >= this.bufferLength) {
startPosn = this.bufferPosn = 0;
if (prevCharCR) bytesConsumed ++;
this.bufferLength = this.in.read(this.buffer);
if (this.bufferLength <= 0) break;
}
for (; this.bufferPosn < this.bufferLength; this.bufferPosn ++) {
if (this.buffer[this.bufferPosn] == LF) {
newlineLength = (prevCharCR) ? 2 : 1;
this.bufferPosn ++;
break;
}
if (prevCharCR) {
newlineLength = 1;
break;
}
prevCharCR = this.buffer[this.bufferPosn] == CR;
}
int readLength = this.bufferPosn - startPosn;
if ((prevCharCR) && (newlineLength == 0))
--readLength;
bytesConsumed += readLength;
int appendLength = readLength - newlineLength;
if (appendLength > maxLineLength - txtLength) {
appendLength = maxLineLength - txtLength;
}
if (appendLength > 0) {
str.append(this.buffer, startPosn, appendLength);
txtLength += appendLength; }
}
while ((newlineLength == 0) && (bytesConsumed < maxBytesToConsume));

if (bytesConsumed > (long)Integer.MAX_VALUE) throw new IOException("Too many bytes before newline: " + bytesConsumed);
return (int)bytesConsumed;
}

//以下是hadoop-core中LineReader的源碼_end

}

2、已按主鍵 key 排好序的情況,並保證相同主鍵一定相鄰。假設每條記錄的第一個字段為主鍵,若沿用上面的 LineReader,需要在核心方法 readLine 中對前後兩條記錄的 id 做 equals 判斷:不同才 split,相同則繼續往下一條。程式碼不再贅貼,但要注意的地方依舊是前後兩個 buffer 交接時,很可能一條記錄被切成兩半,一半在前一個 buffer、一半在後一個 buffer。

這種方式的好處是省去了 reduce 操作,效率會大幅提升——mapper 的過程通常很快,真正費時的是 reduce。

更多Hadoop相關信息見Hadoop 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=13

Copyright © Linux教程網 All Rights Reserved