在 Hive/Presto 中将文件路径拆分为其组成路径

split a file path into its constituent paths in Hive/Presto

使用 Presto/Hive,我想按以下方式拆分字符串。

输入字符串:

\Users\Killer\Downloads\Temp
\Users\Killer\Downloads\welcome

并查询 return 这些行:

\Users\
\Users\Killer\
\Users\Killer\Downloads\
\Users\Killer\Downloads\Temp
\Users\
\Users\Killer\
\Users\Killer\Downloads\
\Users\Killer\Downloads\welcome

谁能帮帮我。

这可以完成这项工作:

SELECT item, array_join( array_agg(item) over (order by id), '\' )
FROM UNNEST(split('\Users\Killer\Downloads\Temp','\')) WITH ORDINALITY t(item,id)

解释:

我们首先 split 通过分隔符 \ 将 sting 到一个数组,然后我们 UNNEST 将这个数组分成行,每个项目一行。之后我们对所有项目执行 array_agg 直到该行 ID(window 函数的“滚动”聚合),最后我们 array_join 使用 \ 分隔符将它们返回。

Hive 的解决方案。拆分得到数组,使用 posexplode 分解数组,使用分析函数再次收集数组并连接(文字 \ 应该用一个反斜杠屏蔽 - \ 并且在拆分中使用的正则表达式中,单个反斜杠表示为四个反斜杠):

select s.level, 
        concat(concat_ws('\',collect_set(s.path) over(order by level rows between unbounded preceding and current row)),
              case when level<size(split(t.str,'\\'))-1  then '\' else '' end 
             ) result
  from mytable t lateral view posexplode(split(t.str,'\\')) s as level, path

结果:

level   result
0         \
1         \Users\
2         \Users\Killer\
3         \Users\Killer\Downloads\
4         \Users\Killer\Downloads\Temp