【发布时间】:2011-12-29 19:23:18
【问题描述】:
有没有办法将构造函数参数提供给 Hadoop 中的映射器?可能通过一些包含 Job 创建的库?
这是我的场景:
public class HadoopTest {
// Extractor turns a line into a "feature"
public static interface Extractor {
public String extract(String s);
}
// A concrete Extractor, configurable with a constructor parameter
public static class PrefixExtractor implements Extractor {
private int endIndex;
public PrefixExtractor(int endIndex) { this.endIndex = endIndex; }
public String extract(String s) { return s.substring(0, this.endIndex); }
}
public static class Map extends Mapper<Object, Text, Text, Text> {
private Extractor extractor;
// Constructor configures the extractor
public Map(Extractor extractor) { this.extractor = extractor; }
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String feature = extractor.extract(value.toString());
context.write(new Text(feature), new Text(value.toString()));
}
}
public static class Reduce extends Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
for (Text val : values) context.write(key, val);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = new Job(conf, "test");
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
}
}
应该清楚,由于 Mapper 仅作为类引用 (Map.class) 提供给 Configuration,因此 Hadoop 无法传递构造函数参数并配置特定的 Extractor。
有 Hadoop 包装框架,例如 Scoobi、Crunch、 Scrunch(可能还有更多我不知道的)似乎具有这种能力,但我不知道它们是如何实现的。 编辑: 在与 Scoobi 合作了一些之后,我发现我在这方面有部分错误。如果您在“映射器”中使用外部定义的对象,Scoobi 要求它是可序列化的,如果不是,则会在运行时报错。所以也许正确的方法就是让我的Extractor可序列化并在Mapper的设置方法中反序列化它......
另外,我实际上在 Scala 工作,因此绝对欢迎基于 Scala 的解决方案(如果不鼓励的话!)
【问题讨论】: