Hive的排序——order by 、sort by、distribute by 、cluster by

Hive中的排序通常涉及到order by 、sort by、distribute by 、cluster by

一、语法

sql 复制代码
select
        column1,
        column2, ...
from table 
[where 条件] 
[group by column]
[order by column] 
[cluster by column| [distribute by column] [sort by column] 
[limit [offset,] rows];

二、排序介绍

2.1 order by

Hive的order by 与其他的sql一样,对所有数据进行排序, 即:全局排序,只有一个 Reducer。 在严格模式(set hive.mapred.mode=strict)下,执行order by 必须加上**limit 子句,避免数据集行数过大。**order by 字段 ,默认是升序。

2.2 distribute by和sort by

针对order by的缺点,Hive提供了distribute by 分区和sort by 排序 。例如: select * from user_info distribute by user_id sort by login_date desc;

  • distribute by

shuffle阶段,基于key值,可以控制数据发往具体某个分区 ,相同key的数据会分发到同一个reduceTask中。

distribute by 类似 MR****中的自定义分区 partition,distribute by 的分区规则是:分区字段的****hashcode值对reduce 个数取模后, 余数相同的数据会分发到同一个reduceTask中。

  • sort by

指定sort by后,可以在每个reducer端做排序,即可以保证局部有序(每个reducer出来的数据是有序的,但是不能保证所有的数据是有序的,除非只有一个reducer)。

指定sort by好处是:执行了局部排序之后可以为接下去的全局排序提高不少的效率。

2.3 cluster by

当 distribute by 和 sorts by 字段相同时,可以使用 cluster by 方式。 但是排序 只能是升序
排序, 不能指定排序规则为 acs 或者 desc 。

sql 复制代码
select *  from user_info distribute by user_id sort by user_id;
--等价于
select *  from user_info cluster by user_id;

三、总结

  • order by全局排序,只有一个reducer,结果输出在一个文件中,当数据量较大时,需要较长的计算时间;
  • distribute by根据指定字段将数据分组,分组编号 = 【字段的hashcode 】% 【reduce数】,sort by是在分组之后,每个组内局部排序,即保障了每个reducer端的数据有序;
  • cluster by既有分组,又有排序,前提是分组与排序字段相同,当distribute和sort的字段是同一个时,cluster by = distribute by + sort by
相关推荐
geovindu20 小时前
SQL Data Sampling and Approximation Techniques using postgreSQL 18
大数据·数据库·数据仓库·sql·postgresql·数据库开发·数据库架构
skywalk81631 天前
hive —— 多机 AI Agent 协同的任务总线:分布式,多节点同时运行,保障不会宕机
人工智能·hive·分布式
程序员梅雨2 天前
【从零开始学习数据仓库 | 第一篇】:维度建模理论
大数据·数据仓库·学习·阿里云·数据分析
棣廷2 天前
初识数据仓库——数仓分层到DataX数据采集
数据仓库
棣廷2 天前
初识Hive(2)
数据仓库·hive·hadoop
skywalk81632 天前
deepseek对skywalk163/hive 和hivecommons/hive 两个多机AI Agent任务调度项目的对比
人工智能·hive·agent
father_12273 天前
【ambari管理下hdp2.6.5升级hive1.2.1-2.1.0-2.3.3】
hive·hadoop·ambari
geovindu3 天前
Pivoting and Unpivoting Data in SQL using postgreSQL 18
大数据·数据库·数据仓库·sql·postgresql·数据库开发·数据库架构
数据库小学妹3 天前
OLAP数据库怎么选?看清OLTP、数仓、湖仓边界
数据仓库·mpp·列式存储·联机分析处理·数据库选型·olap数据库