Hive是將符合SQL語法的字符串解析生成可以在Hadoop上執行的MapReduce的工具。使用Hive儘量按照分佈式計算的一些特點來設計sql,和傳統關係型數據庫有區別,
所以需要去掉原有關係型數據庫下開發的一些固有思維。
基本原則:
1:儘量儘早地過濾數據,減少每個階段的數據量,對於分區表要加分區,同時只選擇需要使用到的字段
select … from A
join B
on A.key = B.key
where A.userid>10
and B.userid<10
and A.dt='20120417'
and B.dt='20120417';
應該改寫爲:
select … from (select … from A
where dt='201200417'
and userid>10
) a
join ( select … from B
where dt='201200417'
and userid < 10
) b
on a.key = b.key;
2、對歷史庫的計算經驗 (這項是說根據不同的使用目的優化使用方法)
歷史庫計算和使用,分區
3:儘量原子化操作,儘量避免一個SQL包含複雜邏輯
可以使用中間表來完成複雜的邏輯
4 jion操作 小表要注意放在join的左邊(目前TCL裏面很多都小表放在join的右邊)。
否則會引起磁盤和內存的大量消耗
5:如果union all的部分個數大於2,或者每個union部分數據量大,應該拆成多個insert into 語句,實際測試過程中,執行時間能提升50%
insert overwite table tablename partition (dt= ....)
select ..... from (
select ... from A
union all
select ... from B
union all
select ... from C
) R
where ...;
可以改寫爲:
insert into table tablename partition (dt= ....)
select .... from A
WHERE ...;
insert into table tablename partition (dt= ....)
select .... from B
WHERE ...;
insert into table tablename partition (dt= ....)
select .... from C
WHERE ...;