Hive高級查詢
- 查詢操作
- group by、Order by 、Join 、distribute by 、Sort by 、cluster by 、Union all
- 底層的實現
- Mapreducer
- 幾個簡單的聚合操作
- count 計數
- count(*) count(1) count(col)
- sum 求和
- sum(可轉成數字的值)返回bigint
- sum(col) + cast(1 as bigint)//必須進行類型轉換
- avg 求平均值
- avg(可轉成數字的值) 返回double
- distinct 不同值個數
- count(distinct col)
- count 計數
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后面非聚合列必須出現在group by中
- 除了普通列就是一些聚合操作
- group by后面也可以跟表達式,比如substr(col)
- 特性
- 使用了reduce操作,受限于reduce數量,設置reduce參數mapred.reduce.tasks
- 輸出文件個數與reduce數相同,文件大小與reduce處理的數據量有關
- 問題
- 網絡負載過重
- 數據傾斜,優化參數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,基于內存做join,屬于優化操作
- 樣例
- select m.col as col,m.col2 as col2,n.col3 as col3
- from(select col,col2 from test where...(map端執行))m (左表)
- [left outer|right outer|left semi] join
- n (右表)
- on m.col=n.col
- where condition (reduce端執行)
- set hive.optimize.skewjoin=true;
Mapjoin
- mapjoin(map side join)
- 在map端把小表加載到內存中,然后讀取大表,和內存中的小表完成連接操作
- 其中使用了分布式緩存技術
- 優缺點
不消耗集群的reduce資源(reduce相對緊缺)
減少了reduce操作,加快程序執行
降低網絡負載
占用部分內存,所以加載到內存中的表不能過大,因為每個計算節點都會加載一次
生成較多的小文件
- 配置以下參數,是hive自動根據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
- 簡單總結一下,mapjoin的使用場景:
- 關聯操作中有一張表非常小
- 不等值的鏈接操作
DIstribute by 和 Sort by
- Distribute分散數據
- distribute by col
- 按照col列把數據分散到不同的reduce
- Sort排序
- sort by col2
- 按照col列把數據排序
- select col1,col2 from M
distribute by col1
sort by col1 asc,col2 desc; - 兩者結合出現,確保每個reduce的輸出都是有序的
- distribute by 與group by 的對比
- 都是按key值劃分數據
- 都使用reduce操作
- 唯一不同,distribute by只是單純的分散數據,而group by把相同key的數據聚集到一起,后續必須是聚合操作
- order by與sort by
- order by是全局排序
- sort by只是確保每個reduce上面輸出的數據有序,如果只有一個reduce時,和order by作用一樣
- 應用場景
- map輸出的文件大小不均
- reduce輸出文件大小不均
- 小文件過多
- 文件超大
Cluster by
- 把有相同值得數據聚集到一起,并排序
- 效果
- cluster by col
- 等同于distribute by col order by col
Union all
- 多個表的數據合并成一個表,hive不支持union
- 樣例
- select col
- form(
- select a as col from t1
- union all
- select b as col from t2
- )tmp
- 要求
- 字段名字一樣
- 字段類型一樣
- 字段個數一樣
- 子表不能有別名
- 如果需要從合并之后的表中查詢數據,那么合并的表必須要有別名