MapReduce 表连接之Reduce端Join

一:背景

Reduce端连接比Map端连接更为普遍,因为输入的数据不需要特定的结构,但是效率比较低,因为所有数据都必须经过Shuffle过程。

二:技术实现

基本思路
(1):Map端读取所有的文件,并在输出的内容里加上标示,代表数据是从哪个文件里来的。
(2):在reduce处理函数中,按照标识对数据进行处理。

(3):然后根据Key去join来求出结果直接输出。


#需求:现有user表和city表,按cityID进行连接

user表:

1	zhangSan	1
2	liSi	2
3	wangWu	1
4	zhaoLiu	3
5	maQi	3
注:第三列为cityID。

city表:

1	beiJin
2	shangHai
3	guangZhou

注:关于表连接操作,我们可以实现直接打标记的做法,看这里,也可以使用实体bean的方式。这篇文章是采用实体bean的方式实现表连接操作。


实现代码:

UserCity.java:

public class UserCity implements WritableComparable<UserCity>{

	//用户ID
	private String userNo = "";
	//用户名
	private String userName = "";
	//城市ID
	private String cityNo = "";
	//城市名称
	private String cityName = "";
	//用户和城市的标志
	private int flag = 0;
	
	
	public UserCity() {
	}

	
	public UserCity(String userNo, String userName, String cityNo, String cityName, int flag) {
		this.userNo = userNo;
		this.userName = userName;
		this.cityNo = cityNo;
		this.cityName = cityName;
		this.flag = flag;
	}
	
	public UserCity(UserCity user) {
		this.userNo = user.getUserNo();
		this.userName = user.getUserName();
		this.cityNo = user.getCityNo();
		this.cityName = user.getCityName();
		this.flag = user.getFlag();
	}

	

	public String getUserNo() {
		return userNo;
	}


	public void setUserNo(String userNo) {
		this.userNo = userNo;
	}


	public String getUserName() {
		return userName;
	}


	public void setUserName(String userName) {
		this.userName = userName;
	}


	public String getCityNo() {
		return cityNo;
	}


	public void setCityNo(String cityNo) {
		this.cityNo = cityNo;
	}


	public String getCityName() {
		return cityName;
	}


	public void setCityName(String cityName) {
		this.cityName = cityName;
	}


	public int getFlag() {
		return flag;
	}


	public void setFlag(int flag) {
		this.flag = flag;
	}


	@Override
	public void readFields(DataInput input) throws IOException {
		this.userNo = input.readUTF();
		this.userName = input.readUTF();
		this.cityNo = input.readUTF();
		this.cityName = input.readUTF();
		this.flag = input.readInt();
	}

	@Override
	public void write(DataOutput output) throws IOException {
		output.writeUTF(this.userNo);
		output.writeUTF(this.userName);
		output.writeUTF(this.cityNo);
		output.writeUTF(this.cityName);
		output.writeInt(this.flag);
		
	}

	@Override
	public int compareTo(UserCity o) {
		
		return 0;
	}


	@Override
	public String toString() {
		return "userNo=" + userNo + ", userName=" + userName + ", cityName=" + cityName ;
	}
	
	

}
注:把要关联的字段定义到一个实体bean中,并且添加一个Boolean变量,用于标记。


UserCityJoinMapReduce.java:

public class UserCityJoinMapReduce {

	//定义输入输出路径
		private static final String INPATH = "hdfs://liaozhongmin21:8020/reduceJoinFiles";
		private static final String OUTPATH = "hdfs://liaozhongmin21:8020/out";
		
		public static void main(String[] args) {
			try {
				//创建配置
				Configuration conf = new Configuration();
				
				//创建FileSystem
				FileSystem fileSystem = FileSystem.get(new URI(OUTPATH), conf);
				//判断输出文件是否存在,如果存在就进行删除
				if (fileSystem.exists(new Path(OUTPATH))){
					fileSystem.delete(new Path(OUTPATH), true);
				}
				
				//创建Job
				Job job = new Job(conf, UserCityJoinMapReduce.class.getName());
				
				//设置输入文件的输入格式
				job.setInputFormatClass(TextInputFormat.class);
				//设置输入目录
				FileInputFormat.setInputPaths(job, new Path(INPATH));
				
				//设置自定义Mapper
				job.setMapperClass(UserCityJoinMapper.class);
				
				//设置Mapper输出的Key和Value
				job.setMapOutputKeyClass(IntWritable.class);
				job.setMapOutputValueClass(UserCity.class);
				
				//设置分区
				job.setPartitionerClass(HashPartitioner.class);
				//设置Reducer的个数
				job.setNumReduceTasks(1);
				
				//设置自定义的Reducer
				job.setReducerClass(UserCityJoinReducer.class);
				
				//设置输出的格式化类
				job.setOutputFormatClass(TextOutputFormat.class);
				//设置输出目录
				FileOutputFormat.setOutputPath(job, new Path(OUTPATH));
				
				//设置输出的key和value
				job.setOutputKeyClass(NullWritable.class);
				job.setOutputValueClass(Text.class);
				
				//提交任务
				System.exit(job.waitForCompletion(true) ? 1 : 0);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	public static class UserCityJoinMapper extends Mapper<LongWritable, Text, IntWritable, UserCity>{
		//定义输出的key和value
		private IntWritable outKey = new IntWritable();
		private UserCity user = null;
		
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, IntWritable, UserCity>.Context context) throws IOException,
				InterruptedException {
			//获取行文本内容
			String line = value.toString();
			//对行文本内容进行切分
			String[] splits = line.split("\t");
			
			//对字符串数组进行判断
			if (splits.length == 2){//如果长度为2就表示城市信息
				//创建对象
				user = new UserCity();
				//设置属性
				user.setCityNo(splits[0]);
				user.setCityName(splits[1]);
				user.setFlag(0);
				//设置输出的key
				outKey.set(Integer.parseInt(splits[0]));
				//把结果写出去
				context.write(outKey, user);
			} else if (splits.length == 3){//如果长度为3就表示是User对象
				//创建对象
				user = new UserCity();
				//设置属性
				user.setUserNo(splits[0]);
				user.setUserName(splits[1]);
				//不要忘记设置关联属性
				user.setCityNo(splits[2]);
				//设置标志:1表示用户
				user.setFlag(1);
				
				//设置输出去key(城市ID)
				outKey.set(Integer.parseInt(splits[2]));
				//把结果写出去
				context.write(outKey, user);
			}
		}
	}
	
	/**
	 * 城市和用户是一对多(一个城市对应多个用户),也就是说相同key传过来之后的结果就是一个城市和多个用户(这个至关重要!)
	 * 问题:多对多怎么搞?
	 * @author 廖钟民
	 *2015年4月6日下午9:40:17
	 */
	public static class UserCityJoinReducer extends Reducer<IntWritable, UserCity, NullWritable, Text>{
		
		//定义输出的value
		private Text outValue = new Text();
		//城市对象(用于存储唯一的城市)
		private UserCity city = null;
		//定义集合用于存储对象
		private List<UserCity> userCities = new ArrayList<UserCity>();
		
		@Override
		protected void reduce(IntWritable key, Iterable<UserCity> values, Reducer<IntWritable, UserCity, NullWritable, Text>.Context context) throws IOException,
				InterruptedException {
			
			//使用list集合之前,要清空上一次的数据。
			userCities.clear();

			//遍历values,把结果装到List集合中
			for (UserCity u : values){//这个values集合中只有一个城市对象,多个用户对象

				if (u.getFlag() == 0){//如果标志为0表示城市对象,这个是唯一的City对象
					city = new UserCity(u);
				} else {//除了唯一的City对象外,其他的都是用户对象,把这些用户对象都添加到集合里
					userCities.add(new UserCity(u));
				}
			}
			
			//遍历集合(把用户对象的城市信息都给填补上)
			for (UserCity user : userCities){

				//给用户对象设置城市信息
				user.setCityName(city.getCityName());
				//设置写出去value
				outValue.set(user.toString());
				//把结果写出去
				context.write(NullWritable.get(), outValue);
			}
		}
	}
}

程序运行的结果如下:




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MapReduce 中进行单连接join)需要使用到 Map 和 Reduce 两个阶段,具体步骤如下: 1. 将两个要连接按照连接字段进行排序和分区,保证相同连接字段值的记录在同一个分区中。 2. 在 Map 阶段,对于每个分区中的记录,将连接字段作为输出的 key,将记录作为输出的 value,然后将它们发送到 Reduce 阶段进行处理。其中,对于第一个的记录,需要在 value 中添加一个标记以区分不同的记录。 3. 在 Reduce 阶段,对于每个连接字段相同的记录,将它们进行组合,生成连接后的记录。具体步骤如下: a. 对于每个连接字段相同的记录,将它们分别存储到两个缓存中,一个缓存存储第一个的记录,另一个缓存存储第二个的记录。 b. 对于每个第一个的记录,将它与第二个的缓存中相同连接字段的记录进行组合,生成连接后的记录。如果第二个的缓存中没有相同连接字段的记录,则不生成连接记录。 4. 将连接后的记录按照连接字段排序,输出最终结果。 需要注意的是,在 MapReduce 中进行单连接操作会产生大量的中间结果,因此需要进行合理的优化和调整,以提高性能和减少资源消耗。例如,可以使用 Combiner 函数来对 Map 阶段的输出进行局部聚合,减少数据传输量和 Reduce 阶段的计算量。同时,也可以对进行预处理和缓存,以减少数据量和加快处理速度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值