【Hive】MapReduce 如何实现 Hive SQL 的基本操作-where

Hive SQL 语法本质上分为 3 类:过滤模式、聚合模式、连接模式。

    过滤模式:例如 where、having 等; 聚合模式:存在 Shuffle 过程,需要特别注意; 连接模式:分为有 Shuffle 连接和无 Shuffle 连接。

1.过滤模式

1.1 where 子句过滤

例:

select *
from stu_tb
where age=19 and name like %红% and score_in (100, 50, 22);

where 的过滤操作发生在 Map 阶段。计算逻辑发送到数据所在的所有机器中执行,实现并行计算,过滤掉大量数据。减少了跨机器网络传输到 Reducer 端的数据量。

MR 伪代码:

map(inkey, invalue, context):
	# 输入在 MR 看来只是字符串
	colsArray = invalue.split("	")
    age = colsArray[3]
	name = colsArray[2]
	score = colsArray[5]
    
	# 不满足条件就抛弃整行数据
	if age != 19:
		return
	if name.indexOf("红") == -1:
		return
	if score != 100 or score != 50 or score != 22:
		return
	
    # 符和条件的数据输出
	context.write(null, age+	+name+	+score)
    
    
reduce(inkey, invalue, context):
    # 略

启示:尽早用 where 过滤掉不必要的数据,提高作业性能。例如:

select count(age)
from (
	select age, count(1) num
    from stu_tb
    group by age
)
where age < 30 and num > 20;

-- 改为如下方式
select count(age)
from (
	select age, count(1) num
    from stu_tb
    where age < 30
    group by age
    having num > 20
);

下一次介绍 having。

经验分享 程序员 微信小程序 职场和发展