猪 Java UDF 问题

Pig Java UDF Issue

这是UDF代码

package myudf;
import java.io.IOException; 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.pig.EvalFunc; 
import org.apache.pig.data.Tuple; 

public class DateFormat extends EvalFunc<String> {
    public String exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0) {
            return null;
        }

        try {
            String dateStr = (String)input.get(0);
            SimpleDateFormat readFormat = new SimpleDateFormat( "MM/dd/yyyy hh:mm:ss.SSS aa");
            SimpleDateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS");
            Date date = null;
            try {
                date = readFormat.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            return writeFormat.format(date).toString();
        } catch(Exception e) {
            throw new IOException("Caught exception processing input row ", e);
        }
    }
}

导出一个 Jar 并在 grunt 中注册

    Register /local/path/to/UDFDate.jar;
    A = LOAD 'hdfs date file';
    B = FOREACH A GENERATE UDFDate.myudf.DateFormat([=12=]);

给出错误

[main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1070: Could not resolve UDFDate.DateFormat using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]

您无需指定 jar 名称 (UDFDate.myudf.DateFormat) 即可调用 jar 中的函数。它应该是 "packageName.className" (myudf.DateFormat).


如果 DateFormatmyudf 包中,那么您应该 运行 为:

B = FOREACH A GENERATE myudf.DateFormat([=14=]);


如果 DateFormatdefault 包中,那么您应该 运行 为:

B = FOREACH A GENERATE DateFormat([=17=]);

将您的 udf 命名为:

packagename.classname([=10=]);

已经给出了答案,但是为了基本上不要每次都重新定义 UDF 调用,您可以简化它:

Register /local/path/to/UDFDate.jar;
DEFINE myDateFormat myudf.DateFormat();
A = LOAD 'hdfs date file';
B = FOREACH A GENERATE myDateFormat([=10=]);