Hive高級查詢
- 查詢操作
- group by、Order by 、Join 、distribute by 、Sort by 、cluster by 、Union all
- 底層的實現(xiàn)
- Mapreducer
- 幾個簡單的聚合操作
- count 計數(shù)
- count(*) count(1) count(col)
- sum 求和
- sum(可轉(zhuǎn)成數(shù)字的值)返回bigint
- sum(col) + cast(1 as bigint)//必須進行類型轉(zhuǎn)換
- avg 求平均值
- avg(可轉(zhuǎn)成數(shù)字的值) 返回double
- distinct 不同值個數(shù)
- count(distinct col)
- count 計數(shù)
Order by
- 按照某些字段排序
- 樣例
- select col1,other...
- from table
- where condition
- oreder by col1,col2 [asc|desc]
- 注意
- order by 后面可以有多列進行排序,默認按字典排序
- order by 為全局排序
- order by 需要reduce操作,且只有一個reduce,與配置無
Group by
- 按照某些字段的值進行分組,有相同值放到一起
- 樣例
- select col1[,col2],count(1),sel_expr(聚合操作)
- from table where condition
- group by col1[,col2]
- [having...]
- 注意
- select后面非聚合列必須出現(xiàn)在group by中
- 除了普通列就是一些聚合操作
- group by后面也可以跟表達式,比如substr(col)
- 特性
- 使用了reduce操作,受限于reduce數(shù)量,設置reduce參數(shù)mapred.reduce.tasks
- 輸出文件個數(shù)與reduce數(shù)相同,文件大小與reduce處理的數(shù)據(jù)量有關
- 問題
- 網(wǎng)絡負載過重
- 數(shù)據(jù)傾斜,優(yōu)化參數(shù)hive.groupby.skewindata=true
Join
- 表連接
- 兩個表m,n之間按照on條件連接,m中的一條記錄和n中的一條記錄組成一條新的記錄
- join等值連接,只有某個值在m和n中同時存在時才輸出
- left outer join左外連接,左邊表中的值無論是否在b中存在時,都輸出,右邊表中的值只有在左邊表中存在時才輸出
- right outer join 和left outer join相反
- left semi join 類似exists
- mapjoin 在map端完成join操作,不需要用reduce,基于內(nèi)存做join,屬于優(yōu)化操作
- 樣例
- select m.col as col,m.col2 as col2,n.col3 as col3
- from(select col,col2 from test where...(map端執(zhí)行))m (左表)
- [left outer|right outer|left semi] join
- n (右表)
- on m.col=n.col
- where condition (reduce端執(zhí)行)
- set hive.optimize.skewjoin=true;
Mapjoin
- mapjoin(map side join)
- 在map端把小表加載到內(nèi)存中,然后讀取大表,和內(nèi)存中的小表完成連接操作
- 其中使用了分布式緩存技術(shù)
- 優(yōu)缺點
不消耗集群的reduce資源(reduce相對緊缺)
減少了reduce操作,加快程序執(zhí)行
降低網(wǎng)絡負載
占用部分內(nèi)存,所以加載到內(nèi)存中的表不能過大,因為每個計算節(jié)點都會加載一次
生成較多的小文件
- 配置以下參數(shù),是hive自動根據(jù)sql,選擇使用common join或者map join
- set hive.auto.convert.join=true;
- hive.mapjoin.smalltable.filesize默認值是25mb
- 第二種方式,手動指定
- select /*+mapjoin(n) */ m.col,m.col2,n.col3 from m
- join n
- on m.col=n.col
- 簡單總結(jié)一下,mapjoin的使用場景:
- 關聯(lián)操作中有一張表非常小
- 不等值的鏈接操作
DIstribute by 和 Sort by
- Distribute分散數(shù)據(jù)
- distribute by col
- 按照col列把數(shù)據(jù)分散到不同的reduce
- Sort排序
- sort by col2
- 按照col列把數(shù)據(jù)排序
- select col1,col2 from M
distribute by col1
sort by col1 asc,col2 desc; - 兩者結(jié)合出現(xiàn),確保每個reduce的輸出都是有序的
- distribute by 與group by 的對比
- 都是按key值劃分數(shù)據(jù)
- 都使用reduce操作
- 唯一不同,distribute by只是單純的分散數(shù)據(jù),而group by把相同key的數(shù)據(jù)聚集到一起,后續(xù)必須是聚合操作
- order by與sort by
- order by是全局排序
- sort by只是確保每個reduce上面輸出的數(shù)據(jù)有序,如果只有一個reduce時,和order by作用一樣
- 應用場景
- map輸出的文件大小不均
- reduce輸出文件大小不均
- 小文件過多
- 文件超大
Cluster by
- 把有相同值得數(shù)據(jù)聚集到一起,并排序
- 效果
- cluster by col
- 等同于distribute by col order by col
Union all
- 多個表的數(shù)據(jù)合并成一個表,hive不支持union
- 樣例
- select col
- form(
- select a as col from t1
- union all
- select b as col from t2
- )tmp
- 要求
- 字段名字一樣
- 字段類型一樣
- 字段個數(shù)一樣
- 子表不能有別名
- 如果需要從合并之后的表中查詢數(shù)據(jù),那么合并的表必須要有別名