欢迎点击此处关注公众号。
1.3 distinct
前面提到 Hive SQL 语法本质上分为 3 类:过滤模式、聚合模式、连接模式。
- 过滤模式:例如 where、having 等;
- 聚合模式:存在 Shuffle 过程,需要特别注意;
- 连接模式:分为有 Shuffle 连接和无 Shuffle 连接。
而 distinct 兼具过滤和聚合的功能。
1.3.1 distinct 过滤
distinct 用于列投影中过滤重复的数据,在 Hive 中发生在 Reduce 阶段。在 Hive 中,下面两个 SQL 等价:
select distinct age
from stu_tb;
select age
from stu_tb
group by age;
1.3.2 distinct 聚合
如果在 Hive 中开启了 hive.map.aggr=true
配置,那么使用 distinct 子句会在前面的流程中进行数据聚合,减少流转到下游的数据量。下面的例子开启了 Map 端聚合:
set hive.map.aggr=true;
select distinct score
from stu_tb;
在 Map 阶段,进行数据局部聚合,在 Reduce 阶段进行数据全局聚合。MR 伪代码如下:
map(inkey, invalue, context):
colsArray = invalue.split("\t")
score = colsArray[5]
# MR 引擎会将相同 key,即相同的 score 的值发送到同一个 combine/reduce 中处理
context.write(score, null)
combine(inkey, invalues, context):
# 抛弃 invalues,只输出 key,完成 局部 聚合
context.write(inkey)
reduce(inkey, invalues, context):
# 抛弃 invalues,只输出 key,完成 全局 聚合
context.write(inkey)