Pig - how to iterate on a bag of maps

2019-07-14 07:34发布

问题:

Let me explain the problem. I have this line of code:

u = FOREACH persons GENERATE FLATTEN($0#'experiences') as j;
dump u;

which produces this output:

([id#1,date_begin#12 2012,description#blabla,date_end#04 2013],[id#2,date_begin#02 2011,description#blabla2,date_end#04 2013])
([id#1,date_begin#12 2011,description#blabla3,date_end#04 2012],[id#2,date_begin#02 2010,description#blabla4,date_end#04 2011])

Then, when I do this:

p = foreach u generate j#'id', j#'description';
dump p;

I have this output:

(1,blabla)
(1,blabla3)

But that's not what I wanted. I would like to have an output like this:

(1,blabla)
(2,blabla2)
(1,blabla3)
(2,blabla4)

How could I have this ?

Thank you very much.

回答1:

I'm assuming that the $0 you are FLATTENing in u is a tuple.

The overall problem is that j is only referencing the first map in the tuple. In order to get the output you want, you'll have to convert each tuple into a bag, then FLATTEN it.

If you know that each tuple will have up to two maps, you can do:

-- My B is your u
B = FOREACH A GENERATE (tuple(map[],map[]))$0#'experiences' AS T ;
B2 = FOREACH B GENERATE FLATTEN(TOBAG(T.$0, T.$1)) AS j ;

C = foreach B2 generate j#'id', j#'description' ;

If you don't know how many fields will be in the tuple, then this is will be much harder.


NOTE: This works for pig 0.10.

For tuples with an undefined number of maps, the best answer I can think of is using a UDF to parse the bytearray:

myudf.py

@outputSchema('vals: {(val:map[])}')
def foo(the_input):
    # This converts the indeterminate number of maps into a bag.
    foo = [chr(i) for i in the_input]
    foo = ''.join(foo).strip('()')
    out = []
    for f in foo.split('],['):
        f = f.strip('[]')
        out.append(dict((k, v) for k, v in [ i.split('#') for i in f.split(',')]))
    return out

myscript.pig

register 'myudf.py' using jython as myudf ;
B = FOREACH A GENERATE FLATTEN($0#'experiences') ;

T1 = FOREACH B GENERATE FLATTEN(myudf.foo($0)) AS M ;
T2 = FOREACH T1 GENERATE M#'id', M#'description' ;

However, this relies on the fact that #, ,, or ],[ will not appear in any of the keys or values in the map.


NOTE: This works for pig 0.11.

So it seems that how pig handles the input to the python UDFs changed in this case. Instead of a bytearray being the input to foo, the bytearray is automatically converted to the appropriate type. In that case it makes everything much easier:

myudf.py

@outputSchema('vals: {(val:map[])}')
def foo(the_input):
    # This converts the indeterminate number of maps into a bag.
    out = []
    for map in the_input:
        out.append(map)
    return out

myscript.pig

register 'myudf.py' using jython as myudf ;

# This time you should pass in the entire tuple.
B = FOREACH A GENERATE $0#'experiences' ;

T1 = FOREACH B GENERATE FLATTEN(myudf.foo($0)) AS M ;
T2 = FOREACH T1 GENERATE M#'id', M#'description' ;