UDAF 就是一个例子

  • 创建一个扩展 org.apache.hadoop.hive.ql.exec.hive.UDAF 的 Java 类创建一个实现 UDAFEvaluator 的内部类

  • 实施五种方法

    • init() - 此方法初始化赋值器并重置其内部状态。我们在下面的代码中使用新的 Column() 来表示尚未汇总任何值。
    • iterate() - 每次有一个要聚合的新值时,都会调用此方法。评估者应该用执行聚合的结果更新其内部状态(我们正在做总结 - 见下文)。我们返回 true 表示输入有效。
    • terminatePartial() - 当 Hive 想要部分聚合的结果时调用此方法。该方法必须返回一个封装聚合状态的对象。
    • merge() - 当 Hive 决定将一个部分聚合与另一个聚合时,调用此方法。
    • terminate() - 当需要聚合的最终结果时调用此方法。
    public class MeanUDAF extends UDAF {
    // Define Logging
    static final Log LOG = LogFactory.getLog(MeanUDAF.class.getName());
    public static class MeanUDAFEvaluator implements UDAFEvaluator {
    /**
     * Use Column class to serialize intermediate computation
     * This is our groupByColumn
     */
    public static class Column {
     double sum = 0;
     int count = 0;
     }
    private Column col = null;
    public MeanUDAFEvaluator() {
     super();
     init();
     }
    // A - Initalize evaluator - indicating that no values have been
    // aggregated yet.
    public void init() {
     LOG.debug("Initialize evaluator");
     col = new Column();
     }
    // B- Iterate every time there is a new value to be aggregated
     public boolean iterate(double value) throws HiveException {
     LOG.debug("Iterating over each value for aggregation");
     if (col == null)
     throw new HiveException("Item is not initialized");
     col.sum = col.sum + value;
     col.count = col.count + 1;
     return true;
     }
    // C - Called when Hive wants partially aggregated results.
     public Column terminatePartial() {
     LOG.debug("Return partially aggregated results");
     return col;
     }
     // D - Called when Hive decides to combine one partial aggregation with another
     public boolean merge(Column other) {
     LOG.debug("merging by combining partial aggregation");
     if(other == null) {
     return true;
     }
     col.sum += other.sum;
     col.count += other.count;
     return true; 
    }
     // E - Called when the final result of the aggregation needed.
     public double terminate(){
     LOG.debug("At the end of last record of the group - returning final result"); 
     return col.sum/col.count;
     }
     }
    }

    hive> CREATE TEMPORARY FUNCTION <FUNCTION NAME> AS 'JAR PATH.jar';
    hive> select id, mean_udf(amount) from table group by id;