Reduce Join
Map端的主要工作:为来自不同表(文件)的key/value 打标记以区别不同来源的记录,比如:tag=0表示来自文件File1,tag=2表示来自文件File2。然后用连接字段作为 key,其余部分和新加的标记作为 value,然后进行输出。
Reduce端的主要工作:在 Reduce端,以连接字段作为key 的分组已经完成,我们只需要在每一个分组当中将那些来源于不同文件的记录(在 map 阶段已经打标记)分开,最后进行合并。
但是,此方法有缺点:1、Map阶段没有对数据瘦身,shuffle的网络传输和排序性能很低;2、Reduce端对2个集合做乘积计算,很耗内存,容易导致OOM
Map Join
两份数据中,如果有一份数据比较小,小数据全部加载到内存,按关键字建立索引。大数据文件作为map的输入文件,对map()方法的每一对输入,都能够方便地和已加载到内存的小数据进行连接。把连接结果按key输出,经过shuffle阶段,reduce端得到的就是已经按key分组的,并且连接好了的数据。
为了支持文件的复制,Hadoop提供了一个类DistributedCache,使用该类的方法如下:
- 用户使用静态方法
DistributedCache.addCacheFile()
指定要复制的文件,它的参数是文件的URI,将一个文件分布式的缓存到每一台机器本地 - 使用
DistributedCache.getLocalCacheFiles()
方法获取文件,然后获取到每一行数据,将每一行数据使用局部变量HashMap存储 - 在Mapper方法里面获取到HDFS上的一个文件,读取内容,join的on条件即为HashMap的key以及读取文件的某个字段,然后做逻辑判断,最后context.write将数据写出,如果输出多个字段,使用javabean封装即可,但是javabean需要实现WritableCompare进行序列化输入输出
SemiJoin
SemiJoin,也叫半连接,是从分布式数据库中借鉴过来的方法。它的产生动机是:对于reduce side join,跨机器的数据传输量非常大,这成了join操作的一个瓶颈,如果能够在map端过滤掉不会参加join操作的数据,则可以大大节省网络IO。
实现方法很简单:选取一个小表,假设是File1,将其参与join的key抽取出来,保存到文件File3中,File3文件一般很小,可以放到内存中。在map阶段,使用DistributedCache将File3复制到各个TaskTracker上,然后将File2中不在File3中的key对应的记录过滤掉,剩下的reduce阶段的工作与reduce side join相同。
reduce side join + BloomFilter
在某些情况下,SemiJoin抽取出来的小表的key集合在内存中仍然存放不下,这时候可以使用BloomFiler以节省空间。
BloomFilter最常见的作用是:判断某个元素是否在一个集合里面。它最重要的两个方法是:add() 和contains()。最大的特点是不会存在false negative,即:如果contains()返回false,则该元素一定不在集合中,但会存在一定的true negative,即:如果contains()返回true,则该元素可能在集合中。
因而可将小表中的key保存到BloomFilter中,在map阶段过滤大表,可能有一些不在小表中的记录没有过滤掉(但是在小表中的记录一定不会过滤掉),这没关系,只不过增加了少量的网络IO而已。
代码实现
订单数据表 order.txt
id | date | pid | amount |
---|---|---|---|
1001 | 20200930 | P0001 | 2 |
1002 | 20200930 | P0001 | 3 |
1003 | 20200930 | P0001 | 3 |
商品信息表 product.txt
id | pname | category_id | price |
---|---|---|---|
P0001 | XiaoMi | 1001 | 2 |
P0001 | SUMSUNG | 1000 | 3 |
P0001 | HUAWEI | 1002 | 3 |
public class InfoBean implements Writable {
private String order_id;
private String date;
private String pid;
private int amount;
private String pname;
private String category_id;
private float price;
// flag=0表示这个对象是封装订单表记录
// flag=1表示这个对象是封装产品信息记录
private String flag;
public void set(String order_id, String date, String pid, int amount, String pname,
String category_id, float price, String flag) {
this.order_id = order_id;
this.date = date;
this.pid = pid;
this.amount = amount;
this.pname = pname;
this.category_id = category_id;
this.price = price;
this.flag = flag;
}
public String getOrder_id() {
return order_id;
}
public void setOrder_id(String order_id) {
this.order_id = order_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
@Override
public void readFields(DataInput in) throws IOException {
this.order_id = in.readUTF();
this.date = in.readUTF();
this.pid = in.readUTF();
this.amount = in.readInt();
this.pname = in.readUTF();
this.category_id = in.readUTF();
this.price = in.readFloat();
this.flag = in.readUTF();
}
@Override
public void write(DataOutput out) throws IOException {
out.writeUTF(order_id);
out.writeUTF(date);
out.writeUTF(pid);
out.writeInt(amount);
out.writeUTF(pname);
out.writeUTF(category_id);
out.writeFloat(price);
out.writeUTF(flag);
}
@Override
public String toString() {
return "order_id=" + order_id + ", date=" + date + ", pid=" + pid + ", amount=" + amount + ", pname="
+ pname + ", category_id=" + category_id + ", price=" + price;
}
}
Reduce端join
public class RJoin {
static class RJoinMapper extends Mapper<LongWritable, Text, Text, InfoBean> {
InfoBean bean = new InfoBean();
Text k = new Text();
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] fields = line.split("\t");
String pid = "";
// 通过文件名判断是哪种数据
FileSplit inputSplit = (FileSplit) context.getInputSplit();
String name = inputSplit.getPath().getName();
if (name.startsWith("order")) {
pid = fields[2];
bean.set(fields[0], fields[1], pid, Integer.parseInt(fields[3]), "", "", -1, "0");
} else {
pid = fields[0];
bean.set("", "", pid, -1, fields[1], fields[2], Float.parseFloat(fields[3]), "1");
}
k.set(pid);
context.write(k, bean);
}
}
static class RJoinReducer extends Reducer<Text, InfoBean, InfoBean, NullWritable> {
@Override
protected void reduce(Text pid, Iterable<InfoBean> values, Context context) throws IOException, InterruptedException {
InfoBean pdBean = new InfoBean();
List<InfoBean> orderBeans = new ArrayList<InfoBean>();
for (InfoBean bean : values) {
if ("1".equals(bean.getFlag())) { //产品
try {
BeanUtils.copyProperties(pdBean, bean);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
} else {
InfoBean orderBean = new InfoBean();
try {
BeanUtils.copyProperties(orderBean, bean);
orderBeans.add(orderBean);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
// 拼接两类数据形成最终结果
for (InfoBean bean : orderBeans) {
bean.setPname(pdBean.getPname());
bean.setCategory_id(pdBean.getCategory_id());
bean.setPrice(pdBean.getPrice());
context.write(bean, NullWritable.get());
}
}
}
public static void main(String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
// 指定本程序的jar包所在的本地路径
job.setJarByClass(RJoin.class);
//System.setProperty("hadoop.home.dir", "D:\\hadoop-2.6.5");
// 指定本业务job要使用的mapper/Reducer业务类
job.setMapperClass(RJoinMapper.class);
job.setReducerClass(RJoinReducer.class);
// 指定mapper输出数据的kv类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(InfoBean.class);
job.setOutputKeyClass(InfoBean.class);
job.setOutputValueClass(NullWritable.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
boolean res = job.waitForCompletion(true);
System.exit(res ? 0 : 1);
}
}
Map端join
public class MapSideJoin {
static class MapSideJoinMapper extends Mapper<LongWritable, Text, InfoBean, NullWritable> {
Map<String, InfoBean> pdInfoMap = new HashMap<String, InfoBean>();
InfoBean bean = new InfoBean();
/**
* 通过阅读父类Mapper的源码,发现 setup方法是在maptask处理数据之前调用一次 可以用来做一些初始化工作
*/
@Override
protected void setup(Context context) throws IOException, InterruptedException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("product.txt")));
String line;
while (StringUtils.isNotEmpty(line = br.readLine())) {
InfoBean pdBean = new InfoBean();
String[] fields = line.split("\t");
pdBean.set("", "", fields[0], -1, fields[1], fields[2], Float.parseFloat(fields[3]), "1");
pdInfoMap.put(fields[0], pdBean);
}
br.close();
}
// 由于已经持有完整的产品信息表,所以在map方法中就能实现join逻辑了
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] fields = line.split("\t");
String pid = fields[2];
//InfoBean productBean = pdInfoMap.get(pid);
bean.setOrder_id(fields[0]);
bean.setDate(fields[1]);
bean.setPid(pid);
bean.setAmount(Integer.parseInt(fields[3]));
bean.setPname(pdInfoMap.get(pid).getPname());
bean.setCategory_id(pdInfoMap.get(pid).getCategory_id());
bean.setPrice(pdInfoMap.get(pid).getPrice());
context.write(bean, NullWritable.get());
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, URISyntaxException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
// 指定本程序的jar包所在的本地路径
job.setJarByClass(RJoin.class);
//System.setProperty("hadoop.home.dir", "D:\\hadoop-2.6.5");
// 指定本业务job要使用的mapper/Reducer业务类
job.setMapperClass(MapSideJoinMapper.class);
// 指定mapper输出数据的kv类型
job.setMapOutputKeyClass(InfoBean.class);
job.setMapOutputValueClass(NullWritable.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
//FileInputFormat.setInputPaths(job, new Path("hdfs://mini1/mapsidejoin/input"));
//FileOutputFormat.setOutputPath(job, new Path("hdfs://mini1/mapsidejoin/output"));
// 指定需要缓存一个文件到所有的maptask运行节点工作目录
/* job.addArchiveToClassPath(archive); */// 缓存jar包到task运行节点的classpath中
/* job.addFileToClassPath(file); */// 缓存普通文件到task运行节点的classpath中
/* job.addCacheArchive(uri); */// 缓存压缩包文件到task运行节点的工作目录
/* job.addCacheFile(uri) */// 缓存普通文件到task运行节点的工作目录
// 将产品表文件缓存到task工作节点的工作目录中去
job.addCacheFile(new URI("hdfs://mini1/mapsidejoin/cache/product.txt"));
// map端join的逻辑不需要reduce阶段,设置reducetask数量为0
job.setNumReduceTasks(0);
boolean res = job.waitForCompletion(true);
System.exit(res ? 0 : 1);
}
}