相关链接:
MapReduce练习一(计数,去重,排序,平均成绩)
MapReduce练习二(单表关联,多表关联,倒排索引)
一些省略的代码可以在练习一中找到。
一,单表关联
要求:给出child-parent(孩子—父母)表,要求输出grandchild-grandparent(孙子—爷奶)表。
Map输出2个表,第一个表key为父母,设一个标识位tag=L,value为tag+孩子+父母,称为左表;第二个表key为孩子,tag=R,value为tag+孩子+父母,称为右表。其实就是左一个child-parent表,右边根据parent连接出一个child-parent表,只不过左表里的parent在右表中是child。
在shuffle时,key相同的会合并形成value-list,所以在reduce时,我们要的祖孙表是满足value-list中同时有L标识和R标识的,也就是根据parent连接成功的。
此时L表中的child放入grandchild数组,R表的parent放入grandparent数组,然后一内一外两个循环遍历这俩数组打印输出(这叫笛卡尔积?)。
给出map和reduce的代码:
public class STjoin extends Configured implements Tool{
static int row = 0; // 标记表头行
public static class Map extends Mapper<LongWritable, Text, Text, Text>{
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{
String line = value.toString();
String[] words = line.split(" +");
String childName = words[0];
String parentName = words[1];
String tag = new String(); // 左右表的标识
// 略去表头那一行
if(!childName.equals("child")){
// 输出左表,以父母为key,想想为啥以父母为key作为左表,其实就是用父母连接两个表
tag = "L";
context.write(new Text(parentName), new Text(tag + "+" + childName + "+" + parentName));
// 输出右表,以孩子为key
tag = "R";
context.write(new Text(childName), new Text(tag + "+" + childName + "+" + parentName));
}
}
}
public static class Reduce extends Reducer<Text,