Convert a column from list to array and array to list in hive using hql

Viewed 240

I want to convert the following column from list to array using hql

list array
[10:20] [10,20]
[30:40:50] [30,40,50]

and I also want to convert it from array to list

array list
[10,20] [10:20]
[30,40,50] [30:40:50]
1 Answers

Array to list demo:

with mytable as (
select stack (2,
array(10,20),
array(30,40,50)
) as myarray
)

select myarray, concat('[',concat_ws(':',collect_list(string(element))),']') as list
  from mytable
       lateral view explode(myarray) e as element
       group by myarray;

Result:

myarray     list
[10,20]     [10:20]
[30,40,50]  [30:40:50]

List to array demo:

with mytable as (
select stack (2,
'[10:20]',
'[30:40:50]'
) as list
)

select list, collect_list(int(element)) myarray
  from mytable
       lateral view explode (split(regexp_replace(list,'\\[|\\]',''),':')) e as element
  group by list;

Result:

list        myarray
[30:40:50]  [30,40,50]
[10:20]     [10,20]

If you are okay with array<string>, then conversion is much simpler:

with mytable as (
select stack (2,
'[10:20]',
'[30:40:50]'
) as list
)

select list, split(regexp_replace(list,'\\[|\\]',''),':') myarray
  from mytable;

Result:

list        myarray
[10:20]     ["10","20"]
[30:40:50]  ["30","40","50"]
Related