user3111525
user3111525

Reputation: 5213

How to generate certain number of tuples in pig?

I have the following dataset:

A:

x1 y z1
x2 y z2
x3 y z3
x43 y z33
x4 y2 z4
x5 y2 z5
x6 y2 z6
x7 y2 z7

B:

y 12
y2 25

Loading A: LOAD '$input' USING PigStorage() AS (k:chararray, m:chararray, n:chararray); Loading B: LOAD '$input2' USING PigStorage() AS (o:chararray, p:int);

I am joining A on m and B on o. What I would like to do is to select only x number of tuples for each o. So, for example if x was 2 it the result is:

x1 y z1
x2 y z2
x4 y2 z4
x5 y2 z5

Upvotes: 1

Views: 287

Answers (1)

alexeipab
alexeipab

Reputation: 3619

To do that you need to use GROUP BY, FOREACH with a nested LIMIT and than JOIN or COGROUP. See implementation in Pig 0.10, I used you input data to get the specified output:

A = load '~/pig/data/subset_join_A.dat' as (k:chararray, m:chararray, n:chararray);
B = load '~/pig/data/subset_join_B.dat' as (o:chararray, p:int);
-- as join will be on m, we need to leave only 2 rows per a value in m.
group_A = group A by m;
top_A_x = foreach group_A {
    top = limit A 2; -- where x = 2
    generate flatten(top);
};

-- another way to do join, allows us to do left or right joins and checks
co_join = cogroup top_A_x by (m), B by (o);
-- filter out records from A that are not in B
filter_join = filter co_join by IsEmpty(B) == false;
result = foreach filter_join generate flatten(top_A_x);

Alternatively you can implement it with just a COGROUP, FOREACH with a nested LIMIT:

A = load '~/pig/data/subset_join_A.dat' as (k:chararray, m:chararray, n:chararray);
B = load '~/pig/data/subset_join_B.dat' as (o:chararray, p:int);

co_join = cogroup A by (m), B by (o);
filter_join = filter co_join by IsEmpty(B) == false;
result = foreach filter_join {
    top = limit A 2;
--you can limit B as well
    generate flatten(top);
};

Upvotes: 1

Related Questions