1. cast(字段 as 需要转化为的类型)

举例:有一个test表,其中有三个字段

select cast(age as bigint) as col1 from test limit  100;

查询的SQL中使用了cast(age as int)表示我将表中原本类型为int的值转为bigint类型,类似于强制类型转换

注:从Hive0.12.0开始支持varchar

2. get_json_object(字段, '$.字段的字段')或get_json_object(字段, '$.字段的字段[i]')

举例:还是test表,现在有四个字段

其中introduce字段中存储的值都是如下格式:

{
    "col1":"hello world",
    "col2":[1,2],
    "col3":{
        "col31":"key1",
        "col32":"key2"
    }
}

单层:select get_json_object(introduce, '$.col1') from test;

解释:其中get_json_object(introduce, '$.col1')表示从introduce字段中取出名为col1对应的值,即"hello world"

嵌套:select get_json_object(introduce, '$.col3.col31') from test;

解释:其中get_json_object(introduce, '$.col3.col31')表示从introduce字段中取出名为col3中col31对应的值,即"key1"

数组:select get_json_object(introduce, '$.col2[1]') from test;

解释:其中get_json_object(introduce, '$.col2[1]')表示从introduce字段中取出名为col2数组中第二个值,即1

3. date_format(FROM_UNIXTIME(表的某个数值,必须是秒级别), '要求转为的格式')

举例:test表,现在有两个字段

time_stamp存储了秒级别的时间戳(如果是bigint,存储了毫秒级别的时间戳,将值/1000转为秒级别即可)

select cast(date_format(FROM_UNIXTIME(time_stamp), 'yyyyMM') as int) as day from test;

解释:其中FROM_UNIXTIME会将时间由数字转为日期,然后使用date_format将该日期转为'yyyyMM'类型的数据,最后使用cast将该字段类型转为int。

4. replace(进行操作的字段, '字段中需要被替换的部分', '替换后的部分')

举例:test表,现在有两个字段

select replace(name, '·', '') as rep from test

解释:将test表中的name字段中·全部替换掉。

5. split(需要被拆分成数据的字段, '字段被拆分成array的中间点')

举例:test表,现在有两个字段

select split(name, '!') as arr from test

解释:如果name字段中的值有【!】,比如【hello!world】那么会被拆成一个包含有两个值的array:["hello", "world"]

6. explode(需要被行转列的array)

还是上面的例子,现在的表具体为:

select id, explode(split(name, ',')) as exp from test

执行后为

 解释:explode函数会将一个array或是map从一行拆为多行,即由行转列

注:仅使用explode的局限:

  1. 不能关联原有的表中的其他字段。
  2. 不能与group by、cluster by、distribute by、sort by联用。
  3. 不能进行UDTF嵌套。
  4. 不允许选择其他表达式。

7. lateral view udtf函数 tableAlias AS columnAlias

lateral view 要与UDTF(user defined table-generating functions)函数一起使用,这里的udft用上面的explode举例,lateral view 会将utdf函数应用到每一行上,经utdf处理后得到多行输出组建成一张虚拟表。

还是这张表:

SELECT id, name
FROM test LATERAL VIEW explode(split(name, ',')) test_demo AS exp;

解释: LATERAL VIEW会将经过UDTF函数处理的内容投射到一张虚拟表上,我们就可以再对这个虚拟表进行各种操作了。

11-02 07:09