實例:HiveSql數(shù)據(jù)傾斜處理
周末小短文:Sql如何處理熱點key
|0x00 問題概述
在面試的時候,經(jīng)常會問到一個問題:Hive在Join的時候,經(jīng)常因為熱點key的問題,導(dǎo)致數(shù)據(jù)傾斜,應(yīng)該怎么解決?方法很簡單,對導(dǎo)致傾斜的key做單獨處理即可,最后再做union,那么Sql應(yīng)該怎么寫?
|0x01 常規(guī)處理
我們首先建一張臨時表:
insert?overwrite?table?tmp_0
select?hot_key
from?(
????select???hot_key
?????????????,count(1)?as?cnt
????from?????table_0
????where????dt?=?'20201206'
????group?by?hot_key
)?a
where????cnt?>=?10000
;
然后將熱點的key單獨組裝一段sql:
select?*
from? table_1?a
join?? tmp_0?b
on??? a.key?=?b.hot_key
;
最后處理非熱點key:
select?*
from??table_1?a
left?join?tmp_0?b
on?????a.key?=?b.hot_key
where??b.hot_key?is?null
;
|0x02 考慮mapjoin
當(dāng)然,我們還有辦法提速嗎?有的,是使用mapjoin,參考下面的寫法:
select?/*+mapjoin(b)*/
?????? b.*
from???tmp_0?a?
right?join?table_1?b
on???? a.hot_key?=?b.key
where??a.hot_key?is?null
;
|0xFF 考慮空值
當(dāng)然,大多數(shù)情況下,key都是有空值情況存在的,我們需要對空值做特殊處理,以上一段sql為例:
select??/*+mapjoin(b1)*/
?????? b.*
from????tmp_0?a?
right?join?table_1?b
on???? a.hot_key?=?coalesce(b.key,?concat('other',?rand()))
where?? a.hot_key?is?null評論
圖片
表情
