reduce/map/semi join

轉自:http://database.51cto.com/art/201410/454277.htm

一、概述

對於RDBMS中的join操作大夥一定非常熟悉,寫sql的時候要十分注意細節,稍有差池就會耗時巨久造成很大的性能瓶頸,而在Hadoop中使用MapReduce框架進行join的操作時同樣耗時,但是由於hadoop的分佈式設計理念的特殊性,因此對於這種join操作同樣也具備了一定的特殊性。本文主要對MapReduce框架對錶之間的join操作的幾種實現方式進行詳細分析,並且根據我在實際開發過程中遇到的實際例子來進行進一步的說明。

二、實現原理

1、在Reudce端進行連接。

在Reudce端進行連接是MapReduce框架進行表之間join操作最爲常見的模式,其具體的實現原理如下:

Map端的主要工作:爲來自不同表(文件)的key/value對打標籤以區別不同來源的記錄。然後用連接字段作爲key,其餘部分和新加的標誌作爲value,最後進行輸出。

reduce端的主要工作:在reduce端以連接字段作爲key的分組已經完成,我們只需要在每一個分組當中將那些來源於不同文件的記錄(在map階段已經打標誌)分開,最後進行笛卡爾只就ok了。原理非常簡單,下面來看一個實例:

(1)自定義一個value返回類型:

  1. package com.mr.reduceSizeJoin;   
  2. import java.io.DataInput;   
  3. import java.io.DataOutput;   
  4. import java.io.IOException;   
  5. import org.apache.hadoop.io.Text;   
  6. import org.apache.hadoop.io.WritableComparable;   
  7. public class CombineValues implements WritableComparable<CombineValues>{   
  8.     //private static final Logger logger = LoggerFactory.getLogger(CombineValues.class);   
  9.     private Text joinKey;//鏈接關鍵字   
  10.     private Text flag;//文件來源標誌   
  11.     private Text secondPart;//除了鏈接鍵外的其他部分   
  12.     public void setJoinKey(Text joinKey) {   
  13.         this.joinKey = joinKey;   
  14.     }   
  15.     public void setFlag(Text flag) {   
  16.         this.flag = flag;   
  17.     }   
  18.     public void setSecondPart(Text secondPart) {   
  19.         this.secondPart = secondPart;   
  20.     }   
  21.     public Text getFlag() {   
  22.         return flag;   
  23.     }   
  24.     public Text getSecondPart() {   
  25.         return secondPart;   
  26.     }   
  27.     public Text getJoinKey() {   
  28.         return joinKey;   
  29.     }   
  30.     public CombineValues() {   
  31.         this.joinKey =  new Text();   
  32.         this.flag = new Text();   
  33.         this.secondPart = new Text();   
  34.     }
  35.  
  36.     @Override 
  37.     public void write(DataOutput out) throws IOException {   
  38.         this.joinKey.write(out);   
  39.         this.flag.write(out);   
  40.         this.secondPart.write(out);   
  41.     }   
  42.     @Override 
  43.     public void readFields(DataInput in) throws IOException {   
  44.         this.joinKey.readFields(in);   
  45.         this.flag.readFields(in);   
  46.         this.secondPart.readFields(in);   
  47.     }   
  48.     @Override 
  49.     public int compareTo(CombineValues o) {   
  50.         return this.joinKey.compareTo(o.getJoinKey());   
  51.     }   
  52.     @Override 
  53.     public String toString() {   
  54.         // TODO Auto-generated method stub   
  55.         return "[flag="+this.flag.toString()+",joinKey="+this.joinKey.toString()+",secondPart="+this.secondPart.toString()+"]";   
  56.     }   

(2)map、reduce主體代碼

  1. package com.mr.reduceSizeJoin;   
  2. import java.io.IOException;   
  3. import java.util.ArrayList;   
  4. import org.apache.hadoop.conf.Configuration;   
  5. import org.apache.hadoop.conf.Configured;   
  6. import org.apache.hadoop.fs.Path;   
  7. import org.apache.hadoop.io.Text;   
  8. import org.apache.hadoop.mapreduce.Job;   
  9. import org.apache.hadoop.mapreduce.Mapper;   
  10. import org.apache.hadoop.mapreduce.Reducer;   
  11. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;   
  12. import org.apache.hadoop.mapreduce.lib.input.FileSplit;   
  13. import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;   
  14. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;   
  15. import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;   
  16. import org.apache.hadoop.util.Tool;   
  17. import org.apache.hadoop.util.ToolRunner;   
  18. import org.slf4j.Logger;   
  19. import org.slf4j.LoggerFactory;   
  20. /**   
  21.  * @author zengzhaozheng   
  22.  * 用途說明:   
  23.  * reudce side join中的left outer join   
  24.  * 左連接,兩個文件分別代表2個表,連接字段table1的id字段和table2的cityID字段   
  25.  * table1(左表):tb_dim_city(id int,name string,orderid int,city_code,is_show)   
  26.  * tb_dim_city.dat文件內容,分隔符爲"|":   
  27.  * id     name  orderid  city_code  is_show   
  28.  * 0       其他        9999     9999         0   
  29.  * 1       長春        1        901          1   
  30.  * 2       吉林        2        902          1   
  31.  * 3       四平        3        903          1   
  32.  * 4       松原        4        904          1   
  33.  * 5       通化        5        905          1   
  34.  * 6       遼源        6        906          1   
  35.  * 7       白城        7        907          1   
  36.  * 8       白山        8        908          1   
  37.  * 9       延吉        9        909          1   
  38.  * -------------------------風騷的分割線-------------------------------   
  39.  * table2(右表):tb_user_profiles(userID int,userName string,network string,double flow,cityID int)   
  40.  * tb_user_profiles.dat文件內容,分隔符爲"|":   
  41.  * userID   network     flow    cityID   
  42.  * 1           2G       123      1   
  43.  * 2           3G       333      2   
  44.  * 3           3G       555      1   
  45.  * 4           2G       777      3   
  46.  * 5           3G       666      4   
  47.  *   
  48.  * -------------------------風騷的分割線-------------------------------   
  49.  *  結果:   
  50.  *  1   長春  1   901 1   1   2G  123   
  51.  *  1   長春  1   901 1   3   3G  555   
  52.  *  2   吉林  2   902 1   2   3G  333   
  53.  *  3   四平  3   903 1   4   2G  777   
  54.  *  4   松原  4   904 1   5   3G  666   
  55.  */ 
  56. public class ReduceSideJoin_LeftOuterJoin extends Configured implements Tool{   
  57.     private static final Logger logger = LoggerFactory.getLogger(ReduceSideJoin_LeftOuterJoin.class);   
  58.     public static class LeftOutJoinMapper extends Mapper<Object, Text, Text, CombineValues> {   
  59.         private CombineValues combineValues = new CombineValues();   
  60.         private Text flag = new Text();   
  61.         private Text joinKey = new Text();   
  62.         private Text secondPart = new Text();   
  63.         @Override 
  64.         protected void map(Object key, Text value, Context context)   
  65.                 throws IOException, InterruptedException {   
  66.             //獲得文件輸入路徑   
  67.             String pathName = ((FileSplit) context.getInputSplit()).getPath().toString();   
  68.             //數據來自tb_dim_city.dat文件,標誌即爲"0"   
  69.             if(pathName.endsWith("tb_dim_city.dat")){   
  70.                 String[] valueItems = value.toString().split("\\|");   
  71.                 //過濾格式錯誤的記錄   
  72.                 if(valueItems.length != 5){   
  73.                     return;   
  74.                 }   
  75.                 flag.set("0");   
  76.                 joinKey.set(valueItems[0]);   
  77.                 secondPart.set(valueItems[1]+"\t"+valueItems[2]+"\t"+valueItems[3]+"\t"+valueItems[4]);   
  78.                 combineValues.setFlag(flag);   
  79.                 combineValues.setJoinKey(joinKey);   
  80.                 combineValues.setSecondPart(secondPart);   
  81.                 context.write(combineValues.getJoinKey(), combineValues);
  82.  
  83.                 }//數據來自於tb_user_profiles.dat,標誌即爲"1"   
  84.             else if(pathName.endsWith("tb_user_profiles.dat")){   
  85.                 String[] valueItems = value.toString().split("\\|");   
  86.                 //過濾格式錯誤的記錄   
  87.                 if(valueItems.length != 4){   
  88.                     return;   
  89.                 }   
  90.                 flag.set("1");   
  91.                 joinKey.set(valueItems[3]);   
  92.                 secondPart.set(valueItems[0]+"\t"+valueItems[1]+"\t"+valueItems[2]);   
  93.                 combineValues.setFlag(flag);   
  94.                 combineValues.setJoinKey(joinKey);   
  95.                 combineValues.setSecondPart(secondPart);   
  96.                 context.write(combineValues.getJoinKey(), combineValues);   
  97.             }   
  98.         }   
  99.     }   
  100.     public static class LeftOutJoinReducer extends Reducer<Text, CombineValues, Text, Text> {   
  101.         //存儲一個分組中的左表信息   
  102.         private ArrayList<Text> leftTable = new ArrayList<Text>();   
  103.         //存儲一個分組中的右表信息   
  104.         private ArrayList<Text> rightTable = new ArrayList<Text>();   
  105.         private Text secondPar = null;   
  106.         private Text output = new Text();   
  107.         /**   
  108.          * 一個分組調用一次reduce函數   
  109.          */ 
  110.         @Override 
  111.         protected void reduce(Text key, Iterable<CombineValues> value, Context context)   
  112.                 throws IOException, InterruptedException {   
  113.             leftTable.clear();   
  114.             rightTable.clear();   
  115.             /**   
  116.              * 將分組中的元素按照文件分別進行存放   
  117.              * 這種方法要注意的問題:   
  118.              * 如果一個分組內的元素太多的話,可能會導致在reduce階段出現OOM,   
  119.              * 在處理分佈式問題之前最好先了解數據的分佈情況,根據不同的分佈採取最   
  120.              * 適當的處理方法,這樣可以有效的防止導致OOM和數據過度傾斜問題。   
  121.              */ 
  122.             for(CombineValues cv : value){   
  123.                 secondPar = new Text(cv.getSecondPart().toString());   
  124.                 //左表tb_dim_city   
  125.                 if("0".equals(cv.getFlag().toString().trim())){   
  126.                     leftTable.add(secondPar);   
  127.                 }   
  128.                 //右表tb_user_profiles   
  129.                 else if("1".equals(cv.getFlag().toString().trim())){   
  130.                     rightTable.add(secondPar);   
  131.                 }   
  132.             }   
  133.             logger.info("tb_dim_city:"+leftTable.toString());   
  134.             logger.info("tb_user_profiles:"+rightTable.toString());   
  135.             for(Text leftPart : leftTable){   
  136.                 for(Text rightPart : rightTable){   
  137.                     output.set(leftPart+ "\t" + rightPart);   
  138.                     context.write(key, output);   
  139.                 }   
  140.             }   
  141.         }   
  142.     }   
  143.     @Override 
  144.     public int run(String[] args) throws Exception {   
  145.           Configuration conf=getConf(); //獲得配置文件對象   
  146.             Job job=new Job(conf,"LeftOutJoinMR");   
  147.             job.setJarByClass(ReduceSideJoin_LeftOuterJoin.class);
  148.             FileInputFormat.addInputPath(job, new Path(args[0])); //設置map輸入文件路徑   
  149.             FileOutputFormat.setOutputPath(job, new Path(args[1])); //設置reduce輸出文件路徑
  150.             job.setMapperClass(LeftOutJoinMapper.class);   
  151.             job.setReducerClass(LeftOutJoinReducer.class);
  152.             job.setInputFormatClass(TextInputFormat.class); //設置文件輸入格式   
  153.             job.setOutputFormatClass(TextOutputFormat.class);//使用默認的output格格式
  154.  
  155.             //設置map的輸出key和value類型   
  156.             job.setMapOutputKeyClass(Text.class);   
  157.             job.setMapOutputValueClass(CombineValues.class);
  158.  
  159.             //設置reduce的輸出key和value類型   
  160.             job.setOutputKeyClass(Text.class);   
  161.             job.setOutputValueClass(Text.class);   
  162.             job.waitForCompletion(true);   
  163.             return job.isSuccessful()?0:1;   
  164.     }   
  165.     public static void main(String[] args) throws IOException,   
  166.             ClassNotFoundException, InterruptedException {   
  167.         try {   
  168.             int returnCode =  ToolRunner.run(new ReduceSideJoin_LeftOuterJoin(),args);   
  169.             System.exit(returnCode);   
  170.         } catch (Exception e) {   
  171.             // TODO Auto-generated catch block   
  172.             logger.error(e.getMessage());   
  173.         }   
  174.     }   

其中具體的分析以及數據的輸出輸入請看代碼中的註釋已經寫得比較清楚了,這裏主要分析一下reduce join的一些不足。之所以會存在reduce join這種方式,我們可以很明顯的看出原:因爲整體數據被分割了,每個map task只處理一部分數據而不能夠獲取到所有需要的join字段,因此我們需要在講join key作爲reduce端的分組將所有join key相同的記錄集中起來進行處理,所以reduce join這種方式就出現了。這種方式的缺點很明顯就是會造成map和reduce端也就是shuffle階段出現大量的數據傳輸,效率很低。

2、在Map端進行連接。

使用場景:一張表十分小、一張表很大。

用法:在提交作業的時候先將小表文件放到該作業的DistributedCache中,然後從DistributeCache中取出該小表進行join key / value解釋分割放到內存中(可以放大Hash Map等等容器中)。然後掃描大表,看大表中的每條記錄的join key /value值是否能夠在內存中找到相同join key的記錄,如果有則直接輸出結果。

直接上代碼,比較簡單:

  1. package com.mr.mapSideJoin;   
  2. import java.io.BufferedReader;   
  3. import java.io.FileReader;   
  4. import java.io.IOException;   
  5. import java.util.HashMap;   
  6. import org.apache.hadoop.conf.Configuration;   
  7. import org.apache.hadoop.conf.Configured;   
  8. import org.apache.hadoop.filecache.DistributedCache;   
  9. import org.apache.hadoop.fs.Path;   
  10. import org.apache.hadoop.io.Text;   
  11. import org.apache.hadoop.mapreduce.Job;   
  12. import org.apache.hadoop.mapreduce.Mapper;   
  13. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;   
  14. import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;   
  15. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;   
  16. import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;   
  17. import org.apache.hadoop.util.Tool;   
  18. import org.apache.hadoop.util.ToolRunner;   
  19. import org.slf4j.Logger;   
  20. import org.slf4j.LoggerFactory;   
  21. /**   
  22.  * @author zengzhaozheng   
  23.  *   
  24.  * 用途說明:   
  25.  * Map side join中的left outer join   
  26.  * 左連接,兩個文件分別代表2個表,連接字段table1的id字段和table2的cityID字段   
  27.  * table1(左表):tb_dim_city(id int,name string,orderid int,city_code,is_show),   
  28.  * 假設tb_dim_city文件記錄數很少,tb_dim_city.dat文件內容,分隔符爲"|":   
  29.  * id     name  orderid  city_code  is_show   
  30.  * 0       其他        9999     9999         0   
  31.  * 1       長春        1        901          1   
  32.  * 2       吉林        2        902          1   
  33.  * 3       四平        3        903          1   
  34.  * 4       松原        4        904          1   
  35.  * 5       通化        5        905          1   
  36.  * 6       遼源        6        906          1   
  37.  * 7       白城        7        907          1   
  38.  * 8       白山        8        908          1   
  39.  * 9       延吉        9        909          1   
  40.  * -------------------------風騷的分割線-------------------------------   
  41.  * table2(右表):tb_user_profiles(userID int,userName string,network string,double flow,cityID int)   
  42.  * tb_user_profiles.dat文件內容,分隔符爲"|":   
  43.  * userID   network     flow    cityID   
  44.  * 1           2G       123      1   
  45.  * 2           3G       333      2   
  46.  * 3           3G       555      1   
  47.  * 4           2G       777      3   
  48.  * 5           3G       666      4   
  49.  * -------------------------風騷的分割線-------------------------------   
  50.  *  結果:   
  51.  *  1   長春  1   901 1   1   2G  123   
  52.  *  1   長春  1   901 1   3   3G  555   
  53.  *  2   吉林  2   902 1   2   3G  333   
  54.  *  3   四平  3   903 1   4   2G  777   
  55.  *  4   松原  4   904 1   5   3G  666   
  56.  */ 
  57. public class MapSideJoinMain extends Configured implements Tool{   
  58.     private static final Logger logger = LoggerFactory.getLogger(MapSideJoinMain.class);   
  59.     public static class LeftOutJoinMapper extends Mapper<Object, Text, Text, Text> {
  60.  
  61.         private HashMap<String,String> city_info = new HashMap<String, String>();   
  62.         private Text outPutKey = new Text();   
  63.         private Text outPutValue = new Text();   
  64.         private String mapInputStr = null;   
  65.         private String mapInputSpit[] = null;   
  66.         private String city_secondPart = null;   
  67.         /**   
  68.          * 此方法在每個task開始之前執行,這裏主要用作從DistributedCache   
  69.          * 中取到tb_dim_city文件,並將裏邊記錄取出放到內存中。   
  70.          */ 
  71.         @Override 
  72.         protected void setup(Context context)   
  73.                 throws IOException, InterruptedException {   
  74.             BufferedReader br = null;   
  75.             //獲得當前作業的DistributedCache相關文件   
  76.             Path[] distributePaths = DistributedCache.getLocalCacheFiles(context.getConfiguration());   
  77.             String cityInfo = null;   
  78.             for(Path p : distributePaths){   
  79.                 if(p.toString().endsWith("tb_dim_city.dat")){   
  80.                     //讀緩存文件,並放到mem中   
  81.                     br = new BufferedReader(new FileReader(p.toString()));   
  82.                     while(null!=(cityInfo=br.readLine())){   
  83.                         String[] cityPart = cityInfo.split("\\|",5);   
  84.                         if(cityPart.length ==5){   
  85.                             city_info.put(cityPart[0], cityPart[1]+"\t"+cityPart[2]+"\t"+cityPart[3]+"\t"+cityPart[4]);   
  86.                         }   
  87.                     }   
  88.                 }   
  89.             }   
  90.         }
  91.  
  92.         /**   
  93.          * Map端的實現相當簡單,直接判斷tb_user_profiles.dat中的   
  94.          * cityID是否存在我的map中就ok了,這樣就可以實現Map Join了   
  95.          */ 
  96.         @Override 
  97.         protected void map(Object key, Text value, Context context)   
  98.                 throws IOException, InterruptedException {   
  99.             //排掉空行   
  100.             if(value == null || value.toString().equals("")){   
  101.                 return;   
  102.             }   
  103.             mapInputStr = value.toString();   
  104.             mapInputSpit = mapInputStr.split("\\|",4);   
  105.             //過濾非法記錄   
  106.             if(mapInputSpit.length != 4){   
  107.                 return;   
  108.             }   
  109.             //判斷鏈接字段是否在map中存在   
  110.             city_secondPart = city_info.get(mapInputSpit[3]);   
  111.             if(city_secondPart != null){   
  112.                 this.outPutKey.set(mapInputSpit[3]);   
  113.                 this.outPutValue.set(city_secondPart+"\t"+mapInputSpit[0]+"\t"+mapInputSpit[1]+"\t"+mapInputSpit[2]);   
  114.                 context.write(outPutKey, outPutValue);   
  115.             }   
  116.         }   
  117.     }   
  118.     @Override 
  119.     public int run(String[] args) throws Exception {   
  120.             Configuration conf=getConf(); //獲得配置文件對象   
  121.             DistributedCache.addCacheFile(new Path(args[1]).toUri(), conf);//爲該job添加緩存文件   
  122.             Job job=new Job(conf,"MapJoinMR");   
  123.             job.setNumReduceTasks(0);
  124.  
  125.             FileInputFormat.addInputPath(job, new Path(args[0])); //設置map輸入文件路徑   
  126.             FileOutputFormat.setOutputPath(job, new Path(args[2])); //設置reduce輸出文件路徑
  127.  
  128.             job.setJarByClass(MapSideJoinMain.class);   
  129.             job.setMapperClass(LeftOutJoinMapper.class);
  130.  
  131.             job.setInputFormatClass(TextInputFormat.class); //設置文件輸入格式   
  132.             job.setOutputFormatClass(TextOutputFormat.class);//使用默認的output格式
  133.  
  134.             //設置map的輸出key和value類型   
  135.             job.setMapOutputKeyClass(Text.class);
  136.  
  137.             //設置reduce的輸出key和value類型   
  138.             job.setOutputKeyClass(Text.class);   
  139.             job.setOutputValueClass(Text.class);   
  140.             job.waitForCompletion(true);   
  141.             return job.isSuccessful()?0:1;   
  142.     }   
  143.     public static void main(String[] args) throws IOException,   
  144.             ClassNotFoundException, InterruptedException {   
  145.         try {   
  146.             int returnCode =  ToolRunner.run(new MapSideJoinMain(),args);   
  147.             System.exit(returnCode);   
  148.         } catch (Exception e) {   
  149.             // TODO Auto-generated catch block   
  150.             logger.error(e.getMessage());   
  151.         }   
  152.     }   

這裏說說DistributedCache。DistributedCache是分佈式緩存的一種實現,它在整個MapReduce框架中起着相當重要的作用,他可以支撐我們寫一些相當複雜高效的分佈式程序。說回到這裏,JobTracker在作業啓動之前會獲取到DistributedCache的資源uri列表,並將對應的文件分發到各個涉及到該作業的任務的TaskTracker上。另外,關於DistributedCache和作業的關係,比如權限、存儲路徑區分、public和private等屬性,接下來有用再整理研究一下寫一篇blog,這裏就不詳細說了。

另外還有一種比較變態的Map Join方式,就是結合HBase來做Map Join操作。這種方式完全可以突破內存的控制,使你毫無忌憚的使用Map Join,而且效率也非常不錯。

3、SemiJoin。

SemiJoin就是所謂的半連接,其實仔細一看就是reduce join的一個變種,就是在map端過濾掉一些數據,在網絡中只傳輸參與連接的數據不參與連接的數據不必在網絡中進行傳輸,從而減少了shuffle的網絡傳輸量,使整體效率得到提高,其他思想和reduce join是一模一樣的。說得更加接地氣一點就是將小表中參與join的key單獨抽出來通過DistributedCach分發到相關節點,然後將其取出放到內存中(可以放到HashSet中),在map階段掃描連接表,將join key不在內存HashSet中的記錄過濾掉,讓那些參與join的記錄通過shuffle傳輸到reduce端進行join操作,其他的和reduce join都是一樣的。看代碼:

  1. package com.mr.SemiJoin;   
  2. import java.io.BufferedReader;   
  3. import java.io.FileReader;   
  4. import java.io.IOException;   
  5. import java.util.ArrayList;   
  6. import java.util.HashSet;   
  7. import org.apache.hadoop.conf.Configuration;   
  8. import org.apache.hadoop.conf.Configured;   
  9. import org.apache.hadoop.filecache.DistributedCache;   
  10. import org.apache.hadoop.fs.Path;   
  11. import org.apache.hadoop.io.Text;   
  12. import org.apache.hadoop.mapreduce.Job;   
  13. import org.apache.hadoop.mapreduce.Mapper;   
  14. import org.apache.hadoop.mapreduce.Reducer;   
  15. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;   
  16. import org.apache.hadoop.mapreduce.lib.input.FileSplit;   
  17. import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;   
  18. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;   
  19. import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;   
  20. import org.apache.hadoop.util.Tool;   
  21. import org.apache.hadoop.util.ToolRunner;   
  22. import org.slf4j.Logger;   
  23. import org.slf4j.LoggerFactory;   
  24. /**   
  25.  * @author zengzhaozheng   
  26.  *   
  27.  * 用途說明:   
  28.  * reudce side join中的left outer join   
  29.  * 左連接,兩個文件分別代表2個表,連接字段table1的id字段和table2的cityID字段   
  30.  * table1(左表):tb_dim_city(id int,name string,orderid int,city_code,is_show)   
  31.  * tb_dim_city.dat文件內容,分隔符爲"|":   
  32.  * id     name  orderid  city_code  is_show   
  33.  * 0       其他        9999     9999         0   
  34.  * 1       長春        1        901          1   
  35.  * 2       吉林        2        902          1   
  36.  * 3       四平        3        903          1   
  37.  * 4       松原        4        904          1   
  38.  * 5       通化        5        905          1   
  39.  * 6       遼源        6        906          1   
  40.  * 7       白城        7        907          1   
  41.  * 8       白山        8        908          1   
  42.  * 9       延吉        9        909          1   
  43.  * -------------------------風騷的分割線-------------------------------   
  44.  * table2(右表):tb_user_profiles(userID int,userName string,network string,double flow,cityID int)   
  45.  * tb_user_profiles.dat文件內容,分隔符爲"|":   
  46.  * userID   network     flow    cityID   
  47.  * 1           2G       123      1   
  48.  * 2           3G       333      2   
  49.  * 3           3G       555      1   
  50.  * 4           2G       777      3   
  51.  * 5           3G       666      4   
  52.  * -------------------------風騷的分割線-------------------------------   
  53.  * joinKey.dat內容:   
  54.  * city_code   
  55.  * 1   
  56.  * 2   
  57.  * 3   
  58.  * 4   
  59.  * -------------------------風騷的分割線-------------------------------   
  60.  *  結果:   
  61.  *  1   長春  1   901 1   1   2G  123   
  62.  *  1   長春  1   901 1   3   3G  555   
  63.  *  2   吉林  2   902 1   2   3G  333   
  64.  *  3   四平  3   903 1   4   2G  777   
  65.  *  4   松原  4   904 1   5   3G  666   
  66.  */ 
  67. public class SemiJoin extends Configured implements Tool{   
  68.     private static final Logger logger = LoggerFactory.getLogger(SemiJoin.class);   
  69.     public static class SemiJoinMapper extends Mapper<Object, Text, Text, CombineValues> {   
  70.         private CombineValues combineValues = new CombineValues();   
  71.         private HashSet<String> joinKeySet = new HashSet<String>();   
  72.         private Text flag = new Text();   
  73.         private Text joinKey = new Text();   
  74.         private Text secondPart = new Text();   
  75.         /**   
  76.          * 將參加join的key從DistributedCache取出放到內存中,以便在map端將要參加join的key過濾出來。b   
  77.          */ 
  78.         @Override 
  79.         protected void setup(Context context)   
  80.                 throws IOException, InterruptedException {   
  81.             BufferedReader br = null;   
  82.             //獲得當前作業的DistributedCache相關文件   
  83.             Path[] distributePaths = DistributedCache.getLocalCacheFiles(context.getConfiguration());   
  84.             String joinKeyStr = null;   
  85.             for(Path p : distributePaths){   
  86.                 if(p.toString().endsWith("joinKey.dat")){   
  87.                     //讀緩存文件,並放到mem中   
  88.                     br = new BufferedReader(new FileReader(p.toString()));   
  89.                     while(null!=(joinKeyStr=br.readLine())){   
  90.                         joinKeySet.add(joinKeyStr);   
  91.                     }   
  92.                 }   
  93.             }   
  94.         }   
  95.         @Override 
  96.         protected void map(Object key, Text value, Context context)   
  97.                 throws IOException, InterruptedException {   
  98.             //獲得文件輸入路徑   
  99.             String pathName = ((FileSplit) context.getInputSplit()).getPath().toString();   
  100.             //數據來自tb_dim_city.dat文件,標誌即爲"0"   
  101.             if(pathName.endsWith("tb_dim_city.dat")){   
  102.                 String[] valueItems = value.toString().split("\\|");   
  103.                 //過濾格式錯誤的記錄   
  104.                 if(valueItems.length != 5){   
  105.                     return;   
  106.                 }   
  107.                 //過濾掉不需要參加join的記錄   
  108.                 if(joinKeySet.contains(valueItems[0])){   
  109.                     flag.set("0");   
  110.                     joinKey.set(valueItems[0]);   
  111.                     secondPart.set(valueItems[1]+"\t"+valueItems[2]+"\t"+valueItems[3]+"\t"+valueItems[4]);   
  112.                     combineValues.setFlag(flag);   
  113.                     combineValues.setJoinKey(joinKey);   
  114.                     combineValues.setSecondPart(secondPart);   
  115.                     context.write(combineValues.getJoinKey(), combineValues);   
  116.                 }else{   
  117.                     return ;   
  118.                 }   
  119.             }//數據來自於tb_user_profiles.dat,標誌即爲"1"   
  120.             else if(pathName.endsWith("tb_user_profiles.dat")){   
  121.                 String[] valueItems = value.toString().split("\\|");   
  122.                 //過濾格式錯誤的記錄   
  123.                 if(valueItems.length != 4){   
  124.                     return;   
  125.                 }   
  126.                 //過濾掉不需要參加join的記錄   
  127.                 if(joinKeySet.contains(valueItems[3])){   
  128.                     flag.set("1");   
  129.                     joinKey.set(valueItems[3]);   
  130.                     secondPart.set(valueItems[0]+"\t"+valueItems[1]+"\t"+valueItems[2]);   
  131.                     combineValues.setFlag(flag);   
  132.                     combineValues.setJoinKey(joinKey);   
  133.                     combineValues.setSecondPart(secondPart);   
  134.                     context.write(combineValues.getJoinKey(), combineValues);   
  135.                 }else{   
  136.                     return ;   
  137.                 }   
  138.             }   
  139.         }   
  140.     }   
  141.     public static class SemiJoinReducer extends Reducer<Text, CombineValues, Text, Text> {   
  142.         //存儲一個分組中的左表信息   
  143.         private ArrayList<Text> leftTable = new ArrayList<Text>();   
  144.         //存儲一個分組中的右表信息   
  145.         private ArrayList<Text> rightTable = new ArrayList<Text>();   
  146.         private Text secondPar = null;   
  147.         private Text output = new Text();   
  148.         /**   
  149.          * 一個分組調用一次reduce函數   
  150.          */ 
  151.         @Override 
  152.         protected void reduce(Text key, Iterable<CombineValues> value, Context context)   
  153.                 throws IOException, InterruptedException {   
  154.             leftTable.clear();   
  155.             rightTable.clear();   
  156.             /**   
  157.              * 將分組中的元素按照文件分別進行存放   
  158.              * 這種方法要注意的問題:   
  159.              * 如果一個分組內的元素太多的話,可能會導致在reduce階段出現OOM,   
  160.              * 在處理分佈式問題之前最好先了解數據的分佈情況,根據不同的分佈採取最   
  161.              * 適當的處理方法,這樣可以有效的防止導致OOM和數據過度傾斜問題。   
  162.              */ 
  163.             for(CombineValues cv : value){   
  164.                 secondPar = new Text(cv.getSecondPart().toString());   
  165.                 //左表tb_dim_city   
  166.                 if("0".equals(cv.getFlag().toString().trim())){   
  167.                     leftTable.add(secondPar);   
  168.                 }   
  169.                 //右表tb_user_profiles   
  170.                 else if("1".equals(cv.getFlag().toString().trim())){   
  171.                     rightTable.add(secondPar);   
  172.                 }   
  173.             }   
  174.             logger.info("tb_dim_city:"+leftTable.toString());   
  175.             logger.info("tb_user_profiles:"+rightTable.toString());   
  176.             for(Text leftPart : leftTable){   
  177.                 for(Text rightPart : rightTable){   
  178.                     output.set(leftPart+ "\t" + rightPart);   
  179.                     context.write(key, output);   
  180.                 }   
  181.             }   
  182.         }   
  183.     }   
  184.     @Override 
  185.     public int run(String[] args) throws Exception {   
  186.             Configuration conf=getConf(); //獲得配置文件對象   
  187.             DistributedCache.addCacheFile(new Path(args[2]).toUri(), conf);
  188.             Job job=new Job(conf,"LeftOutJoinMR");   
  189.             job.setJarByClass(SemiJoin.class);
  190.  
  191.             FileInputFormat.addInputPath(job, new Path(args[0])); //設置map輸入文件路徑   
  192.             FileOutputFormat.setOutputPath(job, new Path(args[1])); //設置reduce輸出文件路徑
  193.  
  194.             job.setMapperClass(SemiJoinMapper.class);   
  195.             job.setReducerClass(SemiJoinReducer.class);
  196.  
  197.             job.setInputFormatClass(TextInputFormat.class); //設置文件輸入格式   
  198.             job.setOutputFormatClass(TextOutputFormat.class);//使用默認的output格式
  199.  
  200.             //設置map的輸出key和value類型   
  201.             job.setMapOutputKeyClass(Text.class);   
  202.             job.setMapOutputValueClass(CombineValues.class);
  203.  
  204.             //設置reduce的輸出key和value類型   
  205.             job.setOutputKeyClass(Text.class);   
  206.             job.setOutputValueClass(Text.class);   
  207.             job.waitForCompletion(true);   
  208.             return job.isSuccessful()?0:1;   
  209.     }   
  210.     public static void main(String[] args) throws IOException,   
  211.             ClassNotFoundException, InterruptedException {   
  212.         try {   
  213.             int returnCode =  ToolRunner.run(new SemiJoin(),args);   
  214.             System.exit(returnCode);   
  215.         } catch (Exception e) {   
  216.             logger.error(e.getMessage());   
  217.         }   
  218.     }   

這裏還說說SemiJoin也是有一定的適用範圍的,其抽取出來進行join的key是要放到內存中的,所以不能夠太大,容易在Map端造成OOM。

三、總結

blog介紹了三種join方式。這三種join方式適用於不同的場景,其處理效率上的相差還是蠻大的,其中主要導致因素是網絡傳輸。Map join效率最高,其次是SemiJoin,最低的是reduce join。另外,寫分佈式大數據處理程序的時最好要對整體要處理的數據分佈情況作一個瞭解,這可以提高我們代碼的效率,使數據的傾斜度降到最低,使我們的代碼傾向性更好。


發佈了67 篇原創文章 · 獲贊 16 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章