【问题标题】:Pig: Multiple UDF in one classPig:一类中有多个UDF
【发布时间】:2016-03-28 10:16:57
【问题描述】:

我想定义多个 Pig UDF。他们每个人都将提取数据的不同部分。在我的例子中,数据是具有复杂结构的 JSON 文档,包括许多嵌套的 JSON 对象。

问题是现在我已经为我需要的每个函数创建了一个不同的 Eval 类。这些类中的每一个都实现了 exec()。 有没有办法将所有函数放到同一个 UDF 类中并从 pig 调用它们?

我的一个 UDF 示例:

public class PigGetTimestamps extends EvalFunc<Tuple>{
  public Tuple exec(org.apache.pig.data.Tuple input) throws IOException {        

    if (input == null || input.size() == 0 ){
        return null;
    }

    try {

        String inputString = DataType.toString(input.get(0));
        try
        {
            String[] tokens=inputString.split("\t");
            if (tokens.length<1)
                return null;
            Document document=new Document(tokens[0], true, false);
            long timestamp_fetch=document.getTimestamp_fetch();
            long timestamp_pub=document.getTimestampPub();
            Tuple output = TupleFactory.getInstance().newTuple(2);
            output.set(0,timestamp_pub);
            output.set(1,timestamp_fetch);
            return output;
        }
        catch(Exception e)
        {
            return null;
        }

    } catch (Exception e) {   
        System.out.println("Can't extract field; error = " + e.getMessage());
        return null;
    }        
}  

【问题讨论】:

    标签: hadoop apache-pig udf


    【解决方案1】:

    您可以使用同一个类,创建它的多个实例 - 在构造函数中您将说明它将执行什么功能

    因此,您将在您的猪中定义不同的实例:

    define udf1 my.package.udf.MultiFunc('1');
    define udf2 my.package.udf.MultiFunc('2');
    

    你的 UDF 类看起来像:

        public class MultiFunc  extends EvalFunc<String> {
    
            private String operation;
            public MultiFunc(String operation){
                this.data = operation;
    
            }
    
            @Override
            public String exec(Tuple tuple) throws IOException {
            switch (operation){
                case "+":
                    //your code here;
                    break;
    
                case "-":
                    //your code here;
                    break;
    
                break;
    
            }        
    }
    

    【讨论】:

    • 有什么标准的方法,你可能会得到结果,但它是一个 hack
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多