使用pig从键值中获取n个值

时间:2013-07-05 10:48:01

标签: hadoop map apache-pig

我有一个测试文件,其中键和值由昏迷分隔。如何使用pig脚本为每个键仅获取10个值。

示例输入:john | str1,str2,str3,str4,str5,str6,str7,str8,str9,str10,str11,str2 ,首选输出:john | str1,str2,str3,str4,str5,str6,str7,str8,str9,str10

1 个答案:

答案 0 :(得分:2)

有很多不同的方法可以做到这一点,具体取决于您输入的具体内容和输出需求。我假设你只想要前十个,其余的值可以被抛弃。

这就是我这样做的方式(CL)。它比短路(CF)稍微长一些,但代码对我来说更清晰,并且允许更灵活地命名模式:

A = LOAD 'myData' USING PigStorage('|') AS (name: chararray, vals: chararray) ;  
B = FOREACH A GENERATE name, STRSPLIT(vals, ',') AS svals: () ;  
CL = FOREACH B GENERATE name,
                        svals.($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) AS ten ; 
                        -- ten can have a schema, like ten: (a1: chararray, etc.)
                        -- After giving it a schema, you can also flatten it to
                        -- make it like the output of CF, but with better types

这是CL的结果模式和输出:

CL: {name: chararray,ten: ()}
(john,(str1,str2,str3,str4,str5,str6,str7,str8,str9,str10))

这种方式稍微短一些,但是将模式应用于值更难:

-- Uses the same A  
B = FOREACH A GENERATE name AS name, FLATTEN(STRSPLIT(vals, ',')) ;
CF = FOREACH B GENERATE $0 AS name: chararray, $1, $2 .. $10 ;

CF的架构和输出:

CF: {name: chararray,bytearray,bytearray,bytearray,bytearray,bytearray,bytearray,bytearray,bytearray,bytearray,bytearray}
(john,str1,str2,str3,str4,str5,str6,str7,str8,str9,str10)