hive 中排序order by,sort by,distribute by使用

前提:hive 中使用的排序有oder by, sort by,distribute By,cluster By
具体使用如下

1.order by :使用 order by 子句做全局排序,Hive分析数据底层的实现是MapReduce,
order by做全局排序,是通过只有一个reducer做到的

hive (default)> select * from emp order by sal desc;

2.sort By:sort by为每个reducer产生一个排序文件。每个Reducer内部进行排序,对全局结果集来说不是排序
对于大规模的数据集order by的效率非常低。在很多情况下,并不需要全局排序,此时可以使用sort by
简单来说就是分区内进行了排序

hive (default)> set mapreduce.job.reduces=3;
hive (default)> select * from emp sort by deptno desc;
hive (default)> insert overwrite local directory '/opt/module/datas/sortby-result' select * from emp sort by deptno desc;

3.distribute By: 在有些情况下,我们需要控制某个特定行应该到哪个reducer,通常是为了进行后续的聚集操作。distribute by 子句可以做这件事。distribute by类似MR中partition(自定义分区),进行分区,结合sort by使用。
简单来说就是:按照那个字段进行分区
对于distribute by进行测试,一定要分配多reduce进行处理,否则无法看到distribute by的效果。
案例实操:
先按照部门编号分区,每个分区内再按照员工编号降序排序。

hive (default)> set mapreduce.job.reduces=3;
hive (default)> insert overwrite local directory '/opt/module/datas/distribute-result' select * from emp distribute by deptno sort by empno desc;

注意:
1.distribute by的分区规则是根据分区字段的hash码与reduce的个数进行模除后,余数相同的分到一个区。
2.Hive要求DISTRIBUTE BY语句要写在SORT BY语句之前。

  1. cluster By
    当distribute by和sorts by字段相同时,可以使用cluster by方式。
    以下两种写法等价
hive (default)> select * from emp cluster by deptno;
hive (default)> select * from emp distribute by deptno sort by deptno;

注意:
cluster by除了具有distribute by的功能外还兼具sort by的功能。
但是排序只能是升序排序,不能指定排序规则为ASC或者DESC。

发布了53 篇原创文章 · 获赞 4 · 访问量 931

猜你喜欢

转载自blog.csdn.net/weixin_43548518/article/details/104087412