數(shù)據(jù)算法 Hadoop/Spark大數(shù)據(jù)處理---第二章

在上一章中,我們實(shí)現(xiàn)的雖然是二次排序,但是排序的value是String或Integer,但是假如換一下,把value換成元組,也即是本章所給的例子:LIMM,2013-12-05,97.65 ,KKIA,2014-15-05,107.65等。


在Hadoop中,在map輸出的時(shí)候,會(huì)進(jìn)行分區(qū),在區(qū)內(nèi)再對(duì)key進(jìn)行排序,分區(qū)的作用就是確定哪一些內(nèi)容發(fā)到那個(gè)reduce,區(qū)內(nèi)排序則是為reduce的排序做好基礎(chǔ)


因此在本章中,也將先設(shè)置分區(qū),確定哪些相同的key發(fā)送到那些區(qū)中,然后在區(qū)中在對(duì)key進(jìn)行排序(因?yàn)閞educe需要),做好在進(jìn)行組內(nèi)排序。從輸入轉(zhuǎn)換成(key,a1)(a1,{a2,a3……})這樣的格式


類名 描述
CompositeKey 定義一個(gè)組合鍵
NaturalValue 定義一個(gè)自然鍵
NaturalKeyPartitioner 定義自然鍵分區(qū)
NaturalKeyGroupingComparator 定義自然鍵如何分組
CompositeKeyComparator 定義區(qū)內(nèi)組合鍵排序
SecondarySortDriver 主程序入口類
SecondarySortMapper Map函數(shù)
SecondarySortReducer Reduce函數(shù)

1.SecondarySortDriver.java

 Configuration conf = new Configuration();
        Job job = new Job(conf, "Secondary Sort");

        // add jars to distributed cache
        HadoopUtil.addJarsToDistributedCache(conf, "/lib/");
        
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length != 2) {
           System.err.println("Usage: SecondarySortDriver <input> <output>");
           System.exit(1);
        }        
       
        job.setJarByClass(SecondarySortDriver.class);
        job.setJarByClass(SecondarySortMapper.class);
        job.setJarByClass(SecondarySortReducer.class);
        
       // set mapper and reducer
        job.setMapperClass(SecondarySortMapper.class);
        job.setReducerClass(SecondarySortReducer.class);
        
        // 定義了自然鍵和組合鍵的bean
        job.setMapOutputKeyClass(CompositeKey.class);
        job.setMapOutputValueClass(NaturalValue.class);
              
        // define reducer's output key-value
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        //定義自然鍵的分區(qū)
        job.setPartitionerClass(NaturalKeyPartitioner.class);
        //定義分區(qū)內(nèi)自然鍵的排序
        job.setGroupingComparatorClass(NaturalKeyGroupingComparator.class);
        //定義組合鍵的排序
        job.setSortComparatorClass(CompositeKeyComparator.class);
        
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));

        job.waitForCompletion(true);

2.CompositeKey.java

//自然鍵是stockSymbol,組合鍵是{stockSymbol,timestamp}
private String stockSymbol;
private long timestamp;

3.NaturalValue.java

    //定義新組合的自然鍵{時(shí)間戳,價(jià)格}
    private long timestamp;
    private double price;

4.NaturalKeyPartitioner.java

//根據(jù)相同的StockSymbol的hash值分配分區(qū)
@Override
    public int getPartition(CompositeKey key, 
                            NaturalValue value,
                            int numberOfPartitions) {
        return Math.abs((int) (hash(key.getStockSymbol()) % numberOfPartitions));
    }

5.NaturalKeyGroupingComparator.java

//對(duì)分區(qū)內(nèi)的鍵進(jìn)行排序,因?yàn)閞educe需要
@Override
    public int compare(WritableComparable wc1, WritableComparable wc2) {
        CompositeKey ck1 = (CompositeKey) wc1;
        CompositeKey ck2 = (CompositeKey) wc2;
        return ck1.getStockSymbol().compareTo(ck2.getStockSymbol());
    }

6.CompositeKeyComparator.java

//定義組合鍵的排序方法
  @Override
    public int compare(WritableComparable wc1, WritableComparable wc2) {
        CompositeKey ck1 = (CompositeKey) wc1;
        CompositeKey ck2 = (CompositeKey) wc2;

        int comparison = ck1.getStockSymbol().compareTo(ck2.getStockSymbol());
        //當(dāng)兩個(gè)鍵的值相同的時(shí)候才比較時(shí)間戳
        if (comparison == 0) {
            // stock symbols are equal here
            if (ck1.getTimestamp() == ck2.getTimestamp()) {
                return 0;
            }
            else if (ck1.getTimestamp() < ck2.getTimestamp()) {
                return -1;
            }
            else {
                return 1;
            }
        }
        else {
            return comparison;
        }
    }

7.SecondarySortMapper.java

    //定義兩個(gè)自然鍵
   private final CompositeKey reducerKey = new CompositeKey();
   private final NaturalValue reducerValue = new NaturalValue();
       
    
    @Override
    public void map(LongWritable key, 
                    Text value,
                    Context context) 
       throws IOException, InterruptedException {
               
       String[] tokens = StringUtils.split(value.toString().trim(), ",");
       if (tokens.length == 3) {
          // tokens[0] = stokSymbol
          // tokens[1] = timestamp (as date)
          // tokens[2] = price as double
          Date date = DateUtil.getDate(tokens[1]);
          if (date == null) {
             return;
          }
          long timestamp = date.getTime();
          //設(shè)置自然鍵和組合鍵
          reducerKey.set(tokens[0], timestamp); 
          reducerValue.set(timestamp, Double.parseDouble(tokens[2]));
          // emit key-value pair
          context.write(reducerKey, reducerValue);
       }

8.SecondarySortReducer.java

//reduce類
public void reduce(CompositeKey key, 
                       Iterable<NaturalValue> values,
                       Context context)
       throws IOException, InterruptedException {

        //用builder對(duì)value進(jìn)行包裝,已經(jīng)是排序好的了
        StringBuilder builder = new StringBuilder();
        for (NaturalValue data : values) {
             builder.append("(");
             String dateAsString = DateUtil.getDateAsString(data.getTimestamp());
             double price = data.getPrice();
             builder.append(dateAsString);
             builder.append(",");
             builder.append(price);          
             builder.append(")");
        }
        //取key和保存好的{values},然后保存到在SecondarySortDriver中設(shè)置的輸出目錄
        context.write(new Text(key.getStockSymbol()), new Text(builder.toString()));
    } // reduce

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 引子 任何一個(gè)概念的引入都是為了解決某種問題,RDD亦然。關(guān)于RDD這個(gè)概念,先拋幾個(gè)問題。 為什么引入RDD這個(gè)...
    陸云子安閱讀 2,084評(píng)論 1 7
  • 3.2 彈性分布式數(shù)據(jù)集 本節(jié)簡(jiǎn)單介紹RDD,并介紹RDD與分布式共享內(nèi)存的異同。 3.2.1 RDD簡(jiǎn)介 在集群...
    Albert陳凱閱讀 1,701評(píng)論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評(píng)論 19 139
  • 趁著國(guó)慶去探訪了漓江岸邊的船上人家 第一次看見有人用船做房子,而且?guī)缀踉诖仙盍艘惠呑?,這是我這個(gè)平原人永遠(yuǎn)想象...
    嘿小時(shí)光閱讀 2,169評(píng)論 0 2
  • ? 在中國(guó),女孩真正意義上的獨(dú)立,不是18歲而是25歲。 25歲,在這最鼎盛的年紀(jì),你談過一場(chǎng)無(wú)關(guān)金錢和物質(zhì)的戀愛...
    丸子日跡閱讀 269評(píng)論 2 3

友情鏈接更多精彩內(nèi)容