HIVE踩坑——NULL和空字符串处理
这⾥我们针对在HIVE中遇到的NULL和空字符串问题进⾏简单探讨,避免踩坑
简单探索
⾸先新建⼀张测试表test_01,⽤作后续测试
CREATE TABLE IF NOT EXISTS `test_01`(
`id` INT, `name` STRING,`age` INT, `score` FLOAT)
ROW FORMAT DELIMITED FIELDS TERMINATED BY',' STORED AS TEXTFILE;
新增简单的⼏条测试数据,具体如下
insert overwrite  table test_01
select NULL,NULL,10,95
union all select2 ,'',10,95
union all select3 ,'Lucy',15,NULL
union all select4,'Jack',15,100;
查看新增数据
hive (tmp)>select*from test_01;
OK
NULL NULL1095.0
21095.0
3        Lucy    15NULL
4        Jack    15100.0
底层HDFS⽂件默认存储格式
[root@nd2 wh]# hadoop fs -cat /user/hive/warehouse/tmp.db/test_01/000000_0
\N,\N,10,95.0
2,,10,95.0
3,Lucy,15,\N
4,Jack,15,100.0
得出结论:
默认情况下,STRING类型的数据如果为" “,底层HDFS⽂件默认存储则是” ";
INT与STRING等类型的数据如果为NULL,底层HDFS默认默认存储为 \N;
这⾥我们根据name条件查询
--条件为 name is null
hive (tmp)>select*from test_01 where name is null;
NULL NULL1095.0
-
-条件为name = ''
hive (tmp)>select*from test_01 where name ='';
21095.0
--条件为id is null
hive (tmp)>select*from test_01 where id is null;
NULL NULL1095.0
可以得出结论:
默认情况下,对于INT可以使⽤is null来判断空;
⽽对于STRING类型,条件is null 查出来的是\N的数据;⽽条件 =" “,查询出来的是” "的数据。
实际情况
在HIVE使⽤中,很多时候我们可能需要使⽤底层HDFS⽂件⽤作数据存储或其它数据迁移,备份。这个时候底层HDFS⽂件中\N和" "处理就显得很重要了(不同的应⽤可能对底层⽂件处理不⼀样)。
在HIVE中,⼀般我们会在新建表之后执⾏
--⾃定义底层⽤什么字符来表⽰NULL。这⾥⽤''来表⽰。换句话说就是让null和''等价,底层HDFS让null不显⽰。
ALTER TABLE test_01 SET SERDEPROPERTIES ('serialization.null.format'='');
我们重新插⼊数据,查询结果
hive (tmp)>select*from test_01;
OK
NULL NULL1095.0
2NULL1095.0
3        Lucy    15NULL
4        Jack    15100.0
底层HDFS⽂件存储的数据格式为
[root@nd2 wh]# hadoop fs -cat /user/hive/warehouse/tmp.db/test_01/000000_0
,,10,95.0
2,,10,95.0
3,Lucy,15,
4,Jack,15,100.0
我们发现底层数据保存的是" ",通过查询显⽰的结果时NULL。
注意:
我们使⽤is null或者 = " “都是根据查询显⽰的结果进⾏过滤。⽽不是根据底层⽂件格式。查询空值⽤is null,如果⽤=” ",查询不到数据。
--条件为 name is null
默认字符串是什么hive (tmp)>select*from test_01 where name is null;
NULL NULL1095.0
2NULL1095.0
--条件为 name =''
hive (tmp)>select*from test_01 where name ='';
OK
Time taken: 4.058 seconds

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。