在Spark SQL临时表中创建自动增量字段

时间:2016-11-18 04:59:16

标签: java apache-spark hive apache-spark-sql auto-increment

我是Spark环境的新手。我在我的项目中使用Spark SQL。我想在Spark SQL临时表中创建自动增量字段。我创建了UDF,但它无法正常工作。我在网上尝试了各种各样的例子。这是我的Java POJO类:

public class AutoIcrementId  {
    int lastValue;
    public int evaluate() {
        lastValue++;
        return lastValue;
    }
}

1 个答案:

答案 0 :(得分:0)

我们可以将 Hive有状态UDF 用于自动增量值。代码将是这样的。

package org.apache.hadoop.hive.contrib.udf;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.udf.UDFType;
import org.apache.hadoop.io.LongWritable;

/**
 * UDFRowSequence.
 */
@Description(name = "row_sequence",
    value = "_FUNC_() - Returns a generated row sequence number starting from 1")
@UDFType(deterministic = false, stateful = true)
public class UDFRowSequence extends UDF
{
  private LongWritable result = new LongWritable();

  public UDFRowSequence() {
    result.set(0);
  }

  public LongWritable evaluate() {
    result.set(result.get() + 1);
    return result;
  }
}

// End UDFRowSequence.java

注册UDF:

CREATE TEMPORARY FUNCTION auto_increment_id AS 
   'org.apache.hadoop.hive.contrib.udf.UDFRowSequence'

<强>用法:

SELECT auto_increment_id() as id, col1, col2 FROM table_name

此处回答了类似的问题(How to implement auto increment in spark SQL