hive group by 導致的資料傾斜問題
阿新 • • 發佈:2021-08-04
Group By
預設情況下,Map階段同一Key資料分發給一個reduce,當一個key資料過大時就傾斜了。
但並不是所有的聚合操作都需要在Reduce端完成,很多聚合操作都可以先在Map端進行部分聚合,最後在Reduce端得出最終結果。
1)開啟Map端聚合引數設定
(1)是否在Map端進行聚合(預設為true)
set hive.auto.convert.join = true;
(2)在Map端進行聚合操作的條目數目
set hive.groupby.mapaggr.checkinterval = 100000
(3)有資料傾斜的時候進行負載均衡(預設是false)
set hive.groupby.skewindata = true
情況一:
select count(distinct member_no),trade_date from uiopdb.sx_trade_his_detail group by trade_date
優化後
select count(member_no),trade_date from ( select member_no,trade_date as trade_date from uiopdb.sx_trade_his_detail group by member_no,trade_date ) d group by trade_date
情況二:
但是對於很大的表,比如需要統計每個會員的總的交易額情況,採用上面的方法也不能跑出來
優化前的程式碼(交易表中有三千萬的資料)
set hive.groupby.skewindata = true; create table tmp_shop_trade_amt as select shop_no ,sum(txn_amt) as txn_amt from uiopdb.sx_trade_his_detail group by shop_no;
優化思路:如果某個key的資料量特別大,資料都集中到某一個reduce Task去進行相關資料的處理,這就導致了資料傾斜問題。
解決方案是首先採用區域性聚合,即給key加上100以內的隨機字首,進行一次預聚合,然後對本次預聚合後的結果進行去掉隨機字首,進行一次資料的全域性聚合。
優化後:
set hive.groupby.skewindata = true; create table tmp_shop_trade_amt_2 as select split(shop_no,'_')[1] as shop_no
,sum(txn_amt) total_txn_amt from
( select concat_ws("_", cast(ceiling(rand()*99) as string), shop_no) as shop_no
,sum(txn_amt) txn_amt from uiopdb.sx_trade_his_detail group by concat_ws("_", cast(ceiling(rand()*99) as string), shop_no) ) s group by split(shop_no,'_')[1] ;
執行結果