Hive函式——日期函式,正則表示式和排序函式
1。日期函式
2。正則表示式
3。排序操作
本文主要分享下Hive中日期函式,正則表示式函式,以及排序函式的使用方法和特點。
1.日期函式
Hive中日期函式功能不是很強大,其實是加減函式只能對天操作,無法直接取n個月前的日期,或n年前的日期。即不支援
add_months()
函式 和
interval
關鍵詞。
1
/* 往前推兩個月 */
2
select
cast
(
add_months
(
date
‘2020-03-31’
,
-
2
)
as
date
format
‘yyyy-dd-mm’
)
——2020-01-31
3
/* 往前推1年*/
4
select
cast
(
date
‘2020-04-01’
-
interval
1
years
)
——2019-04-01
5
——ps:上述語法為TD資料庫,而且注意一點是interval關鍵詞遇到閏年會報錯
6
select
cast
(
date
‘2020-02-29’
-
interval
1
years
)
——結果不會是2019-02-28 而是error
7
——推薦使用add_months()
8
select
cast
(
add_months
(
date
‘2020-02-29’
,
-
12
)
as
date
format
‘yyyy-dd-mm’
)
——2020-02-28
Hive中常用的三個函式如下:
日期減n天
1
select
date_sub
(
current_date
,
2
)
2
select
date_sub
(
‘2020-03-20’
,
1
)
——2020-03-19`
日期加n天
1
select
date_add
(
‘2020-03-19’
,
2
)
——2020-03-21
日期差
1
select
datediff
(
‘2020-03-22’
,
‘2020-03-20’
)
——2
2.正則表示式
Hive中正則表達函式有3個
regexp(string,pattern) --返回值 布林型別 true false
主要在where中作篩選條件
1
select
regexp
(
‘ab。ge’
,
‘[0-9]’
)
——false
2
——同時包含數字和字母的正則表示式:‘^(?![0-9]+$)[0-9a-zA-z]。*?$’
regexp_extract(string,pattern,int index) --返回值 string
int index 取值為[0-n],n不大於正則項pattern的組成個數,正則項由多部分組合每部分在()內包含。
ps: index = 0返回與符合正則的整個原表示式 ,index預設等於1 ;
1
select
regexp_extract
(
‘6a9d0b’
,
‘[0-9a-zA-Z]+’
,
0
)
2
—— 返回 6a9d0b
index 必須且只能設定為0 預設是1 會報錯 ,因為正則項pattern是一個整體,不是幾個部分組成;
正則項: '([0-9]+)(.*?)([0-9]+)'
這個正則項就是三部分組成 第一部分是數字([0-9]+) 第二部分是字元的貪婪匹配,第三部分是字母。
1
——取滿足正則項的整體字串
2
select
regexp_extract
(
‘[“84745554”,“asDd”]’
,
‘([0-9]+)(。*?)([a-zA-Z]+)’
,
0
);
3
——84745554“,”asDd
4
——取滿足正則項的第一部分子字串
5
select
regexp_extract
(
‘[“84745554”,“asDd”]’
,
‘([0-9]+)(。*?)([a-zA-Z]+)’
,
1
);
——
6
——84745554
7
——取滿足正則項的第二部分子字串
8
select
regexp_extract
(
‘[“84745554”,“asDd”]’
,
‘([0-9]+)(。*?)([a-zA-Z]+)’
,
2
);
9
——“,”
10
——取滿足正則項的第三部分子字串
11
select
regexp_extract
(
‘[“84745554”,“asDd”]’
,
‘([0-9]+)(。*?)([a-zA-Z]+)’
,
3
);
12
——asDd
主要在select語句中篩選子字串
1
select
regexp_extrct
(
‘trx_txt’
,
‘[0-9]’
,
1
)
regexp_replace(string,pattern,replace string) --返回值 string
主要在select語句中作替換
1
select
regexp_replace
(
‘adci892’
,
‘[0-9]’
,
‘v’
)
——adcivvv
3.排序操作
order by
會對輸入做全域性排序,因此只有一個reducer(多個reducer無法保證全域性有序),
只有一個reducer,會導致當輸入規模較大時,需要較長的計算時間。
sort by
不是全域性排序,其在資料進入reducer前完成排序,
sort by 的資料只能保證在同一reduce中的資料可以按指定欄位排序。
distribute by
按照指定的欄位對資料進行劃分到不同的輸出reduce / 檔案中
cluster by
除了具有 distribute by 的功能外還兼具 sort by 的功能。
歡迎關注【丁點兒印記】,謝謝支援