Hive字符串处理

Hive字符串处理

  • 截取
  • 拼接
    • 1. concat()
    • 2. concat_ws()
  • 分割
  • 替换
    • 1. 直接替换
    • 2. 正则替换
  • 正则匹配
    • 正则表达式的符号及意义
    • 贪婪匹配 vs 非贪婪匹配
  • JSON字符串解析
    • 1. get_json_object()
      • JSONPath
    • 2. json_tuple()
    • 3. str_to_map()

截取

Return Type Name(Signature) Description
string substr(string A, int start) Returns the substring or slice of the byte array of A starting from start position till the end of string A. For example, substr(‘foobar’, 4) results in ‘bar’ …对于字符串A,从start位置开始截取字符串并返回
string substr(string A, int start, int len) Returns the substring or slice of the byte array of A starting from start position with length len. For example, substr(‘foobar’, 4, 1) results in ‘b’ …对于二进制/字符串A,从start位置开始截取长度为length的字符串并返回
string substring_index(string A, string delim, int count) Returns the substring from string A before count occurrences of the delimiter delim (as of Hive 1.3.0). If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. Substring_index performs a case-sensitive match when searching for delim. Example: substring_index(‘www.apache.org’, ‘.’, 2) = ‘www.apache’…截取第count分隔符之前的字符串,如count为正则从左边开始截取,如果为负则从右边开始截取
int instr(string str, string substr) Returns the position of the first occurrence of substr in str. Returns null if either of the arguments are null and returns 0 if substr could not be found in str. Be aware that this is not zero based. The first character in str has index 1…查找字符串str中子字符串substr出现的位置,如果查找失败将返回0,如果任一参数为Null将返回null,注意位置为从1开始的

拼接

Return Type Name(Signature) Description
string concat(string A, string B…) Returns the string or bytes resulting from concatenating the strings or bytes passed in as parameters in order. For example, concat(‘foo’, ‘bar’) results in ‘foobar’. Note that this function can take any number of input strings…对二进制字节码或字符串按次序进行拼接
string concat_ws(string SEP, string A, string B…) Like concat() above, but with custom separator SEP…与concat()类似,但使用指定的分隔符喜进行分隔
string concat_ws(string SEP, array) Like concat_ws() above, but taking an array of strings. (as of Hive 0.9.0).拼接Array中的元素并用指定分隔符进行分隔

1. concat()

2. concat_ws()

指定分隔符将多个字符串连接起来,结合group by与collect_set使用可实现“列转行”。

hive > select concat_ws('+','a','b','c');
OK
a+b+c

hive > select aa, bb, cc from jj_tmp.user_list;
OK
c	d	1
c	d	2
c	d	3
e	f	4
e	f	5
e	f	6

hive > select aa, bb, concat_ws(',' , collect_set(cast(cc as string))) from user_list group by aa, bb;
OK
c	d	1,2,3
e	f	4,5,6

上述用的到的 collect_set 函数,有两个作用,第一个是去重,去除group by后的重复元素,第二个是形成一个集合,将group by后属于同一组的第三列集合起来成为一个集合。

分割

Return Type Name(Signature) Description
array split(string str, string pat) Splits str around pat (pat is a regular expression).按照正则表达式pat来分割字符串str,并将分割后的数组字符串的形式返回

将字符串按指定分隔符切分,以数组形式返回结果后,可用 [ ] 选择元素,或结合explode()函数实现“行转列”。

hive > select split('888|666|544','\\|');
OK
["888","666","544"]

hive > select split('888|666|544','\\|')[1];
OK
666

hive > select explode(split('888|666|544','\\|'));
OK
888
666
544

替换

1. 直接替换

replace(string1, pattern1, pattern2)
在字符串string1中匹配pattern1,并将所有匹配项替换成pattern2。

hive > select replace('abcd','b','c');
OK
accd

2. 正则替换

Return Type Name(Signature) Description
string regexp_extract(string subject, string pattern, int index) Returns the string extracted using the pattern. For example, regexp_extract(‘foothebar’, ‘foo(.*?)(bar)’, 2) returns ‘bar.’ Note that some care is necessary in using predefined character classes: using ‘\s’ as the second argument will match the letter s; ‘\s’ is necessary to match whitespace, etc. The ‘index’ parameter is the Java regex Matcher group() method index. See docs/api/java/util/regex/Matcher.html for more information on the ‘index’ or Java regex group() method…抽取字符串subject中符合正则表达式pattern的第index个部分的子字符串,注意些预定义字符的使用,如第二个参数如果使用’\s’将被匹配到s,’\s’才是匹配空格

正则匹配

Return Type Name(Signature) Description
string regexp_extract(string subject, string pattern, int index) Returns the string extracted using the pattern. For example, regexp_extract(‘foothebar’, ‘foo(.*?)(bar)’, 2) returns ‘bar.’ Note that some care is necessary in using predefined character classes: using ‘\s’ as the second argument will match the letter s; ‘\s’ is necessary to match whitespace, etc. The ‘index’ parameter is the Java regex Matcher group() method index. See docs/api/java/util/regex/Matcher.html for more information on the ‘index’ or Java regex group() method…抽取字符串subject中符合正则表达式pattern的第index个部分的子字符串,注意些预定义字符的使用,如第二个参数如果使用’\s’将被匹配到s,’\s’才是匹配空格

注意点:

  1. hive转义符需要写两个\;
  2. index的数字不能大于表达式中()的个数,否则报错。

正则表达式的符号及意义

符号 描述
^ 匹配一个输入或一行的开头,/^a/匹配"an A",而不匹配"An a"
$ 匹配一个输入或一行的结尾,/a$/匹配"An a",而不匹配"an A"
* 匹配前面元字符0次或多次
+ 匹配前面元字符1次或多次
? 匹配前面元字符0次或1次
x|y 匹配x或y
{n} 精确匹配n次
{n,} 匹配n次以上
{n,m} 匹配n-m次
[xyz] 字符集(character set),匹配这个集合中的任一一个字符(或元字符)
[^xyz] 不匹配这个集合中的任何一个字符
/d 匹配一个字数字符,//d/ = /[0-9]/
/D 匹配一个非字数字符,//D/ = /[^0-9]/
/w 匹配一个可以组成单词的字符(alphanumeric,这是我的意译,含数字),包括下划线,如[/w]匹配"$5.98"中的5,等于[a-zA-Z0-9]
/W 匹配一个不可以组成单词的字符,如[/W]匹配" 5.98 " 中 的 5.98"中的 5.98",等于[^a-zA-Z0-9]。
/s 匹配一个空白字符,包括/n,/r,/f,/t,/v等
/S 匹配一个非空白字符,等于/[^/n/f/r/t/v]/
/t 匹配一个制表符

贪婪匹配 vs 非贪婪匹配

贪婪匹配 (.*):匹配符合条件的最大长度;
非贪婪匹配 (.*?):匹配符合条件的最小长度。

举例如下:
从字符串"888|666|544"中提取竖线 | 前面的内容,但是在这个字符串中,竖线的个数不是固定的 。

贪婪模式,(.*) 匹配到最后一个竖线前的内容。

hive > select regexp_extract('888|666|544','(.*)\\|',1);
OK
888|666

非贪婪模式,(.*?) 匹配到第一个竖线前的内容。

hive > select regexp_extract('888|666|544','(.*?)\\|',1);
OK
888

JSON字符串解析

Return Type Name(Signature) Description
string get_json_object(string json_string, string path) Extracts json object from a json string based on json path specified, and returns json string of the extracted json object. It will return null if the input json string is invalid. NOTE: The json path can only have the characters [0-9a-z_], i.e., no upper-case or special characters. Also, the keys cannot start with numbers. This is due to restrictions on Hive column names…从指定路径上的JSON字符串抽取出JSON对象,并返回这个对象的JSON格式,如果输入的JSON是非法的将返回NULL,注意此路径上JSON字符串只能由数字 字母 下划线组成且不能有大写字母和特殊字符,且key不能由数字开头,这是由于Hive对列名的限制
tuple json_tuple(jsonStr, k1, k2, …) Takes a set of names (keys) and a JSON string, and returns a tuple of values. This is a more efficient version of the get_json_object UDF because it can get multiple keys with just one call…从一个JSON字符串中获取多个键并作为一个元组返回,与get_json_object不同的是此函数能一次获取多个键值

1. get_json_object()

函数的作用:用来解析json字符串的一个字段。

JSONPath

JSONPath 是xpath在json的应用,JSONPath表达式通常是用来路径检索或设置Json的。

符号 描述
$ 根节点对象
. 子节点
[ ] 数组索引

当指定的JsonPath不存在时,返回NULL。

hive > select * from tmp_json;
OK
{"store":{"fruit":[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}],"bicycle":{"price":19.95,"color":"red"}},"email":"amy@only_for_json_udf_test.net","owner":"amy"}

hive > SELECT get_json_object(json_str, '$.owner') FROM tmp_json;
OK
amy

hive (jj_tmp)> SELECT get_json_object(json_str, '$.store.fruit[0]') FROM tmp_json;
OK
{"weight":8,"type":"apple"}

2. json_tuple()

函数的作用:用来解析json字符串中的多个字段。
当使用json_tuple对象时,可以显著提高效率,一次获取多个对象并且可以被组合使用,写法如下。
其中,需要使用lateral view 视图方法来写,不需要加$标示符读取对象。
json_tuple()函数可以通过套用多层lateral view来提取子节点数据,但是好像没有内置函数像get_json_object()中那样来处理json array中的数据元素。

hive > select b.owner, b.email, d.*
     > from tmp_json a
     > lateral view json_tuple(a.json_str, 'owner', 'email','store') b as owner, email, store
     > lateral view json_tuple(b.store, 'bicycle') c as bicycle
     > lateral view json_tuple(c.bicycle, 'color', 'price') d as bicycle_color, bicycle_price
     > ;
OK
amy	amy@only_for_json_udf_test.net	red	19.95

3. str_to_map()

Return Type Name(Signature) Description
map str_to_map(text[, delimiter1, delimiter2]) Splits text into key-value pairs using two delimiters. Delimiter1 separates text into K-V pairs, and Delimiter2 splits each K-V pair. Default delimiters are ‘,’ for delimiter1 and ‘=’ for delimiter2. 将字符串str按照指定分隔符转换成Map,第一个参数是需要转换字符串,第二个参数是键值对之间的分隔符,默认为逗号;第三个参数是键值之间的分隔符,默认为"="

使用两个分隔符将文本拆分为键值对。 Delimiter1将文本分成K-V对,Delimiter2分割每个K-V对。对于delimiter1默认分隔符是’,’,对于delimiter2默认分隔符是’=’。
转换成map后用 [‘key’] 选取key对应的value。

hive > select str_to_map('aaa:11,bbb:22', ',', ':');
OK
{"bbb":"22","aaa":"11"}

hive > select str_to_map('aaa:11,bbb:22', ',', ':')['aaa'];
OK
11

你可能感兴趣的:(Hive)