完全なファイル データを値とキーのファイル名として持つという特別な要件があるため、Hadoop でテキスト ファイルと gzip ファイルの両方を読み取るカスタム レコード リーダーを作成しました。ソースは次のとおりです。
public class WholeFileRecordReader extends RecordReader<Text, BytesWritable> {
private CompressionCodecFactory compressionCodecs = null;
private FileSplit fileSplit;
private Configuration conf;
private InputStream in;
private Text key = new Text("");
private BytesWritable value = new BytesWritable();
private boolean processed = false;
@Override
public void initialize(InputSplit split, TaskAttemptContext context)
throws IOException, InterruptedException {
this.fileSplit = (FileSplit) split;
this.conf = context.getConfiguration();
final Path file = fileSplit.getPath();
compressionCodecs = new CompressionCodecFactory(conf);
final CompressionCodec codec = compressionCodecs.getCodec(file);
System.out.println(codec);
FileSystem fs = file.getFileSystem(conf);
in = fs.open(file);
if (codec != null) {
in = codec.createInputStream(in);
}
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (!processed) {
byte[] contents = new byte[(int) fileSplit.getLength()];
Path file = fileSplit.getPath();
key.set(file.getName());
try {
IOUtils.readFully(in, contents, 0, contents.length);
value.set(contents, 0, contents.length);
} finally {
IOUtils.closeStream(in);
}
processed = true;
return true;
}
return false;
}
@Override
public Text getCurrentKey() throws IOException, InterruptedException {
return key;
}
@Override
public BytesWritable getCurrentValue() throws IOException, InterruptedException {
return value;
}
@Override
public float getProgress() throws IOException {
return processed ? 1.0f : 0.0f;
}
@Override
public void close() throws IOException {
// Do nothing
}
}
問題は、コードが不完全なファイル データを読み取っていることです。これはおそらく、fileSplit (圧縮ファイルを指す) を使用してコンテンツの長さを決定しているため、値が小さくなっていることが原因です。したがって、これにより不完全なデータが Mapper に渡されます。
gzip ファイル データの実際の長さを取得する方法や、完全なデータを読み取るように RecordReader を変更する方法を教えてください。