如何执行一对多map-reduce连接?

时间:2014-12-10 18:03:11

标签: hadoop mapreduce bigdata

当我们有以下情况时,一对多联合案例如何:

文件1

  

personid1,name1

     

personid2,name2

file2的

  

personid1,address2

file2的

  

personid2,address2

我想要减速器输出

  

personid1,name1,address2

     

personid2,name2,address2

2 个答案:

答案 0 :(得分:1)

似乎你可以使用personid作为你的地图制作者的关键。

然后,您将确保在一个reducer中将属于一个personid的所有记录作为迭代器。现在,您需要区分哪个记录来自哪个来源,因此最好将标识符放在值上。

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.LazyOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class ExampleDriver extends Configured implements Tool {


  @Override
  public int run(String[] args) throws Exception {
    Configuration configuration = getConf();

    Job job = Job.getInstance(configuration, this.getClass().getName());

    job.setJarByClass(ExampleDriver.class);

    MultipleInputs.addInputPath(job, new Path(PERSON_DIR), TextInputFormat.class, PersonMapper.class);
    MultipleInputs.addInputPath(job, new Path(ADDRESS_DIR), TextInputFormat.class, AddressMapper.class);


    job.setMapOutputKeyClass(KeyWithPersonId.class);
    job.setMapOutputValueClass(Text.class);
    job.setReducerClass(JoinPersonWithAddressReducer.class);

    LazyOutputFormat.setOutputFormatClass(job, TextOutputFormat.class); // Not necessary. Can use simple FileOutputFormat.

    return job.waitForCompletion(true) ? 0 : 1;
  }

  public static void main(String[] args) throws Exception {
    int exitCode = ToolRunner.run(new Configuration(), new ExampleDriver(), args);
    System.exit(exitCode);
  }
}

如果您有更多问题,请与我们联系。

答案 1 :(得分:1)

我假设每个personid只能有一个名字,但地址很多。

映射器应扫描所有输入文件并生成键值对,如下所示:

(personid1, (0, name1))
(personid2, (0, name2))
(personid1, (1, address2))
(personid2, (1, address2))

整数标志0表示记录来自file1,标志1表示记录来自其他类型的文件

减速器输入将是:

(personid1, [(0, name1), (1, address2)])
(personid2, [(1, address2), (0, name2)])

Hadoop无法保证随机播放输出中原始值的顺序,因此我在上面的第二行中更改了此顺序只是为了说明这一点。 reducer的工作是解码每个记录的(方括号中的列表) - (flag, value)flag = 0将为您提供名称,以及所有其他对会告诉你这个人的所有地址。

享受Hadoop!

相关问题