如何使用猪中的管道分隔符将字符串数据拆分为数组?

How to split string data to array using pipe delimiter in pig?

我正在尝试编写获取字符串数据的 pig 脚本,如下所示:abc|def|xyz 并尝试将这些值放入字符串数组中。

如何拆分此字符串以获得像 [abc,def,xyz] 这样的字符串数组?

我尝试使用 STRSPLIT 函数,但在我的情况下拆分次数不固定。管道分隔值的数量可能会有所不同,我需要所有这些值都在该数组中。

有什么建议吗???

您的方向是正确的,但是 STRSPLIT 有一件事您没有注意到。当拆分数不固定时,您也可以使用它。该 UDF 的第三个参数是您拥有的 'splits' 的数量,但您可以传递一个负数,它会查找与您的表达式匹配的所有可能的拆分。

来自official documentation for STRSPLIT

limit

If the value is positive, the pattern (the compiled representation of the regular expression) is applied at most limit-1 times, therefore the value of the argument means the maximum length of the result tuple. The last element of the result tuple will contain all input after the last match.

If the value is negative, no limit is applied for the length of the result tuple.

想象一下这个输入:

abc|def|xyz,1
abc|def|xyz|abc|def|xyz,2

您可以执行以下操作:

A = load 'data.txt' using PigStorage(',');
B = foreach A generate STRSPLIT([=11=],'\|',-1);

输出将是:

DUMP B;

((abc,def,xyz))
((abc,def,xyz,abc,def,xyz))

另一个可行的选择是使用 TOKENIZE。建议采用@Balduz 建议的解决方案。

A = load 'data.txt' using PigStorage(',');
B = foreach A generate BagToString(TOKENIZE([=10=],'|'),',');
DUMP B;

输出:DUMP B:

(abc,def,xyz)
(abc,def,xyz,abc,def,xyz)