如何编写Spark UDAF,该udaf只需进行行集合即可



对于我的特定要求,我想编写一个UDAF,只需收集所有输入行。

输入是两列行,双型;

中间模式"我想"是arraylist(如果我错了,请纠正我)

返回的数据类型是arraylist

我写了我的UDAF的"想法",但我希望有人帮助我完成它。

class CollectorUDAF() extends UserDefinedAggregateFunction {
  // Input Data Type Schema
  def inputSchema: StructType = StructType(Array(StructField("value", DoubleType), StructField("y", DoubleType)))
  // Intermediate Schema
  def bufferSchema = util.ArrayList[Array(StructField("value", DoubleType), StructField("y", DoubleType)]
  // Returned Data Type .
  def dataType: DataType = util.ArrayList[Array(StructField("value", DoubleType), StructField("y", DoubleType)]
  // Self-explaining
  def deterministic = true
  // This function is called whenever key changes
  def initialize(buffer: MutableAggregationBuffer) = {
  }
  // Iterate over each entry of a group
  def update(buffer: MutableAggregationBuffer, input: Row) = {

  }
  // Called after all the entries are exhausted.
  def evaluate(buffer: Row) = {
  }
  def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {
  }
}

如果我正确理解您的问题,则遵循是您的解决方案:

class CollectorUDAF() extends UserDefinedAggregateFunction {
  // Input Data Type Schema
  def inputSchema: StructType = new StructType().add("value", DataTypes.DoubleType).add("y", DataTypes.DoubleType)
  // Intermediate Schema
  val bufferFields : util.ArrayList[StructField] = new util.ArrayList[StructField]
  val bufferStructField : StructField = DataTypes.createStructField("array", DataTypes.createArrayType(DataTypes.StringType, true), true)
  bufferFields.add(bufferStructField)
  def bufferSchema: StructType = DataTypes.createStructType(bufferFields)
  // Returned Data Type .
  def dataType: DataType = DataTypes.createArrayType(DataTypes.DoubleType)
  // Self-explaining
  def deterministic = true
  // This function is called whenever key changes
  def initialize(buffer: MutableAggregationBuffer) = {
    buffer(0, new java.util.ArrayList[Double])
  }
  // Iterate over each entry of a group
  def update(buffer: MutableAggregationBuffer, input: Row) = {
    val DoubleList: util.ArrayList[Double]  = new util.ArrayList[Double](buffer.getList(0))
    DoubleList.add(input.getDouble(0))
    DoubleList.add(input.getDouble(1))
    buffer.update(0, DoubleList)
  }
  def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {
    buffer1.update(0, buffer1.getList(0).toArray() ++ buffer2.getList(0).toArray())
  }
  // Called after all the entries are exhausted.
  def evaluate(buffer: Row) = {
    buffer.getList(0).toArray()
  }
}

相关内容

  • 没有找到相关文章

最新更新