Hadoop多路径输出(MultipleOutputs)

使用Hadoop进行数据处理时,有时候需要将计算结果根据不同的条件存入不同的分区。

比如:计算顾客是否回头购买的时候,会将回头了的顾客数据和未回头的顾客数据分别存入不同的表。

可以使用MultipleOutputs实现。

需要在reduce类中定义MultipleOutputs,并且重写Reducer的setup()方法和cleanup()方法。具体实例如下

public static class PeriodReduce extends Reducer<TextPair,Text,NullWritable,Text>{
		private MultipleOutputs<NullWritable, Text> mos;
		
		protected void setup(Context context)throws IOException,InterruptedException{
			mos = new MultipleOutputs<NullWritable, Text>(context);
		}
		
		protected void cleanup(Context context)throws IOException,InterruptedException{
			mos.close();
		}
		
		public void reduce(TextPair key,Iterable<Text> values,Context context)throws IOException,InterruptedException{
			
			Iterator<Text> it = values.iterator();
			ArrayList<String> custInfo = null;
			String last ="notexist";
			String ret = "notexist";
			while (it.hasNext()){
				String line = it.next().toString();
				//排序后,先到达reduce的数据是上个周期的
				if(key.getId()==0){
					custInfo = new ArrayList<String>();
					//将上个周期的购买情况存放
					custInfo.add(line);
					last = "exist";
				}else if(key.getId()==1){
					ret = "exist";
					//如果回头,则加上上个周期信息放入return目录下
					if("exist".equals(last)&&custInfo.size()>0){
						for(String str:custInfo){
							mos.write(NullWritable.get(), new Text(line+"\001"+str),"return/r");
						}
					}
				}
				
				//如果没有回头,直接输出上期
				if("exist".equals(last)&&"notexist".equals(ret)){
					for(String str:custInfo){
						mos.write(NullWritable.get(), new Text(key.getText()+"\001"+str),"loss/l");
					}
					
				}
			}
		}

	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值