1.聚合函數
approx_count_distinct
count_distinct近似值
avg
平均值
collect_list
聚合指定字段的值到list
collect_set
聚合指定字段的值到set
corr
計算兩列的Pearson相關係數
count
計數
countDistinct
去重計數 SQL中用法
select count ( distinct class )
covar_pop
總體協方差(population covariance)
covar_samp
樣本協方差(sample covariance)
first
分組第一個元素
last
分組最後一個元素
grouping
grouping_id
kurtosis
計算峯態( kurtosis) 值
skewness
計算偏度( skewness)
max
最大值
min
最小值
mean
平均值
stddev
即stddev_samp
stddev_samp
樣本標準偏差(sample standard deviation)
stddev_pop
總體標準偏差(population standard deviation)
sum
求和
sumDistinct
非重複值求和 SQL中用法
select sum ( distinct class )
var_pop
總體方差(population variance)
var_samp
樣本無偏方差(unbiased variance)
variance
即var_samp
2.集合函數
array_contains ( column, value)
檢查array類型字段是否包含指定元素
explode
展開array或map爲多行
explode_outer
同explode,但當array或map爲空或null時,會展開爲null。
posexplode
同explode,帶位置索引。
posexplode_outer
同explode_outer,帶位置索引。
from_json
解析JSON字符串爲StructType or ArrayType,有多種參數形式,詳見文檔。
to_json
轉爲json字符串,支持StructType, ArrayType of StructTypes, a MapType or ArrayType of MapTypes。
get_json_object ( column, path)
獲取指定json路徑的json對象字符串。
select get_json_object ( '{"a"1,"b":2}' , '$.a' ) ;
[ JSON Path介紹] ( http: / / blog. csdn. net/ koflance/ article/ details/ 63262484 )
json_tuple ( column, fields)
獲取json中指定字段值。select json_tuple ( '{"a":1,"b":2}' , 'a' , 'b' ) ;
map_keys
返回map的鍵組成的array
map_values
返回map的值組成的array
size
array or map的長度
sort_array ( e: Column, asc: Boolean)
將array中元素排序(自然排序),默認asc。
3.時間函數
add_months ( startDate: Column, numMonths: Int)
指定日期添加n月
date_add ( start: Column, days: Int)
指定日期之後n天 e. g. select date_add ( '2018-01-01' , 3 )
date_sub ( start: Column, days: Int)
指定日期之前n天
datediff ( end: Column, start: Column)
兩日期間隔天數
current_date ( )
當前日期
current_timestamp ( )
當前時間戳,TimestampType類型
date_format ( dateExpr: Column, format: String)
日期格式化
dayofmonth ( e: Column)
日期在一月中的天數,支持 date/ timestamp/ string
dayofyear ( e: Column)
日期在一年中的天數, 支持 date/ timestamp/ string
weekofyear ( e: Column)
日期在一年中的週數, 支持 date/ timestamp/ string
from_unixtime ( ut: Column, f: String)
時間戳轉字符串格式
from_utc_timestamp ( ts: Column, tz: String)
時間戳轉指定時區時間戳
to_utc_timestamp ( ts: Column, tz: String)
指定時區時間戳轉UTF時間戳
hour ( e: Column)
提取小時值
minute ( e: Column)
提取分鐘值
month ( e: Column)
提取月份值
quarter ( e: Column)
提取季度
second ( e: Column)
提取秒
year ( e: Column) : 提取年
last_day ( e: Column)
指定日期的月末日期
months_between ( date1: Column, date2: Column)
計算兩日期差幾個月
next_day ( date: Column, dayOfWeek: String)
計算指定日期之後的下一個週一、二. . . ,dayOfWeek區分大小寫,只接受 "Mon" , "Tue" , "Wed" , "Thu" , "Fri" , "Sat" , "Sun" 。
to_date ( e: Column)
字段類型轉爲DateType
trunc ( date: Column, format: String)
日期截斷
unix_timestamp ( s: Column, p: String)
指定格式的時間字符串轉時間戳
unix_timestamp ( s: Column)
同上,默認格式爲 yyyy- MM- dd HH: mm: ss
unix_timestamp ( ) : 當前時間戳( 秒) , 底層實現爲unix_timestamp ( current_timestamp ( ) , yyyy- MM- dd HH: mm: ss)
window ( timeColumn: Column, windowDuration: String, slideDuration: String, startTime: String)
時間窗口函數,將指定時間( TimestampType) 劃分到窗口
4.數學函數
cos, sin, tan
計算角度的餘弦,正弦。。。
sinh, tanh, cosh
計算雙曲正弦,正切,。。
acos, asin, atan, atan2
計算餘弦/ 正弦值對應的角度
bin
將long 類型轉爲對應二進制數值的字符串For example, bin ( "12" ) returns "1100" .
bround
舍入,使用Decimal的HALF_EVEN模式,v> 0.5 向上舍入,v< 0.5 向下舍入,v0. 5 向最近的偶數舍入。
round ( e: Column, scale: Int)
HALF_UP模式舍入到scale爲小數點。v>= 0.5 向上舍入,v< 0.5 向下舍入, 即四捨五入。
ceil
向上舍入
floor
向下舍入
cbrt
Computes the cube- root of the given value.
conv ( num: Column, fromBase: Int, toBase: Int)
轉換數值(字符串)的進制
log ( base: Double, a: Column) : $log_{ base} ( a) $
log ( a: Column) : $log_e ( a) $
log10 ( a: Column) : $log_{ 10 } ( a) $
log2 ( a: Column) : $log_{ 2 } ( a) $
log1p ( a: Column) : $log_{ e} ( a+ 1 ) $
pmod ( dividend: Column, divisor: Column) : Returns the positive value of dividend mod divisor.
pow ( l: Double, r: Column) : $r^ l$ 注意r是列
pow ( l: Column, r: Double) : $r^ l$ 注意l是列
pow ( l: Column, r: Column) : $r^ l$ 注意r, l都是列
radians ( e: Column) : 角度轉弧度
rint ( e: Column) : Returns the double value that is closest in value to the argument and is equal to a mathematical integer.
shiftLeft ( e: Column, numBits: Int) : 向左位移
shiftRight ( e: Column, numBits: Int) : 向右位移
shiftRightUnsigned ( e: Column, numBits: Int) : 向右位移(無符號位)
signum ( e: Column) : 返回數值正負符號
sqrt ( e: Column) : 平方根
hex ( column: Column) : 轉十六進制
unhex ( column: Column) : 逆轉十六進制
5.混雜(misc)函數
crc32 ( e: Column) : 計算CRC32, 返回bigint
hash ( cols: Column* ) : 計算 hash code,返回int
md5 ( e: Column) : 計算MD5摘要,返回32 位,16 進制字符串
sha1 ( e: Column) : 計算SHA- 1 摘要,返回40 位,16 進制字符串
sha2 ( e: Column, numBits: Int) : 計算SHA- 1 摘要,返回numBits位,16 進制字符串。numBits支持224 , 256 , 384 , or 512.
6.其他非聚合函數
abs ( e: Column)
絕對值
array ( cols: Column* )
多列合併爲array,cols必須爲同類型
map ( cols: Column* ) :
將多列組織爲map,輸入列必須爲(key, value) 形式,各列的key/ value分別爲同一類型。
bitwiseNOT ( e: Column) :
Computes bitwise NOT.
broadcast[ T] ( df: Dataset[ T] ) : Dataset[ T] :
將df變量廣播,用於實現broadcast join。如left. join ( broadcast ( right) , "joinKey" )
coalesce ( e: Column* ) :
返回第一個非空值
col ( colName: String) :
返回colName對應的Column
column ( colName: String) :
col函數的別名
expr ( expr: String) :
解析expr表達式,將返回值存於Column,並返回這個Column。
greatest ( exprs: Column* ) :
返回多列中的最大值,跳過Null
least ( exprs: Column* ) :
返回多列中的最小值,跳過Null
input_file_name ( ) : 返
回當前任務的文件名 ??
isnan ( e: Column) :
檢查是否NaN(非數值)
isnull ( e: Column) :
檢查是否爲Null
lit ( literal: Any) :
將字面量( literal) 創建一個Column
typedLit[ T] ( literal: T) ( implicit arg0: scala. reflect. api. JavaUniverse. TypeTag[ T] ) :
將字面量( literal) 創建一個Column,literal支持 scala types e. g. : List, Seq and Map.
monotonically_increasing_id ( ) :
返回單調遞增唯一ID,但不同分區的ID不連續。ID爲64 位整型。
nanvl ( col1: Column, col2: Column) :
col1爲NaN則返回col2
negate ( e: Column) :
負數,同df. select ( - df ( "amount" ) )
not ( e: Column) :
取反,同df. filter ( ! df ( "isActive" ) )
rand ( ) :
隨機數[ 0.0 , 1.0 ]
rand ( seed: Long) :
隨機數[ 0.0 , 1.0 ] ,使用seed種子
randn ( ) :
隨機數,從正態分佈取
randn ( seed: Long) :
同上
spark_partition_id ( ) :
返回partition ID
struct ( cols: Column* ) :
多列組合成新的struct column ??
when ( condition: Column, value: Any) :
當condition爲true 返回value,如
people. select ( when ( people ( "gender" ) == = "male" , 0 )
. when ( people ( "gender" ) == = "female" , 1 )
. otherwise ( 2 ) )
如果沒有otherwise且condition全部沒命中,則返回null.
7.其他非聚合函數
asc ( columnName: String) : 正序
asc_nulls_first ( columnName: String) : 正序,null排最前
asc_nulls_last ( columnName: String) : 正序,null排最後
e. g.
df. sort ( asc ( "dept" ) , desc ( "age" ) )
desc ( columnName: String) : 倒序
desc_nulls_first ( columnName: String) : 倒序,null排最前
desc_nulls_last ( columnName: String) : 倒序,null排最後
7.字符串函數
ascii ( e: Column) : 計算第一個字符的ascii碼
base64 ( e: Column) : base64轉碼
unbase64 ( e: Column) : base64解碼
concat ( exprs: Column* ) : 連接多列字符串
concat_ws ( sep: String, exprs: Column* ) : 使用sep作爲分隔符連接多列字符串
decode ( value: Column, charset: String) : 解碼
encode ( value: Column, charset: String) : 轉碼,charset支持 'US-ASCII' , 'ISO-8859-1' , 'UTF-8' , 'UTF-16BE' , 'UTF-16LE' , 'UTF-16' 。
format_number ( x: Column, d: Int) : 格式化'#,###,###.##' 形式的字符串
format_string ( format: String, arguments: Column* ) : 將arguments按format格式化,格式爲printf- style。
initcap ( e: Column) : 單詞首字母大寫
lower ( e: Column) : 轉小寫
upper ( e: Column) : 轉大寫
instr ( str: Column, substring: String) : substring在str中第一次出現的位置
length ( e: Column) : 字符串長度
levenshtein ( l: Column, r: Column) : 計算兩個字符串之間的編輯距離(Levenshtein distance)
locate ( substr: String, str: Column) : substring在str中第一次出現的位置,位置編號從1 開始,0 表示未找到。
locate ( substr: String, str: Column, pos: Int) : 同上,但從pos位置後查找。
lpad ( str: Column, len: Int, pad: String) : 字符串左填充。用pad字符填充str的字符串至len長度。有對應的rpad,右填充。
ltrim ( e: Column) : 剪掉左邊的空格、空白字符,對應有rtrim.
ltrim ( e: Column, trimString: String) : 剪掉左邊的指定字符, 對應有rtrim.
trim ( e: Column, trimString: String) : 剪掉左右兩邊的指定字符
trim ( e: Column) : 剪掉左右兩邊的空格、空白字符
regexp_extract ( e: Column, exp: String, groupIdx: Int) : 正則提取匹配的組
regexp_replace ( e: Column, pattern: Column, replacement: Column) : 正則替換匹配的部分,這裏參數爲列。
regexp_replace ( e: Column, pattern: String, replacement: String) : 正則替換匹配的部分
repeat ( str: Column, n: Int) : 將str重複n次返回
reverse ( str: Column) : 將str反轉
soundex ( e: Column) : 計算桑迪克斯代碼(soundex code)PS: 用於按英語發音來索引姓名, 發音相同但拼寫不同的單詞,會映射成同一個碼。
split ( str: Column, pattern: String) : 用pattern分割str
substring ( str: Column, pos: Int, len: Int) : 在str上截取從pos位置開始長度爲len的子字符串。
substring_index ( str: Column, delim: String, count: Int) : Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything the left of the final delimiter ( counting from left) is returned. If count is negative, every to the right of the final delimiter ( counting from the right) is returned. substring_index performs a case - sensitive match when searching for delim.
translate ( src: Column, matchingString: String, replaceString: String) : 把src中的matchingString全換成replaceString。
8.UDF函數
user- defined function.
callUDF ( udfName: String, cols: Column* ) : 調用UDF
val df = Seq ( ( "id1" , 1 ) , ( "id2" , 4 ) , ( "id3" , 5 ) ) . toDF ( "id" , "value" )
val spark = df. sparkSession
spark. udf. register ( "simpleUDF" , ( v: Int) = > v * v)
df. select ( $"id" , callUDF ( "simpleUDF" , $"value" ) )
udf: 定義UDF
spark. udf. register ( "spliceAttr" , ( v1: String, v2: String) = > {
"attr_name:" + v1 + " attr_value:" + v2
} )
9.窗口函數
cume_dist ( ) : cumulative distribution of values within a window partition
currentRow ( ) : returns the special frame boundary that represents the current row in the window partition.
rank ( ) : 排名,返回數據項在分組中的排名,排名相等會在名次中留下空位 1 , 2 , 2 , 4 。
dense_rank ( ) : 排名,返回數據項在分組中的排名,排名相等會在名次中不會留下空位 1 , 2 , 2 , 3 。
row_number ( ) : 行號,爲每條記錄返回一個數字 1 , 2 , 3 , 4
percent_rank ( ) : returns the relative rank ( i. e. percentile) of rows within a window partition.
lag ( e: Column, offset: Int, defaultValue: Any) : offset rows before the current row
lead ( e: Column, offset: Int, defaultValue: Any) : returns the value that is offset rows after the current row
ntile ( n: Int) : returns the ntile group id ( from 1 to n inclusive) in an ordered window partition.
unboundedFollowing ( ) : returns the special frame boundary that represents the last row in the window partition.