MapReduce中多表合并:
合并选择:
Map:使用于一个小表一个大表
reduce:使用于同时为大表的情况
Map端表合并:
优点:适用于关联表中有小表的情形;
可以将小表分发到所有的map节点,这样,map节点就可以在本地对自己所读到的大表数据进行合并并输出最终结果,可以大大提高合并操作的并发度,加快处理速度。
代码实现:
MapJoin.java
public class MapJoin extends Mapper<LongWritable, Text, Text, NullWritable> {
HashMap hashMap = new HashMap<String,String>();
/**
* 初始化
* @param context
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void setup(Context context) throws IOException, InterruptedException {
//获取缓存文件(小表)
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\Jds\\Desktop\\Data\\pd.txt"), "UTF-8"));
//一行一行读取
String line;
while (StringUtils.isNotEmpty(line = reader.readLine())){
//切分
String[] split = line.split("\t");
//数据存入集合
hashMap.put(split[0],split[1]);
}
}
/**
* 连接
* @param key
* @param value
* @param context
* @throws IOException
* @throws InterruptedException
*/
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//获取数据(大表)
String line = value.toString();
//切分
String[] split = line.split("\t");
//判断
String pid = split[1];
if (hashMap.containsKey(pid)){
context.write(new Text(split[0] + "\t" + hashMap.get(pid) + "\t" + split[2]),NullWritable.get());
}
}
}
JoinDriver.java
public class JoinDriver {
public static void main(String[] args) throws Exception{
args = new String[]{
"C:\\Users\\Jds\\Desktop\\Data\\order.txt",
"C:\\Users\\Jds\\Desktop\\Data\\Join1"}