ReduceJoin的体现是在Reduce阶段中就体现了,因为他是将不同数据块输出的相同的key2给聚合起来,所以只要Map阶段把不同的表或文件读取进来并做好区分就可以在reducer阶段进行ReduceJoin
Mapjoin不适合做大表Join,只适合用做小表,可以把小表提前放入缓冲中,在Map阶段进行join
示例代码:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class MapJoinMapper extends Mapper<LongWritable, Text, Text, Text>
{
//把缓冲到表中部门放入到hashMap中
private Map<String, String> dept=new HashMap<>();
//输出的是部门名称和员工姓名
@Override
protected void map(LongWritable key, Text value,Context context)
throws IOException, InterruptedException {
String[] split = value.toString().split(",");
context.write(new Text(dept.get(split[7])), new Text(split[1]));
}
//读入缓冲的文件
@SuppressWarnings("resource")
@Override
protected void setup(Context context)
throws IOException, InterruptedException {
//获取缓存的文件,因为我们只缓存了一个文件,所以只获取第一个就可以
String path = context.getCacheFiles()[0].getPath();
//然后从path中读入数据
//获取读入缓冲的表明
int indexOf = path.lastIndexOf("/");
String deptName = path.substring(indexOf+1);
//先创建一个文件输入流
InputStream inputStream = new FileInputStream(deptName);
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(reader);
String line=null;
while ((line=br.readLine())!=null)
{
String[] split = line.split(",");
dept.put(split[0], split[1]);
}
}
}
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class MapjoinMain
{
public static void main(String[] args) throws Exception {
//创建任务
Job job = Job.getInstance(new Configuration());
job.setJarByClass(MapjoinMain.class);
//指定Map和map的输出类型
job.setMapperClass(MapJoinMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
//将小表输入到内存中
job.addCacheFile(new URI(args[0]));
//指定输入输出类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
//指定文件输入路径和输出路径
FileInputFormat.setInputPaths(job, new Path(args[1]));
FileOutputFormat.setOutputPath(job, new Path(args[2]));
//执行任务
job.waitForCompletion(true);
}
}
然后我们再介绍ReduceJoin的等值连接和自连接
它的原理是通过相同的键在Reduce阶段进行聚合,前提是需要做标记
我们先看一下等值连接,