gengliangwang commented on code in PR #51236: URL: https://github.com/apache/spark/pull/51236#discussion_r2162652154
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/ApproxTopKAggregates.scala: ########## @@ -0,0 +1,290 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.apache.spark.sql.catalyst.expressions.aggregate + +import org.apache.datasketches.common._ +import org.apache.datasketches.frequencies.{ErrorType, ItemsSketch} +import org.apache.datasketches.memory.Memory + +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.analysis.{FunctionRegistry, TypeCheckResult} +import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.{TypeCheckFailure, TypeCheckSuccess} +import org.apache.spark.sql.catalyst.expressions.{ArrayOfDecimalsSerDe, Expression, ExpressionDescription, ImplicitCastInputTypes, Literal} +import org.apache.spark.sql.catalyst.trees.TernaryLike +import org.apache.spark.sql.catalyst.util.{CollationFactory, GenericArrayData} +import org.apache.spark.sql.errors.QueryExecutionErrors +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.types.UTF8String + +/** + * The ApproxTopK function (i.e., "approx_top_k") is an aggregate function that estimates + * the approximate top K (aka. k-most-frequent) items in a column. + * + * The result is an array of structs, each containing a frequent item and its estimated frequency. + * The items are sorted by their estimated frequency in descending order. + * + * The function uses the ItemsSketch from the DataSketches library to do the estimation. + * + * See [[https://datasketches.apache.org/docs/Frequency/FrequencySketches.html]] + * for more information. + * + * @param first the child expression to estimate the top K items from + * @param second the number of top items to return (K) + * @param third the maximum number of items to track in the sketch + */ +// scalastyle:off line.size.limit +@ExpressionDescription( + usage = + """ + _FUNC_(expr, k, maxItemsTracked) - Returns top k items with their frequency. + `k` An optional INTEGER literal greater than 0. If k is not specified, it defaults to 5. + `maxItemsTracked` An optional INTEGER literal greater than or equal to k. If maxItemsTracked is not specified, it defaults to 10000. + """, + examples = + """ + Examples: + > SELECT approx_top_k(expr, 10, 100) FROM VALUES (0), (1), (1), (2), (2), (2) AS tab(expr); + [{'item':2,'count':3},{'item':1,'count':2},{'item':0,'count':1}] + """, + group = "agg_funcs", + since = "4.1.0") +// scalastyle:on line.size.limit +case class ApproxTopK( + first: Expression, + second: Expression, + third: Expression, + mutableAggBufferOffset: Int = 0, + inputAggBufferOffset: Int = 0) + extends TypedImperativeAggregate[ItemsSketch[Any]] + with ImplicitCastInputTypes + with TernaryLike[Expression] { + + def this(child: Expression, topK: Expression, maxItemsTracked: Expression) = + this(child, topK, maxItemsTracked, 0, 0) + + def this(child: Expression, topK: Int, maxItemsTracked: Int) = + this(child, Literal(topK), Literal(maxItemsTracked), 0, 0) + + def this(child: Expression, topK: Expression) = + this(child, topK, Literal(ApproxTopK.DEFAULT_MAX_ITEMS_TRACKED), 0, 0) + + def this(child: Expression, topK: Int) = + this(child, Literal(topK), Literal(ApproxTopK.DEFAULT_MAX_ITEMS_TRACKED), 0, 0) + + def this(child: Expression) = + this(child, Literal(ApproxTopK.DEFAULT_K), Literal(ApproxTopK.DEFAULT_MAX_ITEMS_TRACKED), 0, 0) + + private lazy val itemDataType: DataType = first.dataType + private lazy val k: Int = { + ApproxTopK.checkExpressionNotNull(second, "k") + val k = second.eval().asInstanceOf[Int] + ApproxTopK.checkK(k) + k + } + private lazy val maxItemsTracked: Int = { + ApproxTopK.checkExpressionNotNull(third, "maxItemsTracked") + val maxItemsTracked = third.eval().asInstanceOf[Int] + ApproxTopK.checkMaxItemsTracked(maxItemsTracked, k) + maxItemsTracked + } + + override def inputTypes: Seq[AbstractDataType] = Seq(AnyDataType, IntegerType, IntegerType) + + override def checkInputDataTypes(): TypeCheckResult = { + val defaultCheck = super.checkInputDataTypes() + if (defaultCheck.isFailure) { + defaultCheck + } else if (!ApproxTopK.checkItemType(itemDataType)) { + TypeCheckFailure(f"${itemDataType.typeName} columns are not supported") + } else if (!second.foldable) { + TypeCheckFailure("K must be a constant literal") + } else if (!third.foldable) { + TypeCheckFailure("Number of items tracked must be a constant literal") + } else { + TypeCheckSuccess + } + } + + override def dataType: DataType = ApproxTopK.getResultDataType(itemDataType) + + override def createAggregationBuffer(): ItemsSketch[Any] = { + val maxMapSize = ApproxTopK.calMaxMapSize(maxItemsTracked) + ApproxTopK.createAggregationBuffer(first, maxMapSize) + } + + override def update(buffer: ItemsSketch[Any], input: InternalRow): ItemsSketch[Any] = + ApproxTopK.updateSketchBuffer(first, buffer, input) + + override def merge(buffer: ItemsSketch[Any], input: ItemsSketch[Any]): ItemsSketch[Any] = + buffer.merge(input) + + override def eval(buffer: ItemsSketch[Any]): GenericArrayData = { + ApproxTopK.genEvalResult(buffer, k, itemDataType) + } + + override def serialize(buffer: ItemsSketch[Any]): Array[Byte] = + buffer.toByteArray(ApproxTopK.genSketchSerDe(itemDataType)) + + override def deserialize(storageFormat: Array[Byte]): ItemsSketch[Any] = + ItemsSketch.getInstance(Memory.wrap(storageFormat), ApproxTopK.genSketchSerDe(itemDataType)) + + override def withNewMutableAggBufferOffset(newMutableAggBufferOffset: Int): ImperativeAggregate = + copy(mutableAggBufferOffset = newMutableAggBufferOffset) + + override def withNewInputAggBufferOffset(newInputAggBufferOffset: Int): ImperativeAggregate = + copy(inputAggBufferOffset = newInputAggBufferOffset) + + override protected def withNewChildrenInternal( + newFirst: Expression, + newSecond: Expression, + newThird: Expression): Expression = + copy(first = newFirst, second = newSecond, third = newThird) + + override def nullable: Boolean = false + + override def prettyName: String = + getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("approx_top_k") +} + +object ApproxTopK { + + private val DEFAULT_K: Int = 5 + private val DEFAULT_MAX_ITEMS_TRACKED: Int = 10000 + + private def checkExpressionNotNull(expr: Expression, exprName: String): Unit = { + if (expr == null || expr.eval() == null) { + throw QueryExecutionErrors.approxTopKNullArg(exprName) + } + } + + private def checkK(k: Int): Unit = { + if (k <= 0) { + throw QueryExecutionErrors.approxTopKNonPositiveValue("k", k) + } + } + + private def checkMaxItemsTracked(maxItemsTracked: Int, k: Int): Unit = { + if (maxItemsTracked < k) { Review Comment: Is there a upper limit? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
