日常工作中我们经常会遇到一些非结构化数据,因此常常会将Lateral View 结合explode使用,达到将非结构化数据转化成结构化数据的目的,但是该方法对应explode的内容是有非null限制的,否则就有可能造成数据缺失。
SELECT name,info
FROM
(
SELECT name,
split(info_list,',') as info_arrary
FROM
(
select '张三' as name,'1,2,3' as info_list
union all
select '李四' as name,null as info_list
) t1 -- 构造测试数据
) t2
LATERAL VIEW explode(t2.info_arrary) a as info ;
查看结果我们可以发现 ‘李四’ 这条数据数据丢了,这就会造成我们最终统计的数据出现错误。
通过定位我们可以发现 ‘李四’ 这一行的info字段为null,其split之后的结果自然也是为null,通过LATERAL VIEW explode之后会形成一个为null的view,这样无法关联出数据,该数据就会丢失。
对子查询中的split结果强制使用coalesce()方法,将null替换成一个为[’’]的数组,直接这么写会误以为string字符串。我们可以使用split(’’,’’)构造出一个[’’]数组,改写后的语句如下
SELECT name,info
FROM
(
SELECT name,
coalesce(split(info_list,','),split('','')) as info_arrary
FROM
(
select '张三' as name,'1,2,3' as info_list
union all
select '李四' as name,null as info_list
) t1 -- 构造测试数据
) t2
LATERAL VIEW OUTER explode(t2.info_arrary) a as info ;
使用官方提供的LATERAL VIEW OUTER来进行解决,该方法类似于left outer join,即如果explode出来的结果为null,也会保留记录,只不过对应字段为null,改写后的语句如下:
SELECT name,info
FROM
(
SELECT name,
split(info_list,',') as info_arrary
FROM
(
select '张三' as name,'1,2,3' as info_list
union all
select '李四' as name,null as info_list
) t1 -- 构造测试数据
) t2
LATERAL VIEW OUTER explode(t2.info_arrary) a as info ;
请注意 ‘李四’ 的结果为null,而不是空字符。
以下是官方文档关于该用法的解释:
The user can specify the optional OUTER keyword to generate rows even when a LATERAL VIEW usually would not generate a row. This happens when the UDTF used does not generate any rows which happens easily with explode when the column to explode is empty. In this case the source row would never appear in the results. OUTER can be used to prevent that and rows will be generated with NULL values in the columns coming from the UDTF.
为了保持代码的稳定性与数据的准确性,建议使用第二种方法。