2

我正在维护一个简单的 hadoop 作业,它生成 CSV 文件作为 HDFS 中的输出。该作业使用 TextOutputFormat。我想将前导标题行添加到 csv 文件(我知道部分文件是由不同的工作人员创建的,如果他们每个人都有标题,那不是问题)。如何做到这一点?

编辑:级联可以提供帮助,但乍一看我不想开始使用新框架

编辑:

所以我想为输出的 CSV 文件添加标题。列数是确定的。这是我的减速器类的骨架:

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();
    }
}
4

1 回答 1

0

您可以覆盖 mapper/reducer 类中的 run() 以根据您的要求添加标头。例如。如果您想在您的最终 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);
        }
  }
于 2016-11-13T04:20:46.717 回答