user2931635
user2931635

Reputation: 37

Run a String through Java using Pig

I have a UDF jar which takes in a String as an input through Pig. This java file works through pig fine as running a 'hard coded' string such as this command

B = foreach f generate URL_UDF.mathUDF('stack.overflow');

Will give me the output I expect

My question is I am trying to get information from a text file and use my UDF with it. I load a file and want to pass data within that file which I have loaded to the UDF.

LoadData = load 'data.csv' using PigStorage(',');
f = foreach LoadData generate $0 as col0, $1 as chararray

$1 is the column I needed and researching data types (http://pig.apache.org/docs/r0.7.0/piglatin_ref2.html#Data+Types) a char array is used.

I then tryed using the following command B = foreach f generate URL_UDF.mathUDF($1);

to pass the data into the jar which fails stating

java.lang.ClassCastException: org.apache.pig.data.DataByteArray cannot be cast to java.lang.String

If anybody has any solution to this that would be great.

The java code I am running is as follows

package URL_UDF;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.pig.FilterFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.EvalFunc;
import org.apache.pig.PigWarning;
import org.apache.pig.data.Tuple;
import org.apache.commons.logging.Log;
import org.apache.*;

public class mathUDF extends EvalFunc<String> {

public String exec(Tuple arg0) throws IOException {
    // TODO Auto-generated method stub
    try{

        String urlToCheck = (String) arg0.get(0);

        return urlToCheck;
    }catch (Exception e) {
        // Throwing an exception will cause the task to fail.
        throw new IOException("Something bad happened!", e);
    }
}

}

Thanks

Upvotes: 2

Views: 4636

Answers (1)

Frederic
Frederic

Reputation: 3284

You can specify the schema with LOAD as follows

LoadData = load 'data.csv' using PigStorage(',') AS (col0: chararray, col1:chararray);

and pass col1 to the UDF.

Or

B = foreach LoadData generate (chararray)$1 AS col1:chararray;

Actually, this is a bug (PIG-2315) in Pig which will be fixed in 0.12.1. The AS clause in foreach does not work as one would expect.

Upvotes: 7

Related Questions