Skip to content

[SPARK-52588][SQL] Approx_top_k: accumulate and estimate #51308

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,7 @@ object FunctionRegistry {
expression[HllSketchAgg]("hll_sketch_agg"),
expression[HllUnionAgg]("hll_union_agg"),
expression[ApproxTopK]("approx_top_k"),
expression[ApproxTopKAccumulate]("approx_top_k_accumulate"),

// string functions
expression[Ascii]("ascii"),
Expand Down Expand Up @@ -786,6 +787,7 @@ object FunctionRegistry {
expression[EqualNull]("equal_null"),
expression[HllSketchEstimate]("hll_sketch_estimate"),
expression[HllUnion]("hll_union"),
expression[ApproxTopKEstimate]("approx_top_k_estimate"),

// grouping sets
expression[Grouping]("grouping"),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* 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

import org.apache.datasketches.frequencies.ItemsSketch
import org.apache.datasketches.memory.Memory

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.analysis.FunctionRegistry
import org.apache.spark.sql.catalyst.analysis.TypeCheckResult
import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.{TypeCheckFailure, TypeCheckSuccess}
import org.apache.spark.sql.catalyst.expressions.aggregate.ApproxTopK
import org.apache.spark.sql.catalyst.expressions.codegen.CodegenFallback
import org.apache.spark.sql.types._

/**
* An expression that estimates the top K items from a sketch.
*
* The input is a sketch state that is generated by the ApproxTopKAccumulation function.
* The output 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.
*
* @param state The sketch state, which is a struct containing the serialized sketch data,
* the original data type and the max items tracked of the sketch.
* @param k The number of top items to estimate.
*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = """
_FUNC_(state, k) - Returns top k items with their frequency.
`k` An optional INTEGER literal greater than 0. If k is not specified, it defaults to 5.
""",
examples = """
Examples:
> SELECT _FUNC_(approx_top_k_accumulate(expr)) FROM VALUES (0), (0), (1), (1), (2), (3), (4), (4) AS tab(expr);
[{"item":0,"count":2},{"item":4,"count":2},{"item":1,"count":2},{"item":2,"count":1},{"item":3,"count":1}]

> SELECT _FUNC_(approx_top_k_accumulate(expr), 2) FROM VALUES 'a', 'b', 'c', 'c', 'c', 'c', 'd', 'd' tab(expr);
[{"item":"c","count":4},{"item":"d","count":2}]
""",
group = "misc_funcs",
since = "4.1.0")
// scalastyle:on line.size.limit
case class ApproxTopKEstimate(state: Expression, k: Expression)
extends BinaryExpression
with CodegenFallback
with ImplicitCastInputTypes {

def this(child: Expression, topK: Int) = this(child, Literal(topK))

def this(child: Expression) = this(child, Literal(ApproxTopK.DEFAULT_K))

private lazy val itemDataType: DataType = {
// itemDataType is the type of the "ItemTypeNull" field of the output of ACCUMULATE or COMBINE
state.dataType.asInstanceOf[StructType]("ItemTypeNull").dataType
}

override def left: Expression = state

override def right: Expression = k

override def inputTypes: Seq[AbstractDataType] = Seq(StructType, IntegerType)

override def checkInputDataTypes(): TypeCheckResult = {
val defaultCheck = super.checkInputDataTypes()
if (defaultCheck.isFailure) {
defaultCheck
} else if (!k.foldable) {
TypeCheckFailure("K must be a constant literal")
} else {
Copy link
Member

@gengliangwang gengliangwang Jul 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shall we also check the StructType of state?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, let's add test for this.

TypeCheckSuccess
}
}

override def dataType: DataType = ApproxTopK.getResultDataType(itemDataType)

override def eval(input: InternalRow): Any = {
// null check
ApproxTopK.checkExpressionNotNull(k, "k")
// eval
val stateEval = left.eval(input)
val kEval = right.eval(input)
val dataSketchBytes = stateEval.asInstanceOf[InternalRow].getBinary(0)
val maxItemsTrackedVal = stateEval.asInstanceOf[InternalRow].getInt(2)
val kVal = kEval.asInstanceOf[Int]
ApproxTopK.checkK(kVal)
ApproxTopK.checkMaxItemsTracked(maxItemsTrackedVal, kVal)
val itemsSketch = ItemsSketch.getInstance(
Memory.wrap(dataSketchBytes), ApproxTopK.genSketchSerDe(itemDataType))
ApproxTopK.genEvalResult(itemsSketch, kVal, itemDataType)
}

override protected def withNewChildrenInternal(newState: Expression, newK: Expression)
: Expression = copy(state = newState, k = newK)

override def nullable: Boolean = false

override def prettyName: String =
getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("approx_top_k_estimate")
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ 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.trees.{BinaryLike, TernaryLike}
import org.apache.spark.sql.catalyst.util.{CollationFactory, GenericArrayData}
import org.apache.spark.sql.errors.QueryExecutionErrors
import org.apache.spark.sql.types._
Expand All @@ -53,8 +53,8 @@ import org.apache.spark.unsafe.types.UTF8String
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.
""",
`maxItemsTracked` An optional INTEGER literal greater than or equal to k and has upper limit of 1000000. If maxItemsTracked is not specified, it defaults to 10000.
""",
examples = """
Examples:
> SELECT _FUNC_(expr) FROM VALUES (0), (0), (1), (1), (2), (3), (4), (4) AS tab(expr);
Expand Down Expand Up @@ -173,40 +173,47 @@ case class ApproxTopK(

object ApproxTopK {

private val DEFAULT_K: Int = 5
private val DEFAULT_MAX_ITEMS_TRACKED: Int = 10000
val DEFAULT_K: Int = 5
val DEFAULT_MAX_ITEMS_TRACKED: Int = 10000
private val MAX_ITEMS_TRACKED_LIMIT: Int = 1000000

private def checkExpressionNotNull(expr: Expression, exprName: String): Unit = {
def checkExpressionNotNull(expr: Expression, exprName: String): Unit = {
if (expr == null || expr.eval() == null) {
throw QueryExecutionErrors.approxTopKNullArg(exprName)
}
}

private def checkK(k: Int): Unit = {
def checkK(k: Int): Unit = {
if (k <= 0) {
throw QueryExecutionErrors.approxTopKNonPositiveValue("k", k)
}
}

private def checkMaxItemsTracked(maxItemsTracked: Int, k: Int): Unit = {
def checkMaxItemsTracked(maxItemsTracked: Int): Unit = {
if (maxItemsTracked > MAX_ITEMS_TRACKED_LIMIT) {
throw QueryExecutionErrors.approxTopKMaxItemsTrackedExceedsLimit(
maxItemsTracked, MAX_ITEMS_TRACKED_LIMIT)
}
if (maxItemsTracked <= 0) {
throw QueryExecutionErrors.approxTopKNonPositiveValue("maxItemsTracked", maxItemsTracked)
}
}

def checkMaxItemsTracked(maxItemsTracked: Int, k: Int): Unit = {
checkMaxItemsTracked(maxItemsTracked)
if (maxItemsTracked < k) {
throw QueryExecutionErrors.approxTopKMaxItemsTrackedLessThanK(maxItemsTracked, k)
}
}

private def getResultDataType(itemDataType: DataType): DataType = {
def getResultDataType(itemDataType: DataType): DataType = {
val resultEntryType = StructType(
StructField("item", itemDataType, nullable = false) ::
StructField("count", LongType, nullable = false) :: Nil)
ArrayType(resultEntryType, containsNull = false)
}

private def isDataTypeSupported(itemType: DataType): Boolean = {
def isDataTypeSupported(itemType: DataType): Boolean = {
itemType match {
case _: BooleanType | _: ByteType | _: ShortType | _: IntegerType |
_: LongType | _: FloatType | _: DoubleType | _: DateType |
Expand All @@ -216,13 +223,14 @@ object ApproxTopK {
}
}

private def calMaxMapSize(maxItemsTracked: Int): Int = {
def calMaxMapSize(maxItemsTracked: Int): Int = {
// The maximum capacity of this internal hash map has maxMapCap = 0.75 * maxMapSize
// Therefore, the maxMapSize must be at least ceil(maxItemsTracked / 0.75)
// https://datasketches.apache.org/docs/Frequency/FrequentItemsOverview.html
val ceilMaxMapSize = math.ceil(maxItemsTracked / 0.75).toInt
// The maxMapSize must be a power of 2 and greater than ceilMaxMapSize
math.pow(2, math.ceil(math.log(ceilMaxMapSize) / math.log(2))).toInt
val maxMapSize = math.pow(2, math.ceil(math.log(ceilMaxMapSize) / math.log(2))).toInt
maxMapSize
}

def createAggregationBuffer(itemExpression: Expression, maxMapSize: Int): ItemsSketch[Any] = {
Expand All @@ -242,7 +250,7 @@ object ApproxTopK {
}
}

private def updateSketchBuffer(
def updateSketchBuffer(
itemExpression: Expression,
buffer: ItemsSketch[Any],
input: InternalRow): ItemsSketch[Any] = {
Expand All @@ -268,7 +276,7 @@ object ApproxTopK {
buffer
}

private def genEvalResult(
def genEvalResult(
itemsSketch: ItemsSketch[Any],
k: Int,
itemDataType: DataType): GenericArrayData = {
Expand All @@ -290,7 +298,7 @@ object ApproxTopK {
new GenericArrayData(result)
}

private def genSketchSerDe(dataType: DataType): ArrayOfItemsSerDe[Any] = {
def genSketchSerDe(dataType: DataType): ArrayOfItemsSerDe[Any] = {
dataType match {
case _: BooleanType => new ArrayOfBooleansSerDe().asInstanceOf[ArrayOfItemsSerDe[Any]]
case _: ByteType | _: ShortType | _: IntegerType | _: FloatType | _: DateType =>
Expand All @@ -305,4 +313,123 @@ object ApproxTopK {
new ArrayOfDecimalsSerDe(dt).asInstanceOf[ArrayOfItemsSerDe[Any]]
}
}

def getSketchStateDataType(itemDataType: DataType): StructType =
StructType(
StructField("Sketch", BinaryType, nullable = false) ::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sketch => sketch. let's use camelCase

StructField("ItemTypeNull", itemDataType) ::
StructField("MaxItemsTracked", IntegerType, nullable = false) :: Nil)
}

/**
* An aggregate function that accumulates items into a sketch, which can then be used
* to combine with other sketches, via ApproxTopKCombine,
* or to estimate the top K items, via ApproxTopKEstimate.
*
* The output of this function is a struct containing the sketch in binary format,
* a null object indicating the type of items in the sketch,
* and the maximum number of items tracked by the sketch.
*
* @param expr the child expression to accumulate items from
* @param maxItemsTracked the maximum number of items to track in the sketch
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's also add doc for mutableAggBufferOffset and inputAggBufferOffset

*/
// scalastyle:off line.size.limit
@ExpressionDescription(
usage = """
_FUNC_(expr, maxItemsTracked) - Accumulates items into a sketch.
`maxItemsTracked` An optional positive INTEGER literal with upper limit of 1000000. If maxItemsTracked is not specified, it defaults to 10000.
""",
examples = """
Examples:
> SELECT approx_top_k_estimate(_FUNC_(expr)) FROM VALUES (0), (0), (1), (1), (2), (3), (4), (4) AS tab(expr);
[{"item":0,"count":2},{"item":4,"count":2},{"item":1,"count":2},{"item":2,"count":1},{"item":3,"count":1}]
> SELECT approx_top_k_estimate(_FUNC_(expr, 100), 2) FROM VALUES 'a', 'b', 'c', 'c', 'c', 'c', 'd', 'd' AS tab(expr);
[{"item":"c","count":4},{"item":"d","count":2}]
""",
group = "agg_funcs",
since = "4.1.0")
// scalastyle:on line.size.limit
case class ApproxTopKAccumulate(
expr: Expression,
maxItemsTracked: Expression,
mutableAggBufferOffset: Int = 0,
inputAggBufferOffset: Int = 0)
extends TypedImperativeAggregate[ItemsSketch[Any]]
with ImplicitCastInputTypes
with BinaryLike[Expression] {

def this(child: Expression, maxItemsTracked: Expression) = this(child, maxItemsTracked, 0, 0)

def this(child: Expression, maxItemsTracked: Int) = this(child, Literal(maxItemsTracked), 0, 0)

def this(child: Expression) = this(child, Literal(ApproxTopK.DEFAULT_MAX_ITEMS_TRACKED), 0, 0)

private lazy val itemDataType: DataType = expr.dataType

private lazy val maxItemsTrackedVal: Int = {
ApproxTopK.checkExpressionNotNull(maxItemsTracked, "maxItemsTracked")
val maxItemsTrackedVal = maxItemsTracked.eval().asInstanceOf[Int]
ApproxTopK.checkMaxItemsTracked(maxItemsTrackedVal)
maxItemsTrackedVal
}

override def left: Expression = expr

override def right: Expression = maxItemsTracked

override def inputTypes: Seq[AbstractDataType] = Seq(AnyDataType, IntegerType)

override def checkInputDataTypes(): TypeCheckResult = {
val defaultCheck = super.checkInputDataTypes()
if (defaultCheck.isFailure) {
defaultCheck
} else if (!ApproxTopK.isDataTypeSupported(itemDataType)) {
TypeCheckFailure(f"${itemDataType.typeName} columns are not supported")
} else if (!maxItemsTracked.foldable) {
TypeCheckFailure("Number of items tracked must be a constant literal")
} else {
TypeCheckSuccess
}
}

override def dataType: DataType = ApproxTopK.getSketchStateDataType(itemDataType)

override def createAggregationBuffer(): ItemsSketch[Any] = {
val maxMapSize = ApproxTopK.calMaxMapSize(maxItemsTrackedVal)
ApproxTopK.createAggregationBuffer(expr, maxMapSize)
}

override def update(buffer: ItemsSketch[Any], input: InternalRow): ItemsSketch[Any] =
ApproxTopK.updateSketchBuffer(expr, buffer, input)

override def merge(buffer: ItemsSketch[Any], input: ItemsSketch[Any]): ItemsSketch[Any] =
buffer.merge(input)

override def eval(buffer: ItemsSketch[Any]): Any = {
val sketchBytes = serialize(buffer)
InternalRow.apply(sketchBytes, null, maxItemsTrackedVal)
}

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(
newLeft: Expression,
newRight: Expression): Expression =
copy(expr = newLeft, maxItemsTracked = newRight)

override def nullable: Boolean = false

override def prettyName: String =
getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("approx_top_k_accumulate")
}
Loading