【问题标题】:Loading CSV file on Hive Table with String Array使用字符串数组在 Hive 表上加载 CSV 文件
【发布时间】:2023-04-02 00:30:01
【问题描述】:

我正在尝试将一个 CSV 文件插入 Hive,其中一个字段是字符串数组。

这是 CSV 文件:

48,Snacks that Power Up Weight Loss,Aidan B. Prince,[Health&Fitness,Travel]
99,Snacks that Power Up Weight Loss,Aidan B. Prince,[Photo,Travel]

我尝试创建类似这样的表:

CREATE TABLE IF NOT EXISTS Article
(
ARTICLE_ID INT,
ARTICLE_NSAME STRING,
ARTICLE_AUTHOR STRING,
ARTICLE_GENRE ARRAY<STRING>
);
LOAD DATA INPATH '/tmp/pinterest/article.csv' OVERWRITE INTO TABLE Article;
select * from Article;  

这是我得到的输出:

article.article_id  article.article_name    article.article_author  article.article_genre
48  Snacks that Power Up Weight Loss    Aidan B. Prince ["[Health&Fitness"]
99  Snacks that Power Up Weight Loss    Aidan B. Prince ["[Photo"]

它在最后一个字段 article_genre 中只取一个值。

有人能指出这里有什么问题吗?

【问题讨论】:

  • 我现在不在我的沙箱附近,所以我不能告诉你正确的答案,但我可以告诉你它正在将输入行中的逗号视为新列 - 即使在您希望被视为数组的字段。因此,在您加载的第一行中,[Health&amp;Fitness 存储为ARTICLE_GENRE,而“新列”Travel] 将被忽略。您的第四列不是 Hive 期望的数组格式。

标签: csv hadoop hive


【解决方案1】:

几样东西:
您缺少集合项目分隔符的定义。
另外,我假设您希望 you select * from article 语句返回如下:

48  Snacks that Power Up Weight Loss    Aidan B. Prince ["Health&Fitness","Travel"]
99  Snacks that Power Up Weight Loss    Aidan B. Prince ["Photo","Travel"]

我可以给你一个例子,剩下的你可以摆弄它。 这是我的表定义:

create table article (
  id int,
  name string,
  author string,
  genre array<string>
)
row format delimited
fields terminated by ','
collection items terminated by '|';

这是数据:

48,Snacks that Power Up Weight Loss,Aidan B. Prince,Health&Fitness|Travel
99,Snacks that Power Up Weight Loss,Aidan B. Prince,Photo|Travel

现在执行如下加载:
LOAD DATA local INPATH '/path' OVERWRITE INTO TABLE article; 并执行 select 语句以检查结果。

最重要的一点
为集合项定义分隔符,不要强加您在正常编程中所做的数组结构。
另外,尽量使字段分隔符与集合项分隔符不同,以避免混淆和意外结果。

【讨论】:

  • 优秀的答案!非常感谢。您能否建议如何为地图数据执行此操作?例如,我的 hive 表中有一个 map&lt;string,string&gt; 列,我想创建一个 csv 文件来将数据加载到我的表中。地图数据在 csv 中应该是什么样子?
【解决方案2】:

为了在 Hive 表中插入字符串数组,我们需要注意以下几点。

 1. While creating Hive table.Collection items should be terminated by "," ('colelction.delim'=',',)
 2. Data should be like that in CSV file
  48  Snacks that Power Up Weight Loss    Aidan B. Prince Health&Fitness,Travel
You can modify file  by running below SED commands in follwing order:
 - sed -i 's/\[\"//g' filename
 - sed -i 's/\"\]//g' filename
 - sed -i 's/"//g' filename

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多