剥离 Hive 中的空格

Stripping whitespace in Hive

考虑以下 table、tab

id   fruits
1    orange, banana
2    orange
3    apple, banana, grape

我想 "explode" 这个 table 在 fruits 列:

select

id
individual_fruit

from tab

lateral view explode(split(fruits, ',')) the_fruits as individual_fruit

这给了我这个:

id individual_fruit
1  orange
1   banana
2  orange
3  apple
3   banana
3   grape

其中几行中的前导空格使得很难将这个新 table 与其他 table 连接起来。如何去除新 fruit 列中的空格?我习惯了 Python,而 Hive 的某些部分似乎 Python-esque,所以像 map(str.strip, individual_fruit)) 这样的东西对我来说很有意义(但这显然在 Hive 中不起作用!)。

有几种方法可以解决我的问题。

您可以使用 translate:

translate(individual_fruit, ' ', '')

但这只适用于字符串中只有空格的情况。当包含其他空白类型时,这种方法会变得很麻烦。

或者,使用 trim 删除所有前导和尾随空格

trim(individual_fruit)

我确定还有其他方法可以解决此问题,也许使用 regexp_replace,但我的问题已通过上述方法得到解答。

split 第二个参数是正则表达式

select  t.id
       ,f.individual_fruit

from    tab t
        lateral view explode(split(fruits, '\s*,\s*')) f as individual_fruit
;

+-----+-------------------+
| id  | individual_fruit  |
+-----+-------------------+
| 1   | orange            |
| 1   | banana            |
| 2   | orange            |
| 3   | apple             |
| 3   | banana            |
| 3   | grape             |
+-----+-------------------+