编写简单的Hadoop程序(自连接)

本文介绍如何使用Mapper和Reduce程序实现数据关系映射和处理,包括数据准备、程序编写以及关键步骤的实现。通过两次处理输入数据,创建类似于SQL中两个表的关联,最终实现GrandParent和GrandChild的查找。

准备工作:

如一个列为child,一个列为parent,需要找出grandchile, grandParent

如数据

Lucy Tom
Lucy Jone
Tom Heimi
Tom QiQi
Jone Candy
Jone God

Lucy有四个grandParent:Heimi, QiQi,Candy, God


编写程序Mapper程序,Mapper中两次处理输入数据,类似于SQL中的两个表,两个表的关联列变为key,左表用value值加一个前缀1,右表的值加另一个前缀2。

public class SelfMapper extends Mapper<LongWritable, Text, Text, Text>{
	
	enum Counter{
		LINESKIP
	}
	
	@Override
	public void map(LongWritable key, Text value, Context context)
		      throws IOException, InterruptedException{
		
		String line = value.toString();
		
		try {
			String []arr = line.split(" ");
			context.write(new Text(arr[1]), new Text("1"+arr[0]));
			context.write(new Text(arr[0]), new Text("2"+arr[1]));
		} catch (Exception e) {
			context.getCounter(Counter.LINESKIP).increment(1);
		}
	}
}


编写Reduce程序,Reduce中对value值做处理,坐标的value和右表的value做组合即可。

public class SelfReducer extends Reducer<Text,Text,Text,Text>{
	
	@Override
	public void reduce(Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException{
		List<String> childLst = new ArrayList<String>();
		List<String> parentLst = new ArrayList<String>();
		for(Text t:values){
			if(t.toString().substring(0, 1).equals("1")){
				childLst.add(t.toString().substring(1, t.toString().length()));
			}else if(t.toString().substring(0, 1).equals("2")){
				parentLst.add(t.toString().substring(1, t.toString().length()));
			}
		}
		
		for(String child:childLst){
			for(String parent:parentLst){
				context.write(new Text(child),new Text(parent));
			}
		}
	}

Map

Main程序参考其他的博文。








评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值