0

我的输入是一个字符串,可以包含从 A 到 Z 的任何字符(没有重复,因此最多可以有 26 个字符)。

例如:-

set Input='ATK';

字符串中的字符可以按任何顺序出现。

现在我想创建一个映射对象,它将具有从AZ的固定键。如果对应的字符出现在输入字符串中,则键的值为 1。因此,在此示例(ATK)的情况下,地图对象应如下所示:-

地图对象

那么最好的方法是什么?

所以代码应该是这样的: -

set Input='ATK';
select <some logic>;

Map<string,int>它应该返回一个包含 26 个键值对的映射对象 ( )。最好的方法是什么,而不在 Hive 中创建任何用户定义的函数。我知道有一个很容易想到的函数str_to_map。但它只有在源字符串中存在键值对时才有效,而且它只会考虑输入中指定的键值对。

4

1 回答 1

1

也许效率不高但有效:

select str_to_map(concat_ws('&',collect_list(concat_ws(":",a.dict,case when 
b.character is null then '0' else '1' end))),'&',':')
from 
(
   select explode(split("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z",',')) as dict
) a 
left join
(
   select explode(split(${hiveconf:Input},'')) as character
) b 
on a.dict = b.character

结果:

{"A":"1","B":"0","C":"0","D":"0","E":"0","F":"0","G":"0","H":"0","I":"0","J":"0","K":"1","L":"0","M":"0","N":"0","O":"0","P":"0","Q":"0","R":"0","S":"0","T":"1","U":"0","V":"0","W":"0","X":"0","Y":"0","Z":"0"}
于 2020-10-26T09:13:51.257 回答