Reduce Side Join实现

简介: 关于reduce边join,其最重要的是使用MultipleInputs.addInputPath这个api对不同的表使用不同的Map,然后在每个Map里做一下该表的标识,最后到了Reduce端再根据标识区分对应的表!Reduce Side Join Exa...

关于reduce边join,其最重要的是使用MultipleInputs.addInputPath这个api对不同的表使用不同的Map,然后在每个Map里做一下该表的标识,最后到了Reduce端再根据标识区分对应的表!


Reduce Side Join Example

User and comment join

In thisexample, we’ll be using theusers and comments tables from the StackOverflow dataset. Storing data in this matter makessense, as storingrepetitive user data witheach comment is unnecessary. Thiswould also makeupdating user information diffi‐ cult. However,having disjoint data sets posesproblems when it comes to associating a comment with the user who wroteit. Through the use of a reduceside join, thesetwo data sets canbe merged together using the userID as the foreign key. In this example, we’ll perform an inner, outer, and antijoin. The choice of which join to execute is set during job configuration.

Hadoop supportsthe ability to use multipleinput data typesat once, allowingyou to create a mapper classand input formatfor each inputsplit from different data sources. This is extremely helpful, because you don’t have to code logic for two different data inputs in the samemap implementation. In the following example, two mapperclasses are created: one for the user data and one for the comments. Each mapper classoutputs the user ID as the foreignkey, and the entire record as the value along with a single character to flag whichrecord came fromwhat set. Thereducer then copiesall values for eachgroup in memory, keepingtrack of whichrecord came fromwhat data set.The records are then joined togetherand output.

 



The following descriptions of eachcode section explainthe solution to the problem.

Problem: Given a set of user information and a list of user’s comments, enrich each comment with the information about the userwho created thecomment.

 

Drivercode.The job configurationis slightly different from the standard configuration due to the user of themultiple input utility. We also set the join type in the jobconfig‐ uration to args[2] so it can be used in the reducer. The relevant piece of the drivercode to use the MultipleInput follows:

...

// Use MultipleInputs to set which inputuses what mapper

// This will keep parsingof each dataset separate froma logical standpoint

// The firsttwo elements of theargs arrayare the two inputs 

MultipleInputs.addInputPath(job, new Path(args[0]), TextInputFormat.class,UserJoinMapper.class);

MultipleInputs.addInputPath(job,newPath(args[1]), TextInputFormat.class, CommentJoinMapper.class);

 

job.getConfiguration()..set("join.type", args[2]);

...

 

User mappercode.This mapper parseseach input lineof user dataXML. It grabs theuser ID associated with each record and outputs it along with the entire input  value. It prepends the letter A in front of theentire value. This allows the reducer to know which values came from what data  set.

public static class UserJoinMapper extendsMapper<Object, Text, Text, Text> {

 

private Text outkey =newText();

private Text outvalue =newText();

 

public void map(Object key, Text value, Context context) throwsIOException, InterruptedException {

 

// Parse the input stringinto a nice map

Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());

 

String userId = parsed.get("Id");

 

// The foreign join keyis the userID

outkey.set(userId);

 

// Flag this record for the reducerand then outputoutvalue.set("A" + value.toString()); context.write(outkey, outvalue);

}

}



When you output the value from the map side, the entire record doesn’t have to be sent. This is an opportunity to optimize the join by keepingonly the fields of data you want to join together. It requiresmore pro‐ cessing on the map side, but is worthit in the long run. Also, sincethe foreign key is in the map output key, you don’t need to keep that in the value, either.

 

 

Comment mapper code.This mapper parseseach input line of commentXML. Very sim‐ ilar to the UserJoinMapper,it too grabs the user ID associated with each record and outputs it along with the entire inputvalue. The only different here is that the XML attribute UserId representsthe user that posted to comment, where as Id in theuser  data set is the user ID. Here, this mapper prepends the letter B in front ofthe entire value.

public static class CommentJoinMapper extends Mapper<Object, Text, Text, Text> {

 

private Text outkey =newText();

private Text outvalue =newText();

 

public void map(Object key, Text value, Context context)

throws IOException, InterruptedException {

 

Map<String, String> parsed = transformXmlToMap(value.toString());

 

// The foreign join keyis the userID

outkey.set( parsed.get("UserId"));

 

// Flag this record for the reducerand then outputoutvalue.set("B" + value.toString()); context.write(outkey, outvalue);

}

}

 

Reducer code.The reducer code iterates through all thevalues of each group and looks atwhat each record is tagged with and then puts the record in one of two lists.After all values are binned in either list, the actual join logic is executedusing the two lists. The join logic differs slightly based on the type of join,but always involves iterating through both lists and writing to the Context object.The type of join is pulled from the job configuration in the setup method. Let’s look at the main reduce method before looking at the join logic.

public static class UserJoinReducer extendsReducer<Text, Text, Text, Text> {

 

private staticfinal Text EMPTY_TEXT = Text("");

private Text tmp =newText();

private ArrayList<Text> listA =newArrayList<Text>();

private ArrayList<Text> listB =newArrayList<Text>();


private String joinType =null;

 

public void setup(Context context) {

// Get the type of join fromour configuration

joinType=context.getConfiguration().get("join.type");

}

 

public void reduce(Text key, Iterable<Text> values, Context context)

throws IOException, InterruptedException {

 

// Clear ourlists listA.clear(); listB.clear();

 

// iterate throughall our values,binning each recordbased on what

// it was tagged with.Make sure to remove thetag!

while(values.hasNext()) { tmp=values.next();

if (tmp.charAt(0) == 'A') {

listA.add(new Text(tmp.toString().substring(1)));

} else if (tmp.charAt('0') == 'B') {

listB.add(new Text(tmp.toString().substring(1)));

}

}

 

// Execute our join logicnow that the lists are filled

executeJoinLogic(context);

}

 

private void executeJoinLogic(Context context)

throws IOException, InterruptedException {

...

}

The input data types tothe reducer are two Text objects. The input key isthe foreign join key, which in this example is the user’s ID. The input values associated with the foreign key contain one record from the “users” data set tagged with ‘B’, as well as all the comments the user posted tagged with ‘B’. Any type of data formatting you would want toperform should be done here prior to outputting. For simplicity, the raw XML value from the left data set (users)is output as the key and the raw XML value from the rightdata set (comments) is output as the value.

Next, let’s look at each of the join types. First up is an inner join. If both the lists are not empty, simply performtwo nested forloops and joineach of thevalues together.

if (joinType.equalsIgnoreCase("inner")) {

// If both lists are not empty,join A with B

if (!listA.isEmpty() && !listB.isEmpty()) {

for (Text A : listA) {

for(Text B : listB) { context.write(A, B);


}

}

}

}...

For aleft outer join,if the right list is not empty, join A with B.If the right list is empty, outputeach record of A with an empty string.

... else if(joinType.equalsIgnoreCase("leftouter")) {

// For each entry in A,

for (Text A : listA) {

// If list B is not empty,join A andB

if (!listB.isEmpty()) {

for(Text B : listB) { context.write(A, B);

}

}else{

// Else, outputA by itself

context.write(A, EMPTY_TEXT);

}

}

}...

A rightouter join is very similar, except switching from the check for empty elements fromBto A. If the left list is empty, write records from B withan empty output key.

...else if (joinType.equalsIgnoreCase("rightouter")) {

// For each entry in B,

for (Text B : listB) {

// If list A is not empty,join A andB

if (!listA.isEmpty()) {

for(Text A : listA) { context.write(A, B);

}

} else {

// Else, outputB by itself

context.write(EMPTY_TEXT, B);

}

}

}...

A fullouter join is more complex, in that we want to keep allrecords, ensuring thatwe join records whereappropriate. If list A is not empty, then for everyelement inA, join withB whenthe B listis not empty, or output A by itself. IfA isempty, then just output B.

... else if (joinType.equalsIgnoreCase("fullouter")) {

// If list A is not empty

if (!listA.isEmpty()) {

// For each entry in A

for (Text A : listA) {

// If list B is not empty,join A with B

if (!listB.isEmpty()) {


for(Text B : listB) { context.write(A, B);

}

}else {

// Else, outputA by itself

context.write(A, EMPTY_TEXT);

}

}

} else {

// If list A is empty, just output B

for (Text B : listB) { context.write(EMPTY_TEXT, B);

}

}

}...

For anantijoin, if at least one of the lists is empty, output the recordsfrom the non- empty list with an empty Text object.

... else if(joinType.equalsIgnoreCase("anti")) {

// If list A is empty and B is empty or vice versa

if (listA.isEmpty() ^ listB.isEmpty()) {

 

// Iterate both A and B with null values

// The previous XOR checkwill make sure exactly one of

// these lists is emptyand therefore the list will be skipped

for (Text A : listA) { context.write(A, EMPTY_TEXT);

}

 

for (Text B : listB) { context.write(EMPTY_TEXT, B);


 

}

}


目录
相关文章
|
安全 容灾 项目管理
 2023年上半年信息系统项目管理师综合知识真题与答案解释(1)
 2023年上半年信息系统项目管理师综合知识真题与答案解释(1)
747 1
|
人工智能 Kubernetes 安全
阿里云 ACK 新升级,打造智算时代的现代化应用平台
阿里云 ACK 新升级,打造智算时代的现代化应用平台
71669 10
|
存储 缓存 网络协议
DNS攻击基础
DNS攻击基础
|
开发者
AppsFlyer 研究(十六)广告平台配置及代理商授权总结
AppsFlyer 研究(十六)广告平台配置及代理商授权总结
1598 0
|
4月前
|
自然语言处理 测试技术 API
大模型Qwen3.8‑Max‑Preview深度解析:2.4万亿参数MoE旗舰模型API实战落地指南
大模型技术持续快速迭代,混合专家架构成为旗舰模型主流技术路线。Qwen3.8‑Max‑Preview作为新一代旗舰预览版本,以2.4万亿总参数的MoE稀疏混合专家架构为底座,兼具百万级超长上下文、原生全模态理解、双推理机制、全栈工程代码生成、多智能体协同自动化等能力,是开发者、企业构建AI应用的重要基座。该模型打破传统大模型“参数大但是实际推理成本居高不下”的困境,兼顾复杂任务推理精度与运行成本。本文完整拆解底层架构、五大核心能力,提供可直接复制运行的Python、cURL调用代码,覆盖开发、文档处理、多模态、智能体自动化业务场景,同时整理实用调优技巧与常见故障排查方案,帮助开发者快速完成业务
450 1
|
5月前
|
人工智能 关系型数据库 MySQL
给你的AI Agent装上"行为记忆":agentmemory安装到整合全指南
agentmemory是专为AI Agent设计的本地化“情节记忆”引擎,解决其无状态、易失忆问题。它自动记录操作历史、决策与教训,支持LLM压缩、向量检索与知识图谱,R@5召回率达95.2%,节省92% token,开源(Apache 2.0),零外部依赖,15分钟即可部署启用。
1400 0
|
6月前
|
数据采集 监控 数据管理
数据治理是什么,怎么开展——从概念到落地的完整拆解
数据治理是什么、管什么、怎么开展?本文从企业真实痛点出发,将数据治理拆解为六项核心任务(数据标准、数据质量、元数据、主数据、数据安全、数据生命周期),并给出从零启动的四阶段落地路径:启动准备→摸清家底→建立基线→持续运营,附五个常见失败模式及避坑建议。
|
8月前
|
安全 网络协议 Android开发
基于开源MobileIMSDK框架,即时通讯IM产品RainbowChat v12.0发布
RainbowChat 是一套基于 MobileIMSDK 开源通信框架的产品级移动端IM系统。可能是市面上开放源码的,唯一一款同时支持TCP、UDP、WebSocket三种网络通信协议的IM产品。
487 3
|
8月前
|
人工智能 监控 API
阿里云/本地部署 OpenClaw 搭建全自动情报助手:Tavily+Apify+Decodo工具链+千问/Coding Plan配置实战教程
2026年,OpenClaw(原Clawdbot)已经从单纯的对话框架,进化为可自主完成信息检索、网页抓取、定时监控、结果推送的全自动AI助手。通过搭配Tavily智能搜索、Apify结构化抓取、Decodo代理IP这三类工具,OpenClaw可以真正做到无人值守、自动干活,覆盖竞品监控、选题挖掘、客户尽调、内容聚合等高频办公场景。本文完整还原工具配置逻辑、实战指令、踩坑记录,并同步提供**2026阿里云轻量服务器部署、本地MacOS/Linux/Windows11部署流程、阿里云千问Qwen3.6-Plus与免费Coding Plan API配置、常见问题一站式解答**,所有代码可直接复制运
883 0
|
机器学习/深度学习 人工智能 算法
DeepSeek深度解析:一场「通用人工智能」的觉醒革命
DeepSeek,由幻方量化打造的国产大模型,正以彗星般的速度革新AI领域。它不仅刷新了中文AI技术基准,还在底层架构上实现颠覆性突破。文章从技术逻辑、产业影响和未来挑战三个维度解析这场AI革命。DeepSeek采用多模态神经网络设计,融合异构数据,展现通感能力;引入动态神经元编织与具身智能,提升参数效率。其混合架构在数学推理中表现卓越,并通过认知卸载机制优化长文本处理。DeepSeek正在重塑金融投研范式,推动AI原生开发模式,同时引发对伦理与硬件限制的深思。最终,DeepSeek重新诠释了“智能”本质,促使人类与AI共同进化为认知伙伴。
929 8