Hive Lateral View explode列为空时导致数据异常丢失

一、问题描述

日常工作中我们经常会遇到一些非结构化数据,因此常常会将Lateral View 结合explode使用,达到将非结构化数据转化成结构化数据的目的,但是该方法对应explode的内容是有非null限制的,否则就有可能造成数据缺失。

sql 复制代码
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,这样无法关联出数据,该数据就会丢失。

三、解决办法(建议使用方法二)

3.1 方法一

对子查询中的split结果强制使用coalesce()方法,将null替换成一个为['']的数组,直接这么写会误以为string字符串。我们可以使用split('','')构造出一个['']数组,改写后的语句如下

sql 复制代码
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 ;

请注意 '李四' 的结果为空字符,不是null。

3.2 方法二

使用官方提供的LATERAL VIEW OUTER来进行解决,该方法类似于left outer join,即如果explode出来的结果为null,也会保留记录,只不过对应字段为null,改写后的语句如下:

sql 复制代码
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.

为了保持代码的稳定性与数据的准确性,建议使用第二种方法。

相关推荐
WL_Aurora9 小时前
Hadoop HA高可用架构深度解析
大数据·hadoop·架构
Irene199110 小时前
Windows 11 WSL Ubuntu 环境:实际安装 Hive 踩坑实录
hive·windows·ubuntu
Irene199111 小时前
Windows 11 WSL Ubuntu 环境:实际安装 Hadoop 踩坑实录
linux·hadoop·ubuntu
Irene199111 小时前
(课堂笔记)Hive 分区、分桶与数据倾斜
hive·hadoop
Irene19911 天前
在 WSL Ubuntu 上安装和使用 Hive
linux·hive·ubuntu
二宝哥1 天前
大数据之安装Hadoop3.1.4
大数据·hadoop
Irene19911 天前
Windows 11 WSL Ubuntu 环境:安装 Hadoop 完整指南
hadoop·ubuntu
Irene19912 天前
(课堂笔记)Hive 基础
hive·hadoop
nassi_2 天前
对AI工程问题的一些思考
大数据·人工智能·hadoop
云策数链2 天前
ERP报表系统设计与数据仓库
数据仓库·erp·用友·云策数链