MapJoin适用于一张表示十分小,一张表十分大的场景。在Map端缓存多张表,提前处理业务逻辑,这样增加Map端业务,减少Reduce端数据的压力,尽可能的减少数据倾斜。
1 京东
2 淘宝
3 亚马逊
3 shampoo 25
1 novel 70
2 phone 3999
1 desk 94
3 noodles 20
2 ipad 4988
1 notebook 20
2 computer 5999
3 clothes 111
1 pen 4
3 pizza 60
第一张表是公司(id,名称),第二张表的商品(id,商品名称,价格)。将这两个表合并(join),形成一个如下的新表。
1 京东 pen 4
1 京东 notebook 20
1 京东 desk 94
1 京东 novel 70
2 淘宝 computer 5999
2 淘宝 ipad 4988
2 淘宝 phone 3999
3 亚马逊 pizza 60
3 亚马逊 clothes 111
3 亚马逊 noodles 20
3 亚马逊 shampoo 25
驱动类设置要加载的缓存数据,job.addCacheFile(new URI(“file:///e:/brand.txt”));,注意URL的格式(file:///)。
public class MapJoinDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, URISyntaxException {
args = new String[] {
"e:/order.txt", "e:/output"};
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJarByClass(MapJoinDriver.class);
job.setMapperClass(MapJoinMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
//加载缓存数据
job.addCacheFile(new URI("file:///e:/brand.txt"));
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
boolean result = job.waitForCompletion(true);
System.exit(result ? 0 : 1);
}
}
setup的时候缓存一张小表,map的时候就可以使用这张表。
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.IOUtils;
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>{
Text k = new Text();
Text v = new Text();
HashMap<String, String> map = new HashMap<>();
@Override
protected void setup(Mapper<LongWritable, Text, Text, Text>.Context context)
throws IOException, InterruptedException {
URI[] uri = context.getCacheFiles();
String path = uri[0].getPath().toString();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
String line;
while(StringUtils.isNotEmpty(line = reader.readLine())) {
String[] split = line.split(" ");
map.put(split[0], split[1]);
}
IOUtils.closeStream(reader);
}
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
throws IOException, InterruptedException {
String[] split = value.toString().split(" ");
k.set(split[0]);
v.set(map.get(split[0]) + " " + split[1] + " " + split[2]);
context.write(k, v);
}
}