How to flatten a group into a single tuple in Pig?

user2730009 picture user2730009 · Aug 31, 2013 · Viewed 46.9k times · Source

From this:

(1, {(1,2), (1,3), (1,4)} )
(2, {(2,5), (2,6), (2,7)} )

...How could we generate this?

((1,2),(1,3),(1,4))
((2,5),(2,6),(2,7))

...And how could we generate this?

(1, 2, 3, 4)
(2, 5, 6, 7)

For a single row I know how to do. The problem is when I have to iterate over many rows AND manipulate internal groups at the same time.

Answer

zsxwing picture zsxwing · Aug 31, 2013

For your question, I prepared the following file:

1,2
1,3
1,4
2,5
2,6
2,7

At first, I used the following script to get the input r3 which you described in your question:

r1 = load 'test_file' using PigStorage(',') as (a:int, b:int);
r2 = group r1 by a;
r3 = foreach r2 generate group as a, r1 as b;
describe r3;
-- r3: {a: int,b: {(a: int,b: int)}}
-- r3 is like (1, {(1,2), (1,3), (1,4)} )

If we want to generate the following content,

(1, 2, 3, 4)
(2, 5, 6, 7)

we can use the following script:

r4 = foreach r3 generate a, FLATTEN(BagToTuple(b.b));
dump r4;

For the following content,

((1,2),(1,3),(1,4))
((2,5),(2,6),(2,7))

I can not find any helpful builtin function. Maybe you need to write your custom BagToTuple. Here is the builtin BagToTuple source codes: http://www.grepcode.com/file/repo1.maven.org/maven2/org.apache.pig/pig/0.11.1/org/apache/pig/builtin/BagToTuple.java#BagToTuple.getOuputTupleSize%28org.apache.pig.data.DataBag%29