Hadoop Reducer自定义可写

时间:2017-10-21 22:57:23

标签: java apache hadoop mapreduce writable

我有以下Reducer类

public class CompanyMinMaxReducer extends Reducer<Text, DateClosePair, Text, Text> {
   private Text rText = new Text();

public void reduce(Text key, Iterable<DateClosePair> values, Context context)
          throws IOException, InterruptedException {

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
    LongWritable minDay = new LongWritable();
    LongWritable maxDay = new LongWritable();

for(DateClosePair val: values){
  LongWritable tempDate = val.getDate();
      DoubleWritable tempClose = val.getClose();

      if(tempDate.compareTo(maxDay) > 0){
        maxDay = tempDate;
      }else if(tempDate.compareTo(minDay) < 0){
        minDay = tempDate;
      }


      if(tempClose.get() > max){
        max = (int)tempClose.get();
      }else if(tempClose.get() < min){
        min = (int)tempClose.get();
      }
    }

String minDayFinal = "" + new SimpleDateFormat("yyyy").format(new Date(minDay.get()));
String maxDayFinal = "" + new SimpleDateFormat("yyyy").format(new Date(maxDay.get()));
    String output = minDayFinal + " - " + maxDayFinal + " MIN: " + min + " MAX: " + max;

    rText.set(output);
    context.write(key, rText);
}
}

我的数据集采用以下格式:

exchange, stock_symbol, date, stock_price_open,stock_price_high,stock_price_low, stock_price_close, stock_volume,stock_price_adj_close.

例如:

NASDAQ,AAPL,1970-10-22, ... 

我被要求编写一个新的MapReduce程序,该程序为每个公司提供它在股票市场中存在的年限,以及股票获得的最大和最小收盘价。

我的程序产生正确的输出,但由于某种原因,开始日期是恒定的:

AAON    1970 - 2002 MIN: 1 MAX: 35
AATI    1970 - 2010 MIN: 2 MAX: 15
ABCO    1970 - 2004 MIN: 14 MAX: 69
ABCW    1970 - 2007 MIN: 0 MAX: 53
ABII    1970 - 2008 MIN: 25 MAX: 78
ABIO    1970 - 1999 MIN: 0 MAX: 139
ABMC    1970 - 2004 MIN: 0 MAX: 6
ABTL    1970 - 2004 MIN: 0 MAX: 58
ACAD    1970 - 2009 MIN: 0 MAX: 17
ACAP    1970 - 2005 MIN: 15 MAX: 55
ACAT    1970 - 2009 MIN: 3 MAX: 29
ACCL    1970 - 1997 MIN: 3 MAX: 104
ACEL    1970 - 1998 MIN: 0 MAX: 10
ACET    1970 - 2004 MIN: 4 MAX: 27
ACFC    1970 - 2008 MIN: 1 MAX: 20
ACGL    1970 - 1997 MIN: 11 MAX: 80
ACLI    1970 - 2006 MIN: 2 MAX: 77
ACLS    1970 - 2001 MIN: 0 MAX: 30

DateClosePair是一个客户可写的我写的就像你在网上找到的每个例子一样。

min_closing价格和max_closing价格是正确的,但mix_date和max_date错误,这是很奇怪的。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

LongWritable minDay = new LongWritable()将您的最小日期变量初始化为1970.

更准确地说:除非给定特定值,否则LongWritable会根据java language spec将其内部long初始化为0。当它被送入java.util.Date时,它将被解释为来自Unix纪元的0毫秒:January 1, 1970, 00:00:00 UTC

我的猜测是1970年是数据集中所有日期值的下限。这会为每个键写它。

我注意到您使用int min = Integer.MAX_VALUE来初始化关闭值。也许您可以使用LongWritable minDay = LongWritable(Long.MAX_VALUE)来解决?

答案 1 :(得分:0)

我已经解决了由别名引起的问题。

而不是maxDay = tempDate;现在maxDay指向tempDate对象,我应该调用方法.set()

解决方案:

maxDay.set(tempDate.get());