hive - 将代码字符串翻译成 hive 中的 desc
问题描述
这里我们有一个带连字符的字符串,例如0-1-3
.... 并且长度不固定,而且我们在 hive 中有一个 DETAIL 表来解释每个代码的含义。
DETAIL
| code | desc |
+ ---- + ---- +
| 0 | AAA |
| 1 | BBB |
| 2 | CCC |
| 3 | DDD |
现在我们需要一个配置单元查询来将代码字符串转换为描述字符串。
例如:案例0-1-3
应该得到一个字符串,如AAA-BBB-DDD
.
关于如何获得的任何建议?
解决方案
Split
您的字符串以获取数组、explode
数组并与详细表连接(在我的示例中使用 CTE 而不是它,使用普通表代替)以使 desc 与代码连接。然后使用来组装字符串collect_list(desc)
以获取数组 +concat_ws()
以获取连接字符串:
select concat_ws('-',collect_list(d.desc)) as code_desc
from
( --initial string explode
select explode(split('0-1-3','-')) as code
) s
inner join
(-- use your table instead of this subquery
select 0 code, 'AAA' desc union all
select 1, 'BBB' desc union all
select 2, 'CCC' desc union all
select 3, 'DDD' desc
) d on s.code=d.code;
结果:
OK
AAA-BBB-DDD
Time taken: 114.798 seconds, Fetched: 1 row(s)
如果您需要保留原始顺序,则使用posexplode
它返回元素及其在原始数组中的位置。然后您可以通过记录 ID 和 pos before 进行排序collect_list()
。
如果您的字符串是表格列,则使用横向视图来选择分解值。
这是一个更复杂的示例,具有保留顺序和横向视图。
select str as original_string, concat_ws('-',collect_list(s.desc)) as transformed_string
from
(
select s.str, s.pos, d.desc
from
( --initial string explode with ordering by str and pos
--(better use your table PK, like ID instead of str for ordering), pos
select str, pos, code from ( --use your table instead of this subquery
select '0-1-3' as str union all
select '2-1-3' as str union all
select '3-2-1' as str
)s
lateral view outer posexplode(split(s.str,'-')) v as pos,code
) s
inner join
(-- use your table instead of this subquery
select 0 code, 'AAA' desc union all
select 1, 'BBB' desc union all
select 2, 'CCC' desc union all
select 3, 'DDD' desc
) d on s.code=d.code
distribute by s.str -- this should be record PK candidate
sort by s.str, s.pos --sort on each reducer
)s
group by str;
结果:
OK
0-1-3 AAA-BBB-DDD
2-1-3 CCC-BBB-DDD
3-2-1 DDD-CCC-BBB
Time taken: 67.534 seconds, Fetched: 3 row(s)
请注意,使用的是distribute
+sort
而不是简单的order by str, pos
。分发 + 排序在完全分布式模式下order by
工作,也可以正确工作,但在单个减速器上。