MapRedece中的分區Partitioner

來源:互聯網
上載者:User

MapRedece中的分區Partitioner
MapRedece中的分區Partitioner分析

MapReduce中會將map輸出的k-v對,按照相同的key進行分組,然後分發給不同的reduceTask中。
預設的分發規則為:根據key的hashcode%reducetask數來分發
所以如果要按照特定的需求進行分組,則需要改寫資料分發組件Partitioner。

實現
  1. 自訂資料分發類CustomPartitioner 繼承抽象類別Partitioner
  2. 重寫getPartition方法
getPartition方法說明

public int getPartition(Text key, LongWritable value, int numPartitions)

  • key : map階段輸出的key值
  • value : map階段輸出的value值
  • numPartitions : 設定的reduce數量(擷取的是job.setNumReduceTasks(int num)設定的num)
  • 傳回值是根據自訂規則得出的分區位置
案例需求

根據歸屬地輸出資料流量統計資料結果到不同檔案,以便於在查詢統計結果時可以定位到省級範圍進行流量統計。

實現
/*** 自訂分發規則類CustomPartitioner* @author:yanzhelee*/public class CustomPartitioner extends Partitioner<Text,LongWritable>{    //用於將手機號的前三個數字和分區塊進行對應    static HashMap<String, Integer> provinceMap = new HashMap<String, Integer>();    //設定預設的初始值    static {        //key為手機號的前三位元字,value為用於表示地區的分區號        provinceMap.put("135", 0);        provinceMap.put("136", 1);        provinceMap.put("137", 2);        provinceMap.put("138", 3);        provinceMap.put("139", 4);    }    @Override    public int getPartition(Text key, FlowBean value, int numPartitions) {        Integer code = provinceMap.get(key.toString().substring(0, 3));        //如果不存在,則分區號為5        return code == null ? 5 : code;    }}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.