如何在Trino中将Map(varchar,varchar)类型转换为字符串?
解决Map(varchar,varchar)转"key"=>"value"格式字符串的问题
Spark SQL 实现方案
利用map_entries将Map转为键值对数组,再通过transform遍历处理每个键值对,最后用concat_ws拼接成目标格式:
SELECT concat_ws( ',', transform( map_entries(your_map_column), entry -> concat('"', entry.key, '"=>"', entry.value, '"') ) ) AS formatted_str FROM your_table;
如果键或值中包含双引号,需要先转义避免格式混乱,修改后的代码:
SELECT concat_ws( ',', transform( map_entries(your_map_column), entry -> concat( '"', replace(entry.key, '"', '\\"'), '"=>"', replace(entry.value, '"', '\\"'), '"' ) ) ) AS formatted_str FROM your_table;
Hive SQL 实现方案
Hive不支持transform,可以通过explode拆分Map为多行键值对,拼接后再聚合:
SELECT concat_ws(',', collect_list(concat('"', key, '"=>"', value, '"'))) AS formatted_str FROM your_table LATERAL VIEW explode(your_map_column) exploded AS key, value -- 必须加上原表中除map列外的所有列作为分组条件 GROUP BY id, other_columns;
同样处理双引号转义的版本:
SELECT concat_ws(',', collect_list( concat( '"', replace(key, '"', '\\"'), '"=>"', replace(value, '"', '\\"'), '"' ) )) AS formatted_str FROM your_table LATERAL VIEW explode(your_map_column) exploded AS key, value GROUP BY id, other_columns;
内容的提问来源于stack exchange,提问作者Cherry
相关产品推荐
相关产品推荐

