Spark SQL函数大杂烩

  • 函数很多,都在下面了:
    • 1.聚合函数
    • 2.集合函数
    • 3.时间函数
    • 4.数学函数
    • 5.混杂(misc)函数
    • 6.其他非聚合函数
    • 7.排序函数
    • 8.字符串函数
    • 9.UDF函数
    • 10.窗口函数
  • org.apache.spark.sql.functions是一个Object,提供了约两百多个函数
  • 大部分函数与Hive的差不多
  • 除UDF函数,均可在spark-sql中直接使用
  • 经过import org.apache.spark.sql.functions._ ,也可以用于Dataframe,Dataset
  • version 2.3.0
  • 大部分支持Column的函数也支持String类型的列名。这些函数的返回类型基本都是Column

函数很多,都在下面了:

1.聚合函数

approx_count_distinct
count_distinct近似值avg
平均值collect_list
聚合指定字段的值到listcollect_set
聚合指定字段的值到setcorr
计算两列的Pearson相关系数count
计数countDistinct
去重计数 SQL中用法
select count(distinct class)covar_pop
总体协方差(population covariance)covar_samp
样本协方差(sample covariance)first
分组第一个元素last
分组最后一个元素groupinggrouping_idkurtosis计算峰态(kurtosis)值skewness计算偏度(skewness)max
最大值min
最小值mean
平均值stddev即stddev_sampstddev_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的键组成的arraymap_values
返回map的值组成的arraysize
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/stringdayofyear(e: Column)
日期在一年中的天数, 支持 date/timestamp/stringweekofyear(e: Column)
日期在一年中的周数, 支持 date/timestamp/stringfrom_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)
字段类型转为DateTypetrunc(date: Column, format: String)
日期截断unix_timestamp(s: Column, p: String)
指定格式的时间字符串转时间戳unix_timestamp(s: Column)
同上,默认格式为 yyyy-MM-dd HH:mm:ssunix_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,返回biginthash(cols: Column*):计算 hash code,返回intmd5(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对应的Columncolumn(colName: String):
col函数的别名expr(expr: String):
解析expr表达式,将返回值存于Column,并返回这个Column。greatest(exprs: Column*):
返回多列中的最大值,跳过Nullleast(exprs: Column*):
返回多列中的最小值,跳过Nullinput_file_name():返
回当前任务的文件名 ??isnan(e: Column):
检查是否NaN(非数值)isnull(e: Column):
检查是否为Nulllit(literal: Any):
将字面量(literal)创建一个ColumntypedLit[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则返回col2negate(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 IDstruct(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函数desc,desc_nulls_first,desc_nulls_last

8.字符串函数


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分割strsubstring(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。

9.UDF函数

user-defined function.callUDF(udfName: String, cols: Column*): 调用UDF
import org.apache.spark.sql._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

10.窗口函数


cume_dist(): cumulative distribution of values within a window partitioncurrentRow(): 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,4percent_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 rowlead(e: Column, offset: Int, defaultValue: Any): returns the value that is offset rows after the current rowntile(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.

Spark SQL函数总结相关推荐

  1. Spark Sql 函数

    Spark Sql 函数 一. 字符串函数 1. 字符串截取 1.1 字符串截取之substring_index函数 1.2 字符串截取之substring函数和substr函数 2. 字符串查找 2 ...

  2. Spark SQL 函数全集

    org.apache.spark.sql.functions是一个Object,提供了约两百多个函数. 大部分函数与Hive的差不多. 除UDF函数,均可在spark-sql中直接使用. 经过impo ...

  3. spark sql 之 collect_set collect_list 后WrappedArray 取值

    示例:demo数据 userId place 1001 北京 1001 上海 spark建立的虚拟表 userPlaceView.根据用户ID进行分组,用collect_set(place)获取pla ...

  4. sparksql 大小写_Spark SQL函数

    Spark SQL函数 发布时间:2018-10-23 14:35, 浏览次数:942 , 标签: Spark SQL <>Spark SQL函数 <>一.概述 <> ...

  5. Spark SQL实战(08)-整合Hive

    1 整合原理及使用 Apache Spark 是一个快速.可扩展的分布式计算引擎,而 Hive 则是一个数据仓库工具,它提供了数据存储和查询功能.在 Spark 中使用 Hive 可以提高数据处理和查 ...

  6. Hive/Spark SQL使用案例

    Hive/Spark SQL使用案例 求 TOPN:开窗函数 求天数:datediff() 函数 求每个学生的成绩都大于...系列:开窗 / 分组 表转置/行转列系列一:concat_ws 函数 表转 ...

  7. spark SQL快速入门 1-9 慕课网

    1.hadoop安装 1.修改hadoop配置文件hadoop-env.shexport JAVA_HOME=/home/hadoop/app/jdk1.8.0_91core-site.xml< ...

  8. 大数据分析实训——使用Spark SQL分析美国新冠肺炎疫情

    项目思路: 使用Spark SQL读取文件数据集来生成Data Frame对象,再利用Spark SQL函数对Data Frame对象进行数据分析,并将结果存入MySQL数据库,再以Web网页的形式对 ...

  9. Spark SQL基本操作以及函数的使用

    2019独角兽企业重金招聘Python工程师标准>>> 引语: 本篇博客主要介绍了Spark SQL中的filter过滤数据.去重.集合等基本操作,以及一些常用日期函数,随机函数,字 ...

最新文章

  1. 资源 | 我们从8800个机器学习开源项目中精选出Top30,推荐给你
  2. 【Android游戏开发十五】关于Android 游戏开发中 OnTouchEvent() 触屏事件的性能优化笔记! .
  3. Android studio Dialog 弹出式对话框
  4. java string 返回匹配正则的字符串的起始位置_Python小课堂正则表达式
  5. elasticsearch快照和恢复
  6. switchcase的用法
  7. 【转】DOS下文件传输---初识TCP网络编程改版
  8. 一张图弄懂java线程的状态和生命周期
  9. 天下为公:TCP堵塞控制
  10. 看完这篇你们团队的代码也很规范
  11. scrapy中自定义过滤规则以及start_urls不进过滤器的问题
  12. 我比领导小15岁,互相有好感,为什么每次路过我办公室都叹气?
  13. 给你的应用“一只”智慧的眼睛 —— Barcode常识普及以及识别信息处理
  14. [Soft]软件技术的两个趋势
  15. asm 与 cglib(整理的)
  16. 使用内存映射提高BufferedRandoAccessFile性能(测试可用)
  17. [Windows Server 2012] SQL Server 备份和还原方法
  18. Velocity之vm页面注释
  19. 一篇文章带你入门python基础开发
  20. access里面的表达式运用_ACCESS条件表达式用法

热门文章

  1. DC综合的一些基本概念
  2. 数据库系统概论—除运算的理解
  3. 随笔之看雷军视频有感//2021-2-24
  4. web程序_通过学号查询学生信息_笔记
  5. 编译原理 - 词法分析
  6. 12步解N-S方程之第五步(1)
  7. java dispo lock_java
  8. 【博学谷学习记录】超强总结,用心分享|人工智能第一课Python的认识与环境搭建。
  9. 鸿蒙最新功能及承载设备详解:HarmonyOS 2及华为全场景新品发布会全纪录
  10. LeetCode:1309. 解码字母到整数映射