我正在维护一个简单的 hadoop 作业,该作业生成 CSV 文件作为 HDFS 中的输出。该作业使用 TextOutputFormat。 我想将前导标题行添加到 csv 文件(我知道零件文件是由不同的 worker 创建的,如果他们每个人都获得标题,那不是问题)。 如何实现?
编辑:级联可以 help但乍一看我不想开始使用新框架
编辑:
所以我想为输出的 CSV 文件添加标题。列数 是确定性的。 这是我的 Reducer 类的骨架:
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
public final class Reducer extends Reducer<Text, IntWritable, Text, IntWritable>
{
private MultipleOutputs<Text, IntWritable> mos;
private static final Text KEY_HOLDER = new Text();
private static final IntWritable VALUE_HOLDER = new IntWritable(1);
@Override
public void setup(final Context context)
{
mos = new MultipleOutputs<Text, IntWritable>(context);
}
@Override
public void cleanup(final Context context) throws IOException, InterruptedException
{
mos.close();
}
@Override
public void reduce(final Text key, final Iterable<IntWritable> values, final Context context)
throws IOException, InterruptedException
{
// [... some business logic ...]
mos.write(KEY_HOLDER, VALUE_HOLDER, "myFileName");
context.progress();
}
}
最佳答案
您可以覆盖映射器/缩减器类中的 run() 以根据您的要求添加 header 。例如。如果您想在您的最终 o/p 中添加 FisrtName 和 LastName。您可以使用以下代码作为引用。
public void run(Context context) throws IOException, InterruptedException
{
setup(context);
column = new Text("ColumnName") ;
values = new Text("FirstName" + "\t" + "LastName") ;
context.write(column, values);
try
{
while (context.nextKey())
{
reduce(context.getCurrentKey(), context.getValues(), context);
Iterator<IntWritable> iter = context.getValues().iterator();
if(iter instanceof ReduceContext.ValueIterator)
{ ((ReduceContext.ValueIterator<IntWritable>)iter).resetBackupStore();
}
}
}
finally
{
cleanup(context);
}
}
关于java - Hadoop 文本输出格式 : add headers to CSV output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18416461/