資料如下:
需要把相同訂單id的記錄放在一個檔案中,并以訂單id命名。
(2)實作思路
這個需求可以直接使用MultipleOutputs這個類來實作。
預設情況下,每個reducer寫入一個檔案,檔案名由分區号命名,例如’part-r-00000’,而 MultipleOutputs可以用key作為檔案名,例如‘Order_0000001-r-00000’。
是以,思路就是map中處理每條記錄,以‘訂單id’為key,reduce中使用MultipleOutputs進行輸出,會自動以key為檔案名,檔案内容就是相同key的所有記錄。
例如‘Order_0000001-r-00000’的内容就是:
Order_0000001,Pdt_05,25.8
Order_0000001,Pdt_01,222.8
Pom.xml如下:
主類:MultipleOutputTest
package duowenjianshuchu;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
public class MultipleOutputTest {
static class MyMapper extends Mapper<LongWritable,Text,Text,Text>{
@Override
protected void map(LongWritable key, Text value,Context context)throws IOException, InterruptedException {
String[] fields = value.toString().split(" ",2);
context.write(new Text(fields[0]), value);
}
}
static class MyReducer extends Reducer<Text,Text,NullWritable,Text>{
private MultipleOutputs<NullWritable, Text> multipleOutputs;
protected void setup(Context context){
multipleOutputs = new MultipleOutputs<NullWritable, Text>(context);
}
@Override
protected void reduce(Text key, Iterable<Text> values,Context context)throws IOException, InterruptedException {
for (Text value : values) {
multipleOutputs.write(NullWritable.get(), value, key.toString());
}
}
protected void cleanup(Context context) throws IOException, InterruptedException{
multipleOutputs.close();
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJarByClass(MultipleOutputTest.class);
job.setJobName("MultipleOutputTest");
job.setMapperClass(MyMapper.class);
job.setReducerClass(MyReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
}
}
結果展示如下: