实例:HiveSql数据倾斜处理

数据管道

共 1024字,需浏览 3分钟

 ·

2020-12-07 22:32

周末小短文:Sql如何处理热点key

|0x00 问题概述

在面试的时候,经常会问到一个问题:Hive在Join的时候,经常因为热点key的问题,导致数据倾斜,应该怎么解决?方法很简单,对导致倾斜的key做单独处理即可,最后再做union,那么Sql应该怎么写?

|0x01 常规处理

我们首先建一张临时表:

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

当然,我们还有办法提速吗?有的,是使用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 考虑空值

当然,大多数情况下,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
浏览 30
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报