已复制
全屏展示
复制代码

hive中order sort distribute cluster总结


· 2 min read

一. order by

order by是全局排序,因此只有一个Reducer,会导致当输入规模较大时,消耗较长的计算时间。

二. sort by

不是全局排序,其在数据进入reducer前完成局部排序,即它会在数据进入reduce之前为每个reducer都产生一个排序后的文件。sort by只保证每个reducer的输出有序,不保证全局有序。使用sort by你可以指定执行的reduce个数。对输出的数据再执行归并排序,即可得到全部结果。

使用sort by 和order by 快速获取top10

select salary from 
    (select salary from users sort by salary desc limit 10) tmp 
order by salary desc limit 10;


# 每个Reduce启动的任务数
set mapred.reduce.tasks=4;

# reducer 数量上线
set hive.exec.reducers.max=1009;

三. distribute by

sort by为每个reduce产生一个排序文件,distribute by控制某些特定的行应该到哪个reducer,所以distribute by经常和sort by配合使用。


select salary from users distribute by salary sort by salary desc limit 10

四. cluster by

当分区字段和排序字段相同时,cluster by可以简化distribute by 和 sort by 的SQL 写法,但是排序只能是升序排序,不能指定排序规则为ASC或者DESC。


select salary from users cluster by salary limit 10

五. 总结

  • order by 是全局排序,可能性能会比较差;
  • sort by 分区内有序,往往配合distribute by来确定该分区都有那些数据;
  • distribute by 确定了数据分发的规则,满足相同条件的数据被分发到一个reducer;
  • cluster by 当distribute by和sort by 字段相同时,可以使用cluster by 代替distribute by和sort by,但是cluster by默认是升序,不能指定排序方向;
  • sort by limit 相当于每个reduce 的数据limit 之后,进行order by 然后再limit;

文章推荐