spark sql常见的内置函数

本文详细介绍了Spark SQL中常用的字符串处理函数,包括concat、concat_ws、decode、encode、format_string等,以及日期时间操作,如current_date、current_timestamp、unix_timestamp、from_unixtime等。这些函数在数据处理和分析中起着重要作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串:

1.concat对于字符串进行拼接
concat(str1, str2, …, strN) - Returns the concatenation of str1, str2, …, strN.

Examples:> SELECT concat(‘Spark’, ‘SQL’);  SparkSQL

2.concat_ws在拼接的字符串中间添加某种格式
concat_ws(sep, [str | array(str)]+) - Returns the concatenation of the strings separated by sep.

Examples:> SELECT concat_ws(’ ', ‘Spark’, ‘SQL’);  Spark SQL

3.decode转码
decode(bin, charset) - Decodes the first argument using the second argument character set.

Examples: > SELECT decode(encode(‘abc’, ‘utf-8’), ‘utf-8’);   abc

4.encode设置编码格式
encode(str, charset) - Encodes the first argument using the second argument character set.

Examples: > SELECT encode(‘abc’, ‘utf-8’);abc

5.format_string/printf 格式化字符串
format_string(strfmt, obj, …) - Returns a formatted string from printf-style format strings.

Examples:> SELECT format_string(“Hello World %d %s”, 100, “days”);  Hello World 100 days

6.initcap将每个单词的首字母变为大写,其他字母小写; lower全部转为小写,upper大写
initcap(str) - Returns str with the first letter of each word in uppercase. All other letters are in lowercase. Words are delimited by white space.

Examples:> SELECT initcap(‘sPark sql’);  Spark Sql

7.length返回字符串的长度
Examples:> SELECT length('Spark SQL ');  10

8.levenshtein编辑距离(将一个字符串变为另一个字符串的距离)
levenshtein(str1, str2) - Returns the Levenshtein distance between the two given strings.

Examples:> SELECT levenshtein(‘kitten’, ‘sitting’);   3

9.lpad返回固定长度的字符串,如果长度不够,用某种字符补全,rpad右补全
lpad(str, len, pad) - Returns str, left-padded with pad to a length of len. If str is longer than len, the return value is shortened to len characters.

Examples:> SELECT lpad(‘hi’, 5, ‘??’);   ???hi

10.ltrim去除空格或去除开头的某些字符,rtrim右去除,trim两边同时去除
ltrim(str) - Removes the leading space characters from str.

ltrim(trimStr, str) - Removes the leading string contains the characters from the trim string

Examples:

SELECT ltrim(’ SparkSQL ');   SparkSQL
SELECT ltrim(‘Sp’, ‘SSparkSQLS’);   arkSQLS
11.regexp_extract 正则提取某些字符串,regexp_replace正则替换
Examples:> SELECT regexp_extract(‘100-200’, ‘(\d+)-(\d+)’, 1);   100

Examples: > SELECT regexp_replace(‘100-200’, ‘(\d+)’, ‘num’);   num-num

12.repeat复制给的字符串n次
Examples: > SELECT repeat(‘123’, 2);  123123

13.instr返回截取字符串的位置/locate
instr(str, substr) - Returns the (1-based) index of the first occurrence of substr in str.

Examples:> SELECT instr(‘SparkSQL’, ‘SQL’);  6

Examples:> SELECT locate(‘bar’, ‘foobarbar’);   4

14.space 在字符串前面加n个空格
space(n) - Returns a string consisting of n spaces.

Examples:> SELECT concat(space(2), ‘1’);  1

15.split以某些字符拆分字符串
split(str, regex) - Splits str around occurrences that match regex.

Examples:> SELECT split(‘oneAtwoBthreeC’, ‘[ABC]’);      [“one”,“two”,“three”,""]

16.substr截取字符串,substring_index
Examples:

SELECT substr(‘Spark SQL’, 5);  k SQL
SELECT substr(‘Spark SQL’, -3);  SQL
SELECT substr(‘Spark SQL’, 5, 1);   k
SELECT substring_index(‘www.apache.org’, ‘.’, 2);   www.apache
17.translate 替换某些字符串为
Examples: > SELECT translate(‘AaBbCc’, ‘abc’, ‘123’);   A1B2C3

18.get_json_object
get_json_object(json_txt, path) - Extracts a json object from path.

Examples:> SELECT get_json_object(’{“a”:“b”}’, ‘$.a’);  b

19.unhex
unhex(expr) - Converts hexadecimal expr to binary.

Examples:> SELECT decode(unhex(‘537061726B2053514C’), ‘UTF-8’);   Spark SQL

20.to_json
to_json(expr[, options]) - Returns a json string with a given struct value

Examples:

SELECT to_json(named_struct(‘a’, 1, ‘b’, 2));   {“a”:1,“b”:2}

SELECT to_json(named_struct(‘time’, to_timestamp(‘2015-08-26’, ‘yyyy-MM-dd’)), map(‘timestampFormat’, ‘dd/MM/yyyy’));   {“time”:“26/08/2015”}

SELECT to_json(array(named_struct(‘a’, 1, ‘b’, 2));   [{“a”:1,“b”:2}]

SELECT to_json(map(‘a’, named_struct(‘b’, 1)));  {“a”:{“b”:1}}

SELECT to_json(map(named_struct(‘a’, 1),named_struct(‘b’, 2)));   {"[1]":{“b”:2}}

SELECT to_json(map(‘a’, 1));  {“a”:1}

SELECT to_json(array((map(‘a’, 1))));  [{“a”:1}]
时间日期:

一、获取当前时间
1.current_date获取当前日期
2018-04-09

2.current_timestamp/now()获取当前时间
2018-04-09 15:20:49.247

二、从日期时间中提取字段
1.year,month,day/dayofmonth,hour,minute,second
Examples:> SELECT day(‘2009-07-30’); 30

2.dayofweek (1 = Sunday, 2 = Monday, …, 7 = Saturday),dayofyear
Examples:> SELECT dayofweek(‘2009-07-30’);   5

Since: 2.3.0

3.weekofyear
weekofyear(date) - Returns the week of the year of the given date. A week is considered to start on a Monday and week 1 is the first week with >3 days.

Examples:> SELECT weekofyear(‘2008-02-20’);   8

4.trunc截取某部分的日期,其他部分默认为01
第二个参数 [“year”, “yyyy”, “yy”, “mon”, “month”, “mm”]

Examples:

SELECT trunc(‘2009-02-12’, ‘MM’);
2009-02-01
SELECT trunc(‘2015-10-27’, ‘YEAR’);
2015-01-01
5.date_trunc [“YEAR”, “YYYY”, “YY”, “MON”, “MONTH”, “MM”, “DAY”, “DD”, “HOUR”, “MINUTE”, “SECOND”, “WEEK”, “QUARTER”]
Examples:> SELECT date_trunc(‘2015-03-05T09:32:05.359’, ‘HOUR’);  2015-03-05T09:00:00

Since: 2.3.0

6.date_format将时间转化为某种格式的字符串
Examples:> SELECT date_format(‘2016-04-08’, ‘y’);    2016

三、日期时间转换
1.unix_timestamp返回当前时间的unix时间戳
Examples:

SELECT unix_timestamp();  1476884637
SELECT unix_timestamp(‘2016-04-08’, ‘yyyy-MM-dd’);   1460041200
2.from_unixtime将时间戳换算成当前时间,to_unix_timestamp将时间转化为时间戳
Examples:

SELECT from_unixtime(0, ‘yyyy-MM-dd HH:mm:ss’);  1970-01-01 00:00:00
SELECT to_unix_timestamp(‘2016-04-08’, ‘yyyy-MM-dd’);  
1460041200
3.to_date/date将字符串转化为日期格式,to_timestamp(Since: 2.2.0)
SELECT to_date(‘2009-07-30 04:17:52’);  2009-07-30
SELECT to_date(‘2016-12-31’, ‘yyyy-MM-dd’);   2016-12-31
SELECT to_timestamp(‘2016-12-31 00:12:00’);   2016-12-31 00:12:00
4.quarter 将1年4等分(range 1 to 4)
Examples:> SELECT quarter(‘2016-08-31’); 3

四、日期、时间计算
1.months_between两个日期之间的月数
months_between(timestamp1, timestamp2) - Returns number of months between timestamp1 and timestamp2.

Examples:> SELECT months_between(‘1997-02-28 10:30:00’, ‘1996-10-30’);  3.94959677

  1. add_months返回日期后n个月后的日期
    Examples:> SELECT add_months(‘2016-08-31’, 1);  2016-09-30

3.last_day(date),next_day(start_date, day_of_week)
Examples:

SELECT last_day(‘2009-01-12’);  2009-01-31
SELECT next_day(‘2015-01-14’, ‘TU’);  2015-01-20
4.date_add,date_sub(减)
date_add(start_date, num_days) - Returns the date that is num_days after start_date.

Examples:

SELECT date_add(‘2016-07-30’, 1);  2016-07-31
5.datediff(两个日期间的天数)
datediff(endDate, startDate) - Returns the number of days from startDate to endDate.

Examples:> SELECT datediff(‘2009-07-31’, ‘2009-07-30’); 1

6.关于UTC时间
to_utc_timestamp
to_utc_timestamp(timestamp, timezone) - Given a timestamp like ‘2017-07-14 02:40:00.0’, interprets it as a time in the given time zone, and renders that time as a timestamp in UTC. For example, ‘GMT+1’ would yield ‘2017-07-14 01:40:00.0’.

Examples:> SELECT to_utc_timestamp(‘2016-08-31’, ‘Asia/Seoul’);  2016-08-30 15:00:0

from_utc_timestamp
from_utc_timestamp(timestamp, timezone) - Given a timestamp like ‘2017-07-14 02:40:00.0’, interprets it as a time in UTC, and renders that time as a timestamp in the given time zone. For example, ‘GMT+1’ would yield ‘2017-07-14 03:40:00.0’.

Examples:> SELECT from_utc_timestamp(‘2016-08-31’, ‘Asia/Seoul’);  2016-08-31 09:00:00

<think>我们正在讨论SparkSQL中的select函数。根据用户的问题,他想了解select函数的使用方法和示例。根据引用[3],我们可以看到在SparkSQL中调用自定义函数的两种方式:SQL方式和DSL方式。在SQL方式中,我们使用spark.sql("""select..."""),其中select就是SQL语句的一部分。在DSL方式中,我们使用DataFrame的select方法,例如df.select(...)。另外,引用[5]中展示了一个使用select的SQL语句示例:spark.sql("selectname,class,score,count(name)over(partitionbyclass)name_countfromscores").show因此,我们可以将select的使用分为两种风格:SQL风格和DataFrameAPI(DSL)风格。下面我们将分别介绍这两种风格的使用方法,并给出示例。1.SQL风格:在SparkSQL中,我们可以直接执行SQL查询语句。首先需要将DataFrame注册为临时视图,然后使用spark.sql()方法执行SQL语句,其中就包含select子句。2.DataFrameAPI(DSL)风格:使用DataFrame的select方法,可以传入多个列表达式(可以是列名、列的计算表达式等)。同时,我们还可以在select中使用一些内置函数或者窗口函数等,如引用[5]中使用了窗口函数count(...)over(...)。下面给出具体示例:首先,假设我们有一个DataFrame,名为df,它包含以下列:id,name,address。示例1:选择特定的列(SQL风格)df.createOrReplaceTempView("people")spark.sql("SELECTid,nameFROMpeople").show()示例2:选择特定的列(DSL风格)df.select("id","name").show()示例3:在select中使用表达式(例如,给列重命名,进行计算等)SQL风格:spark.sql("SELECTid,name,addressashome_addressFROMpeople").show()DSL风格:importorg.apache.spark.sql.functions._df.select(col("id"),col("name"),col("address").alias("home_address")).show()示例4:在select中使用函数(例如,字符串函数)SQL风格:spark.sql("SELECTid,name,upper(address)asupper_addressFROMpeople").show()DSL风格:df.select(col("id"),col("name"),upper(col("address")).alias("upper_address")).show()示例5:在select中使用窗口函数(如引用[5])SQL风格:spark.sql("selectname,class,score,count(name)over(partitionbyclass)asname_countfromscores").show()DSL风格:importorg.apache.spark.sql.expressions.WindowvalwindowSpec=Window.partitionBy("class")df.select(col("name"),col("class"),col("score"),count("name").over(windowSpec).alias("name_count")).show()另外,在引用[3]中,我们还看到了在select中调用自定义函数的示例(SQL方式和DSL方式)。例如,调用一个名为sql_add_suffix的自定义函数:SQL风格:spark.sql("selectid,name,sql_add_suffix(address)asnew_addressfromtemp").show()DSL风格:df.select('id,'name,dsl1_add_suffix('address).alias('new_address')).show()总结:SparkSQL的select函数用于选择指定的列,并可以对列进行变换(使用内置函数或自定义函数)。用户可以根据自己的喜好选择SQL风格或DSL风格(DataFrameAPI)来编写代码。根据要求,生成相关问题:1.SparkSQL中如何重命名select出来的列?2.在SparkSQL的select中如何使用条件表达式?3.SparkSQL中select和selectExpr有什么区别?4.如何在select中使用聚合函数?5.如何通过select添加新列?</think>### Spark SQL `select` 函数详解 `select` 函数是 Spark SQL 的核心操作之一,用于从 DataFrame 或 Dataset 中选取指定列或表达式。支持两种使用方式:**SQL 语法**和 **DSL(领域特定语言)语法**。 #### 一、基础用法 1. **选择指定列(SQL 语法)**: ```sql SELECT col1, col2 FROM table_name ``` ```scala // 示例:选择 name 和 age 列 spark.sql("SELECT name, age FROM users").show() ``` 2. **选择指定列(DSL 语法)**: ```scala df.select("col1", "col2") ``` ```scala // 示例:选择 name 和 address 列 df.select("name", "address").show() ``` #### 二、进阶用法 1. **表达式计算**: ```scala // 给地址添加后缀(引用自定义函数)[^3] df.select( $"id", $"name", sql_add_suffix($"address").alias("new_address") ).show() ``` 2. **使用内置函数**: ```scala import org.apache.spark.sql.functions._ // 计算名字长度并重命名列 df.select($"name", length($"name").alias("name_length")).show() ``` 3. **操作 Map 类型**(引用[^2]): ```sql -- 提取 map 中的值 SELECT my_map['key1'] AS value FROM table ``` #### 三、窗口函数(引用[^5]) ```sql -- 按班级分区计算人数 SELECT name, class, score, COUNT(name) OVER(PARTITION BY class) AS name_count FROM scores ``` #### 四、自定义聚合(引用[^4]) ```scala // 注册自定义聚合函数 spark.udf.register("my_agg", new MyAggregationFunction) // 在 select 中使用 spark.sql("SELECT class, my_agg(score) FROM scores GROUP BY class") ``` #### 五、性能优化建议 1. **列裁剪**:只选择必要列,减少数据传输 ```scala df.select("id", "name") // 优于 select("*") ``` 2. **避免复杂嵌套**:对复杂表达式分步计算 3. **使用别名**:对计算列使用 `alias()` 提高可读性 > **注意**:完整示例代码可参考 Spark 官方仓库的 `examples/src/main/scala/org/apache/spark/examples/sql/` 目录[^1][^4]。 --- ### 相关问题 1. Spark SQL 中如何实现 `select` 时的条件过滤? 2. `select` 和 `selectExpr` 有什么区别?何时使用后者? 3. 如何在 `select` 中处理嵌套结构(如 struct 或 array)? 4. `select` 操作是否会触发 Spark 作业执行? 5. 如何通过 `select` 实现列的动态选择(如基于变量选择列)?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值