从列值生成 Hive 行

Posted

技术标签:

【中文标题】从列值生成 Hive 行【英文标题】:Hive rows generation from a column value 【发布时间】:2019-09-17 03:55:08 【问题描述】:

如何根据单个列值在 Hive 中生成行。例如,

我有下表数据。我需要生成相似的行(所有字段都相同),但所有列值都用于评分?

item_id   cost   rating
23        1290   0.08
14        1498   0.06

我需要如下所示的输出。

item_id   cost   rating
23        1290   0.08
23        1290   0.07
23        1290   0.06
23        1290   0.05
23        1290   0.04
23        1290   0.03
23        1290   0.02
23        1290   0.01
14        1498   0.06
14        1498   0.05
14        1498   0.04
14        1498   0.03
14        1498   0.02
14        1498   0.01

【问题讨论】:

【参考方案1】:

例如这样:

with initial_data as(
select stack(2,
23, 1290, 0.08,
14, 1498, 0.06
) as (item_id, cost, rating)
) 

select item_id, cost, (i+1)/100 as rating
from
(
select d.*, cast(d.rating*100 as int)-1 as n --the number of rows to generate
  from initial_data d
)s lateral view posexplode(split(space(s.n),' ')) e as i, x  --generate rows with numbers (i)
order by item_id desc, rating desc; --remove ordering for faster processing if you do not need ordered output

结果:

OK
23      1290    0.08
23      1290    0.07
23      1290    0.06
23      1290    0.05
23      1290    0.04
23      1290    0.03
23      1290    0.02
23      1290    0.01
14      1498    0.06
14      1498    0.05
14      1498    0.04
14      1498    0.03
14      1498    0.02
14      1498    0.01
Time taken: 74.993 seconds, Fetched: 14 row(s)

【讨论】:

以上是关于从列值生成 Hive 行的主要内容,如果未能解决你的问题,请参考以下文章

FlatMap 从列值到多行缺少架构

从列值中查找缺失的键 ID 或数字

根据相邻列值 Pandas 从列中按第一个或第二个空格提取字符串

在 INSERT SELECT 语句期间生成增量数值列值

使用 hive 生成​​ Parquet 文件

Hive 不读取 Spark 生成的分区 parquet 文件