Hive在引用字段中使用逗号加载CSV

时间:2012-11-29 15:05:58

标签: hadoop hbase hive hdfs delimiter

我正在尝试将CS​​V文件加载到Hive表中,如下所示:

CREATE TABLE mytable
(
num1 INT,
text1 STRING,
num2 INT,
text2 STRING
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ",";

LOAD DATA LOCAL INPATH '/data.csv'
OVERWRITE INTO TABLE mytable;    


csv由逗号(,)分隔,如下所示:

1, "some text, with comma in it", 123, "more text"

由于第一个字符串中有',',因此会返回损坏的数据 有没有办法设置文本分隔符或让Hive忽略字符串中的','?

我无法更改csv的分隔符,因为它是从外部源中提取的。

6 个答案:

答案 0 :(得分:29)

问题是Hive无法处理引用的文本。您需要通过更改字段之间的分隔符来预处理数据(例如:使用Hadoop流式处理作业),或者您也可以尝试使用使用OpenCSV解析文件的自定义CSV SerDe

答案 1 :(得分:29)

如果您可以重新创建或解析输入数据,则可以为CREATE TABLE指定转义字符:

ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';

将此行视为4个字段

1,some text\, with comma in it,123,more text

答案 2 :(得分:20)

从Hive 0.14开始,CSV SerDe是Hive安装的标准部分

ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'

(参见:https://cwiki.apache.org/confluence/display/Hive/CSV+Serde

答案 3 :(得分:0)

将分隔符保留在单引号中,它将起作用。

ROW FORMAT DELIMITED 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';

这将有效

答案 4 :(得分:0)

在FIELDS TERMINATED BY'\;'

中添加反斜杠

例如:

CREATE  TABLE demo_table_1_csv
COMMENT 'my_csv_table 1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\;'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'your_hdfs_path'
AS 
select a.tran_uuid,a.cust_id,a.risk_flag,a.lookback_start_date,a.lookback_end_date,b.scn_name,b.alerted_risk_category,
CASE WHEN (b.activity_id is not null ) THEN 1 ELSE 0 END as Alert_Flag 
FROM scn1_rcc1_agg as a LEFT OUTER JOIN scenario_activity_alert as b ON a.tran_uuid = b.activity_id;

我已经测试了它,但它确实有效。

答案 5 :(得分:0)

ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE Serde为我工作。我的分隔符是“ |”并且其中一列用双引号引起来。

查询:

CREATE EXTERNAL TABLE EMAIL(MESSAGE_ID STRING, TEXT STRING, TO_ADDRS STRING, FROM_ADDRS STRING, SUBJECT STRING, DATE STRING)
ROW FORMAT SERDE 'ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE'
WITH SERDEPROPERTIES (
     "SEPARATORCHAR" = "|",
     "QUOTECHAR"     = "\"",
     "ESCAPECHAR"    = "\""
)    
STORED AS TEXTFILE location '/user/abc/csv_folder';