首页 > 解决方案 > 如何在蜂巢中的管道分隔符后获取第 N 个字符串

问题描述

我在 Hive 中有一个表,我想从其中一个看起来像这样的列中提取字符串的第 5 个分量 -

样本数据

john:12|doe|google|usa|google.com|newspaper - title - 1 - volume - 1234|360671191
john:34|doe|fb|usa|google.com|newspaper - title - X - volume - 1233|360671192
john:45|doe|twitter|usa|google.com|newspaper - title - Y - volume - 1232|360671193
jane:45:1323

我想在第一个管道字符(|)之后解析出第 5 个字符串。输出列的值为 -

newspaper - title - 1 - volume - 1234
newspaper - title - X - volume - 1233
newspaper - title - Y - volume - 1232
jane:45:1323

如果标题不存在(如在记录 4 中),则我们按原样返回原始字符串。

标签: hive

解决方案


使用拆分功能,如下所示:

with your_data as (
select stack(4,
'john:12|doe|google|usa|google.com|newspaper - title - 1 - volume - 1234|360671191',
'john:34|doe|fb|usa|google.com|newspaper - title - X - volume - 1233|360671192',
'john:45|doe|twitter|usa|google.com|newspaper - title - Y - volume - 1232|360671193',
'jane:45:1323'
) as str
)

select nvl(splitted_str[5], original_str) result
 from
(
select split(str,'\\|') splitted_str, str original_str 
  from your_data
)s;

回报:

newspaper - title - 1 - volume - 1234   
newspaper - title - X - volume - 1233   
newspaper - title - Y - volume - 1232   
jane:45:1323    

推荐阅读