在 Hive 列中存储和查询空白值

问题描述

我需要在 Hive 表的某些列中存储长度为 1、2 和 3 的空白字符串。

存储:

  1. 如果我的列类型是 char,那么我看到数据总是在存储前被修剪。即长度(列)始终为 0
  2. 如果我的列类型是 varchar,则不会修剪数据。所以长度(列)分别是 1、2 和 3。 这样就解决了我的存储问题。

查询

  1. 我无法按值查询该列。 说。 select * from hive table where column = ' '; 它只有在我做类似的事情时才有效 select * from hive table where length(column) > 0 and trim(column) = '';

有没有办法单独处理这个问题? 说我想查询那些列值为长度为 3 的空字符串的记录?我该怎么做?

这就是我尝试过的(请注意,问题似乎出在文件存储为镶木地板时)

CREATE EXTERNAL TABLE IF NOT EXISTS DUMMY5 (
  col1 varchar(3)) 
  STORED AS PARQUET
LOCATION "/DUMMY5";

insert into DUMMY5 values ('  '); // 2 character strings
insert into DUMMY5 values ('   '); //3 character strings

select col1,length(col1) from DUMMY5;
+-------+------+--+
| col1  | _c1  |
+-------+------+--+
|       | 3    |
|       | 2    |
+-------+------+--+

select col1,length(col1) from DUMMY5 where col1 = '  '; // 0 record
select col1,length(col1) from DUMMY5  where col1 = '   '; // 0 record

解决方法

运行 Hive 2.1.1

drop table dummy_tbl;
CREATE TABLE  dummy_tbl (
  col1 char(1),col2 varchar(1),col3 char(3),col4 varchar(3)) ;
  
  insert into dummy_tbl values ('  ','  ','  ');
  
   select  length(col1),length(col2),length(col3),length(col4) from dummy_tbl;

结果:

c0  c1  c2  c3
0   1   0   2

Varchar 列绝对正确。 col2 是 trimmed on insert,it is documented。 col4 varchar(2) 工作正常,此查询返回 1:

 select count(*) from dummy_tbl where col4='  '; --returns 1

并且所有字符列的长度显示为 0 并且比较忽略空格,例如 documented

select  count(*) from dummy_tbl where col1=' '; --single space --returns 1
select  count(*) from dummy_tbl where col1='  '; --two spaces --also returns 1 because it is ignoring spaces

您可以使用具有适当长度的 varchar。或者,如果您不确定长度,请输入 STRING