【发布时间】:2011-10-17 16:59:18
【问题描述】:
我正在尝试使用 Hadoop 编写一个简单的 Map Reduce 程序,它将给出最容易患流感的月份。我正在使用谷歌流感趋势数据集,可以在这里找到http://www.google.org/flutrends/data.txt。
Mapper和reducer我都写了,如下图
public class MaxFluPerMonthMapper extends Mapper<LongWritable, Text, IntWritable, IntWritable> {
private static final Log LOG =
LogFactory.getLog(MaxFluPerMonthMapper.class);
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String row = value.toString();
LOG.debug("Received row " + row);
List<String> columns = Arrays.asList(row.split(","));
String date = columns.get(0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int month = 0;
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(date));
month = calendar.get(Calendar.MONTH);
} catch (ParseException e) {
e.printStackTrace();
}
for (int i = 1; i < columns.size(); i++) {
String fluIndex = columns.get(i);
if (StringUtils.isNotBlank(fluIndex) && StringUtils.isNumeric(fluIndex)) {
LOG.info("Writing key " + month + " and value " + fluIndex);
context.write(new IntWritable(month), new IntWritable(Integer.valueOf(fluIndex)));
}
}
}
}
减速器
public class MaxFluPerMonthReducer extends Reducer<IntWritable, IntWritable, Text, IntWritable> {
private static final Log LOG =
LogFactory.getLog(MaxFluPerMonthReducer.class);
@Override
protected void reduce(IntWritable key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
LOG.info("Received key " + key.get());
int sum = 0;
for (IntWritable intWritable : values) {
sum += intWritable.get();
}
int month = key.get();
String monthString = new DateFormatSymbols().getMonths()[month];
context.write(new Text(monthString), new IntWritable(sum));
}
}
使用上面显示的这些 Mapper 和 Reducer,我得到以下输出
一月 545419 二月 528022 三月 436348 4 月 336759 5 月 346482 六月 309795 七月 312966 八月 307346 九月 322359 十月 428346 十一月 461195 12 月 480078
我想要的只是一个输出给我 January 545419 我怎样才能做到这一点?通过将状态存储在减速器中还是有其他解决方案?或者我的 mapper 和 reducer 对于我在这个数据集上提出的问题是错误的?
【问题讨论】:
-
首先,使用组合器。其次,我认为实现这一点的一个 hacky 方法可能是使用 12 个 reducer。我不确定这是否总是有效。但是看看这个hadoop.apache.org/mapreduce/docs/r0.21.0/api/org/apache/hadoop/…