Hive查詢 分桶表 常用函數 自定義函數:
查詢語法
1 2 3 4 5 6 7 8 9 10 11
[WITH CommonTableExpression (, CommonTableExpression)*] (Note: Only available starting with Hive 0.13 .0 ) SELECT [ALL | DISTINCT ] select_expr, select_expr, ... FROM table_reference [WHERE where_condition] [GROUP BY col_list] [ORDER BY col_list] [CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list] ] [LIMIT number ]
參考文檔
基本查詢
全表查詢
條件查詢
1
select empno, ename from emp;
注意:
SQL 語言大小寫不敏感。
SQL 可以寫在一行或者多行
關鍵字不能被縮寫也不能分行
各子句一般要分行寫。
使用縮進提高語句的可讀性。
列別名
重命名一個列
便於計算
緊跟列名,也可以在列名和別名之間加入關鍵字‘AS’
1 2
hive > select ename AS name, deptno dn from emp;
算術運算符
運算符
描述
A+B
A和B 相加
A-B
A減去B
A*B
A和B 相乘
A/B
A除以B
A%B
A對B取餘
A&B
A和B按位取與
A\
B
A和B按位取或
A^B
A和B按位取異或
~A
A按位取反
1 2
select ename,sal +100 from emp;
常用函數
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
select count (*) cnt from emp;select max (sal) max_sal from emp;select min (sal) min_sal from emp;select sum (sal) sum_sal from emp; select sum (sal) sum_sal from emp; select * from emp limit 5 ;
Where語句
1.使用WHERE子句,將不滿足條件的行過濾掉
2.WHERE子句緊隨FROM子句
1 2
select * from emp where sal >1000 ;
比較運算符
操作符
支持的數據類型
描述
A=B
基本數據類型
如果A等於B則返回TRUE,反之返回FALSE
A<=>B
基本數據類型
如果A和B都爲NULL,則返回TRUE,其他的和等號(=)操作符的結果一致,如果任一爲NULL則結果爲NULL
A<>B, A!=B
基本數據類型
A或者B爲NULL則返回NULL;如果A不等於B,則返回TRUE,反之返回FALSE
A<B
基本數據類型
A或者B爲NULL,則返回NULL;如果A小於B,則返回TRUE,反之返回FALSE
A<=B
基本數據類型
A或者B爲NULL,則返回NULL;如果A小於等於B,則返回TRUE,反之返回FALSE
A>B
基本數據類型
A或者B爲NULL,則返回NULL;如果A大於B,則返回TRUE,反之返回FALSE
A>=B
基本數據類型
A或者B爲NULL,則返回NULL;如果A大於等於B,則返回TRUE,反之返回FALSE
A [NOT] BETWEEN B AND C
基本數據類型
如果A,B或者C任一爲NULL,則結果爲NULL。如果A的值大於等於B而且小於或等於C,則結果爲TRUE,反之爲FALSE。如果使用NOT關鍵字則可達到相反的效果。
A IS NULL
所有數據類型
如果A等於NULL,則返回TRUE,反之返回FALSE
A IS NOT NULL
所有數據類型
如果A不等於NULL,則返回TRUE,反之返回FALSE
IN(數值1, 數值2)
所有數據類型
使用 IN運算顯示列表中的值
A [NOT] LIKE B
STRING 類型
B是一個SQL下的簡單正則表達式,如果A與其匹配的話,則返回TRUE;反之返回FALSE。B的表達式說明如下:‘x%’表示A必須以字母‘x’開頭,‘%x’表示A必須以字母’x’結尾,而‘%x%’表示A包含有字母’x’,可以位於開頭,結尾或者字符串中間。如果使用NOT關鍵字則可達到相反的效果。
A RLIKE B, A REGEXP B
STRING 類型
B是一個正則表達式,如果A與其匹配,則返回TRUE;反之返回FALSE。匹配使用的是JDK中的正則表達式接口實現的,因爲正則也依據其中的規則。例如,正則表達式必須和整個字符串A相匹配,而不是隻需與其字符串匹配。
1 2 3 4 5 6 7 8 9 10 11 12
select * from emp where sal =5000 ; select * from emp where sal between 500 and 10000 ; select * from emp where comm is null ; select * from emp where sal in (1500 ,5000 );select * from emp where sal=1500 or sal= 5000 ;
Like和RLike
使用LIKE運算選擇類似的值
選擇條件可以包含字符或數字:% 代表零個或多個字符(任意個字符)。_ 代表一個字符。
RLIKE子句是Hive中這個功能的一個擴展,其可以通過Java的正則表達式這個更強大的語言來指定匹配條件。
1 2 3 4 5 6
select * from emp where sal LIKE '2%' ; select * from emp where sal LIKE '_2%' ;select * from emp where sal RLIKE '[2]' ;
邏輯運算符
操作符
含義
AND
邏輯並
OR
邏輯或
NOT
邏輯否
1 2 3 4
select deptno, avg (sal) from emp group by deptno;select deptno, avg (sal) avg_sal from emp group by deptno having avg_sal > 2000 ;
Join語句
等值Join
注意:Hive支持通常的SQL JOIN語句,但 只支持等值連接,不支持非等值連接 。
1 2 3 4
select e.empno, e.ename, d.deptno, d.dname from emp e join dept d on e.deptno = d.deptno; select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno = d.deptno;
表的別名:(1)使用別名可以簡化查詢。(2)使用表名前綴可以提高執行效率。
左外連接
左外連接:JOIN操作符左邊表中符合WHERE子句的所有記錄將會被返回。
1
select e.empno, e.ename, d.deptno from emp e left join dept d on e.deptno = d.deptno;
右外連接
右外連接:JOIN操作符右邊表中符合WHERE子句的所有記錄將會被返回。
1
select e.empno, e.ename, d.deptno from emp e right join dept d on e.deptno = d.deptno;
滿外連接
滿外連接:將會返回所有表中符合WHERE語句條件的所有記錄。如果任一表的指定字段沒有符合條件的值的話,那麼就使用NULL值替代。
1
select e.empno, e.ename, d.deptno from emp e full join dept d on e.deptno = d.deptno;
多表連接
數據準備
創建位置表
1 2 3 4 5
create table if not exists default.location(loc int , loc_name string ) row format delimited fields terminated by '\t' ;
導入數據
1
load data local inpath '/opt/module/datas/location.txt' into table default.location;
多表連接查詢
1 2 3 4 5 6
SELECT e.ename, d.deptno, l. loc_nameFROM emp e JOIN dept dON d.deptno = e.deptno JOIN location lON d.loc = l.loc;
注意:大多數情況下,Hive會對每對JOIN連接對象啓動一個MapReduce任務。本例中會首先啓動一個MapReduce job對錶e和表d進行連接操作,然後會再啓動一個MapReduce job將第一個MapReduce job的輸出和表l;進行連接操作。Hive總是按照從左到右的順序執行的。因此不是Hive總是按照從左到右的順序執行的。
笛卡爾積
笛卡爾集會在下面條件下產生:
省略連接條件
連接條件無效
所有表中的所有行互相連接
1 2 3 4 5
select empno, dname from emp, dept; select e.empno, e.ename, d.deptno from emp e join dept d on e.deptno= d.deptno or e.ename=d.ename;
排序
全局排序
Order By:全局排序,一個Reducer
1.使用 ORDER BY 子句排序 ASC(ascend): 升序(默認) DESC(descend): 降序
ORDER BY 子句在SELECT語句的結尾
1 2 3 4
hive (default)> select * from emp order by sal; select * from emp order by sal desc ;
按照別名排序
1 2 3 4
select ename, sal*2 twosal from emp order by twosal;select ename, deptno, sal from emp order by deptno, sal;
MR內部排序(Sort By)
Sort By:每個Reducer內部進行排序,對全局結果集來說不是排序。
1 2 3 4 5 6 7 8 9 10 11
set mapreduce.job.reduces=3 ;set mapreduce.job.reduces;select empno,ename,sal,deptno from emp sort by empno desc ;select empno,ename,sal,deptno from emp sort by deptno desc ;
分區排序 (Distribute By)
Distribute By:類似MR中partition,進行分區,結合sort by使用。
注意:Hive要求DISTRIBUTE BY語句要寫在SORT BY語句之前。對於distribute by進行測試,一定要分配多reduce進行處理,否則無法看到distribute by的效果。
案例實操:
1 2 3
set mapreduce.job.reduces=3 ; select * from emp distribute by deptno sort by empno desc ;
Cluster By
當distribute by和sorts by字段相同時,可以使用cluster by方式。
cluster by除了具有distribute by的功能外還兼具sort by的功能。但是排序只能是倒序排序,不能指定排序規則爲ASC或者DESC。
1 2
select * from emp cluster by deptno;select * from emp distribute by deptno sort by deptno;
桶表
分區針對的是數據的存儲路徑;分桶針對的是數據文件。
分區提供一個隔離數據和優化查詢的便利方式。不過,並非所有的數據集都可形成合理的分區,特別是之前所提到過的要確定合適的劃分大小這個疑慮。 分桶是將數據集分解成更容易管理的若干部分的另一個技術。
1 2 3 4 5 6 7 8 9
create table stu_buck(id int , name string )clustered by (id ) into 4 bucketsrow format delimited fields terminated by '\t' ;Num Buckets: 4 load data local inpath '/opt/module/datas/student.txt' into table stu_buck;
查看創建的分桶表
1 2 3 4 5 6 7 8 9 10 11 12
create table stu(id int , name string )row format delimited fields terminated by '\t' ;load data local inpath '/opt/module/datas/student.txt' into table stu;truncate table stu_buck;insert into table stu_buck select id , name from stu;
1 2
insert into table stu_buck select id , name from stu;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
hive> select * from stu_buck; OK 1016 ss16 1012 ss12 1008 ss8 1004 ss4 1009 ss9 1005 ss5 1001 ss1 1013 ss13 1010 ss10 1002 ss2 1006 ss6 1014 ss14 1003 ss3 1011 ss11 1007 ss7 1015 ss15 Time taken: 0.091 seconds, Fetched: 16 row(s)
分桶抽樣查詢
對於非常大的數據集,有時用戶需要使用的是一個具有代表性的查詢結果而不是全部結果。Hive可以通過對錶進行抽樣來滿足這個需求。
查詢表stu_buck中的數據 select * from 表名 tablesample(bucket x out of y on id);
y必須是table總bucket數的倍數或者因子。hive根據y的大小,決定抽樣的比例。例如,table總共分了4份,當y=2時,抽取(4/2=)2個bucket的數據,當y=8時,抽取(4/8=)1/2個bucket的數據。
x表示從哪個bucket開始抽取,如果需要取多個分區,以後的分區號爲當前分區號加上y。例如,table總bucket數爲4,tablesample(bucket 1 out of 2),表示總共抽取(4/2=)2個bucket的數據,抽取第1(x)個和第4(x+y)個bucket的數據。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
hive> select * from stu_buck tablesample(bucket 1 out of 4 on id); OK 1016 ss16 1012 ss12 1008 ss8 1004 ss4 hive> select * from stu_buck tablesample(bucket 1 out of 8 on id); OK 1016 ss16 1008 ss8 hive> select * from stu_buck tablesample(bucket 6 out of 3 on id); FAILED: SemanticException [Error 10061]: Numerator should not be bigger than denominator in sample clause for table stu_buck
其他常用查詢函數
空字段賦值
NVL:給值爲NULL的數據賦值,它的格式是NVL( string1,replace_with)。它的功能是如果string1爲NULL,則NVL函數返回replace_with的值,否則返回string1的值,如果兩個參數都爲NULL ,則返回NULL。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
hive> select ename, deptno, sal, nvl(comm,'無') from emp; OK SMITH 20 800.0 無 ALLEN 30 1600.0 300.0 WARD 30 1250.0 500.0 JONES 20 2975.0 無 MARTIN 30 1250.0 1400.0 BLAKE 30 2850.0 無 CLARK 10 2450.0 無 SCOTT 20 3000.0 無 KING 10 5000.0 無 TURNER 30 1500.0 0.0 ADAMS 20 1100.0 無 JAMES 30 950.0 無 FORD 20 3000.0 無 MILLER 10 1300.0 無
CASE WHEN
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
[[email protected] datas]$ vim emp_sex.txt 悟空 A 男 八戒 A 男 沙和尚 B 男 唐僧 A 女 白龍馬 B 女 白骨精 B 女 create table person_info(name string , constellation string , blood_type string ) row format delimited fields terminated by "\t" ;select t1.c_b, CONCAT_WS ("|" ,COLLECT_SET(t1.name)) from ( select CONCAT_WS ("," ,constellation,blood_type) c_b, name from person_info) t1 group by t1.c_b; dept_id male female A 2 1 B 1 2
行轉列
CONCAT(string A/col, string B/col…):返回輸入字符串連接後的結果,支持任意個輸入字符串;
CONCAT_WS(separator, str1, str2,…):它是一個特殊形式的 CONCAT()。第一個參數剩餘參數間的分隔符。分隔符可以是與剩餘參數一樣的字符串。如果分隔符是 NULL,返回值也將爲 NULL。這個函數會跳過分隔符參數後的任何 NULL 和空字符串。分隔符將被加到被連接的字符串之間;
COLLECT_SET(col):函數只接受基本數據類型,它的主要作用是將某字段的值進行去重彙總,產生array類型字段。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
[[email protected] datas]$ vim person_info.txt 孫悟空 白羊座 A 唐僧 射手座 A 沙和尚 白羊座 B 豬八戒 白羊座 A 白龍馬 射手座 A create table person_info(name string , constellation string , blood_type string ) row format delimited fields terminated by "\t" ;load data local inpath "/opt/module/datas/ constellation.txt" into table person_info;select t1.base, concat_ws ('|' , collect_set(t1.name)) name from (select name , concat (constellation, "," , blood_type) base from person_info) t1 group by t1.base; 射手座,A 唐僧|白龍馬 白羊座,A 孫悟空|豬八戒 白羊座,B 沙和尚
列轉行
EXPLODE(col):將hive一列中複雜的array或者map結構拆分成多行。
LATERAL VIEW用法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias
解釋:用於和split, explode等UDTF一起使用,它能夠將一列數據拆成多行數據,在此基礎上可以對拆分後的數據進行聚合。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
[[email protected] datas]$ vim movie.txt 《疑犯追蹤》 懸疑,動作,科幻,劇情 《Lie to me》 懸疑,警匪,動作,心理,劇情 《戰狼2》 戰爭,動作,災難 create table movie_info( movie string , category array <string >) row format delimited fields terminated by "\t" collection items terminated by "," ; select movie,category_namefrom movie_infoLATERAL VIEW EXPLODE (category ) tmpTable as category_name;movie category_name 《疑犯追蹤》 懸疑 《疑犯追蹤》 動作 《疑犯追蹤》 科幻 《疑犯追蹤》 劇情 《Lie to me》 懸疑 《Lie to me》 警匪 《Lie to me》 動作 《Lie to me》 心理 《Lie to me》 劇情 《戰狼2》 戰爭 《戰狼2》 動作 《戰狼2》 災難
窗口函數
函數
功能
OVER()
指定分析函數工作的數據窗口大小,這個數據窗口大小可能會隨着行的變而變化
CURRENT ROW
當前行
n PRECEDING
往前n行數據
n FOLLOWING
往後n行數據
UNBOUNDED
起點,UNBOUNDED PRECEDING 表示從前面的起點, UNBOUNDED FOLLOWING表示到後面的終點
LAG(col,n)
往前第n行數據
LEAD(col,n)
往後第n行數據
NTILE(n)
把有序分區中的行分發到指定數據的組中,各個組有編號,編號從1開始:n必須爲int類型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
[[email protected] datas]$ vim business.txt jack,2018-01-01,10 tony,2018-01-02,15 jack,2018-02-03,23 tony,2018-01-04,29 jack,2018-01-05,46 jack,2018-04-06,42 tony,2018-01-07,50 jack,2018-01-08,55 mart,2018-04-08,62 mart,2018-04-09,68 neil,2018-05-10,12 mart,2018-04-11,75 neil,2018-06-12,80 mart,2018-04-13,94 create table business(name string , orderdate string , cost int ) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' ; load data local inpath "/opt/module/datas/business.txt" into table business;select name ,count (*) over () from business where substring (orderdate,1 ,7 ) = '2018-04' group by name ;name count_window_0 mart 2 jack 2 select name ,orderdate,cost ,sum (cost ) over (partition by month (orderdate)) from business;select *,sum (cost ) over (partition by month (orderdate)) from business;select *,lag(orderdate,1 ) over (distribute by name sort by orderdate), lead (orderdate,1 ) over (distribute by name sort by orderdate) from business;select *,lag(orderdate,1 ,"2016-12-31" ) over (distribute by name sort by orderdate) from business;select *,ntile(5 ) over (sort by orderdate) gid from business where gid=1 ;Xselect *,ntile(5 ) over (sort by orderdate) gid from business having gid=1 ;X select * from ( select *,ntile(5 ) over (sort by orderdate) gid from business ) t where gid=1 ; select * from ( select name ,orderdate,cost , ntile(5 ) over (order by orderdate) sorted from business ) t where sorted = 1 ;
Rank
函數
功能
RANK()
排序相同時會重複,總數不會變
DENSE_RANK()
排序相同時會重複,總數會減少
ROW_NUMBER()
會根據順序計算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
[[email protected] datas]$ vi score.txt 孫悟空,語文,87, 孫悟空,數學,95, 孫悟空,英語,73, 白龍馬,語文,94, 白龍馬,數學,56, 白龍馬,英語,84, 魯智深,語文,89, 魯智深,數學,86, 魯智深,英語,84, 白骨精,語文,79, 白骨精,數學,85, 白骨精,英語,78, create table score(name string ,subject string , score int ) row format delimited fields terminated by "\t" ;load data local inpath '/opt/module/datas/score.txt' into table score;name subject score rp drp rmp 孫悟空 數學 95 1 1 1 魯智深 數學 86 2 2 2 白骨精 數學 85 3 3 3 白龍馬 數學 56 4 4 4 魯智深 英語 84 1 1 1 白龍馬 英語 84 1 1 2 白骨精 英語 78 3 2 3 孫悟空 英語 73 4 3 4 白龍馬 語文 94 1 1 1 魯智深 語文 89 2 2 2 孫悟空 語文 87 3 3 3 白骨精 語文 79 4 4 4
自定義函數
Hive 自帶了一些函數,比如:max/min等,但是數量有限,自己可以通過自定義UDF來方便的擴展。
當Hive提供的內置函數無法滿足你的業務處理需要時,此時就可以考慮使用用戶自定義函數(UDF:user-defined function)。
根據用戶自定義函數類別分爲以下三種:
(1)UDF(User-Defined-Function) 一進一出
(2)UDAF(User-Defined Aggregation Function) 聚集函數,多進一出 類似於:count/max/min
(3)UDTF(User-Defined Table-Generating Functions) 一進多出 如lateral view explore()
官方文檔地址
編程步驟:
(1)繼承org.apache.hadoop.hive.ql.UDF
(2)需要實現evaluate函數;evaluate函數支持重載;
(3)在hive的命�"line">score int ) row format delimited fields terminated by "\t" ;load data local inpath '/opt/module/datas/score.txt' into table score;name subject score rp drp rmp 孫悟空 數學 95 1 1 1 魯智深 數學 86 2 2 2 白骨精 數學 85 3 3 3 白龍馬 數學 56 4 4 4 魯智深 英語 84 1 1 1 白龍馬 英語 84 1 1 2 白骨精 英語 78 3 2 3 孫悟空 英語 73 4 3 4 白龍馬 語文 94 1 1 1 魯智深 語文 89 2 2 2 孫悟空 語文 87 3 3 3 白骨精 語文 79 4 4 4
自定義函數
Hive 自帶了一些函數,比如:max/min等,但是數量有限,自己可以通過自定義UDF來方便的擴展。
當Hive提供的內置函數無法滿足你的業務處理需要時,此時就可以考慮使用用戶自定義函數(UDF:user-defined function)。
根據用戶自定義函數類別分爲以下三種:
(1)UDF(User-Defined-Function) 一進一出
(2)UDAF(User-Defined Aggregation Function) 聚集函數,多進一出 類似於:count/max/min
(3)UDTF(User-Defined Table-Generating Functions) 一進多出 如lateral view explore()
官方文檔地址
編程步驟:
(1)繼承org.apache.hadoop.hive.ql.UDF
(2)需要實現evaluate函數;evaluate函數支持重載;
(3)在hive的命令行窗口創建函數
1 2 3 4 5 6 7 8
# add jar jar_path # create [temporary] function [dbname.]function_name AS class_name; # Drop [temporary] function [if exists] [dbname.]function_name;
自定義UDF函數
1 2 3 4 5 6 7 8
<dependencies > <dependency > <groupId > org.apache.hive</groupId > <artifactId > hive-exec</artifactId > <version > 1.2.1</version > </dependency > </dependencies >
java類
1 2 3 4 5 6 7 8 9 10 11 12 13
import org.apache.hadoop.hive.ql.exec.UDF; public class Lower extends UDF { public String evaluate (final String s) { if (s == null) { return null; } return s.toLowerCase(); } }
上傳上服務器
添加jar
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
hive> add jar /home/hadoop/udf.jar; Added [/home/hadoop/udf.jar] to class path Added resources: [/home/hadoop/udf.jar] hive> add jar /home/hadoop/udf.jar; Added [/home/hadoop/udf.jar] to class path Added resources: [/home/hadoop/udf.jar] hive> create temporary function mylower as "com.hph.Lower"; OK Time taken: 0.033 seconds hive> select ename, mylower(ename) lowername from emp limit 2; OK ename lowername SMITH smith ALLEN allen