Skip to content
Closed
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 @@ -30,6 +30,7 @@ import org.apache.spark.sql.catalyst.expressions.Literal.TrueLiteral
import org.apache.spark.sql.functions.col
import org.apache.spark.sql.hudi.ColumnStatsExpressionUtils._
import org.apache.spark.sql.hudi.command.exception.HoodieAnalysisException
import org.apache.spark.sql.types.StringType
import org.apache.spark.unsafe.types.UTF8String

import java.util.concurrent.atomic.AtomicBoolean
Expand Down Expand Up @@ -320,20 +321,10 @@ object DataSkippingUtils extends Logging {
Option.empty
})

// Filter "colA like 'xxx%'"
// Translates to "colA_minValue <= xxx AND xxx <= colA_maxValue" for index lookup
//
// NOTE: Since a) this operator matches strings by prefix and b) given that this column is going to be ordered
// lexicographically, we essentially need to check that provided literal falls w/in min/max bounds of the
// given column
case StartsWith(sourceExpr @ AllowedTransformationExpression(attrRef), v @ Literal(_: UTF8String, _)) =>
case StartsWith(attrRef: AttributeReference, prefix @ Literal(_: UTF8String, _))
if attrRef.dataType == StringType && prefix.dataType == StringType =>
getTargetIndexedColumnName(attrRef, indexedCols)
.map { colName =>
val targetExprBuilder: Expression => Expression = swapAttributeRefInExpr(sourceExpr, attrRef, _)
genColumnValuesEqualToExpression(colName, v, targetExprBuilder)
}.orElse({
Option.empty
})
.map(colName => genColumnStartsWithExpression(colName, prefix))

// Filter "expr(colA) not like 'xxx%'"
// Translates to "NOT(expr(colA_minValue) like 'xxx%' AND expr(colA_maxValue) like 'xxx%')" for index lookup
Expand Down Expand Up @@ -501,6 +492,16 @@ object ColumnStatsExpressionUtils {
And(LessThanOrEqual(minValueExpr, value), GreaterThanOrEqual(maxValueExpr, value))
}

def genColumnStartsWithExpression(colName: String, prefix: Expression): Expression = {
val minValueExpr = genColMinValueExpr(colName)
val maxValueExpr = genColMaxValueExpr(colName)
Or(
Or(IsNull(minValueExpr), IsNull(maxValueExpr)),
And(
GreaterThanOrEqual(maxValueExpr, prefix),
Or(LessThanOrEqual(minValueExpr, prefix), StartsWith(minValueExpr, prefix))))
}

def genColumnOnlyValuesEqualToExpression(colName: String,
value: Expression,
targetExprBuilder: Function[Expression, Expression] = Predef.identity): Expression = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,18 @@ import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.HoodieCatalystExpressionUtils.resolveExpr
import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute
import org.apache.spark.sql.catalyst.encoders.DummyExpressionHolder
import org.apache.spark.sql.catalyst.expressions.{Expression, InSet, Not}
import org.apache.spark.sql.catalyst.expressions.{AttributeReference, Expression, InSet, Left, Literal, Not, StartsWith}
import org.apache.spark.sql.catalyst.optimizer.OptimizeIn
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.functions.{col, date_format, lower, upper}
import org.apache.spark.sql.hudi.DataSkippingUtils
import org.apache.spark.sql.internal.SQLConf.SESSION_LOCAL_TIMEZONE
import org.apache.spark.sql.types._
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.apache.spark.unsafe.types.{ByteArray, UTF8String}
import org.junit.jupiter.api.{BeforeEach, Test}
import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue}
import org.junit.jupiter.api.Assumptions.assumeTrue
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.{Arguments, MethodSource}
import org.junit.jupiter.params.provider.Arguments.arguments
Expand Down Expand Up @@ -143,6 +145,49 @@ class TestDataSkippingUtils extends HoodieSparkClientTestBase with SparkAdapterS
}


@Test
def testPrefixPruningFallsBackForTransformedColumn(): Unit = {
val sourceExpr = StartsWith(Left(AttributeReference("B", StringType)(), Literal(1)), Literal("a"))
assertEquals(Literal.TrueLiteral,
DataSkippingUtils.translateIntoColumnStatsIndexFilterExpr(sourceExpr, indexedCols = indexedCols))
}

@Test
def testPrefixPruningFallsBackForNonBinaryCollation(): Unit = {
assumeTrue(spark.version.startsWith("4."))
val collatedType = DataType.fromDDL("STRING COLLATE UTF8_LCASE")
val sourceExpr = StartsWith(AttributeReference("B", collatedType)(),
Literal.create(UTF8String.fromString("ABC"), collatedType))
assertEquals(Literal.TrueLiteral,
DataSkippingUtils.translateIntoColumnStatsIndexFilterExpr(sourceExpr, indexedCols = indexedCols))
}

@Test
def testPrefixPruningPreservesMatchingValues(): Unit = {
val values = Seq("", "A", "a", "ab", "aba", "abb", "abc", "abc1", "abc9", "abd", "b",
"中文", "中文1", "😀", "😀1", "\uffff", "\uffff1")
val prefixes = Seq("", "a", "ab", "abc", "b", "中文", "😀", "\uffff")
val filters = prefixes.map { prefix =>
val sourceExpr = resolveExpr(spark, sparkAdapter.getExpressionFromColumn(col("B").startsWith(prefix)), sourceTableSchema)
prefix -> DataSkippingUtils.translateIntoColumnStatsIndexFilterExpr(sourceExpr, indexedCols = indexedCols)
}
def compare(left: String, right: String): Int =
ByteArray.compareBinary(UTF8String.fromString(left).getBytes, UTF8String.fromString(right).getBytes)

for {
minimum <- values
maximum <- values if compare(minimum, maximum) <= 0
(prefix, filter) <- filters
if values.exists(value => compare(minimum, value) <= 0 && compare(value, maximum) <= 0 && value.startsWith(prefix))
} {
val boundFilter = filter.transformDown {
case attribute: UnresolvedAttribute if attribute.name == "B_minValue" => Literal(minimum)
case attribute: UnresolvedAttribute if attribute.name == "B_maxValue" => Literal(maximum)
}
assertTrue(boundFilter.eval().asInstanceOf[Boolean], s"Incorrectly pruned [$minimum, $maximum] for prefix $prefix")
}
}

private def optimize(expr: Expression): Expression = {
val rules: Seq[Rule[LogicalPlan]] =
OptimizeIn ::
Expand Down Expand Up @@ -176,9 +221,62 @@ object TestDataSkippingUtils {
Seq(
IndexRow("file_1", valueCount = 1, B_minValue = "aba", B_maxValue = "adf", B_nullCount = 1), // may contain strings starting w/ "abc"
IndexRow("file_2", valueCount = 1, B_minValue = "adf", B_maxValue = "azy", B_nullCount = 0),
IndexRow("file_3", valueCount = 1, B_minValue = "aaa", B_maxValue = "aba", B_nullCount = 0)
IndexRow("file_3", valueCount = 1, B_minValue = "aaa", B_maxValue = "aba", B_nullCount = 0),
IndexRow("file_4", valueCount = 2, B_minValue = "abc1", B_maxValue = "abc9", B_nullCount = 0),
IndexRow("file_5", valueCount = 1, B_minValue = "abc1", B_maxValue = "abc1", B_nullCount = 0),
IndexRow("file_6", valueCount = 1, B_minValue = "abc", B_maxValue = "abc", B_nullCount = 0),
IndexRow("file_7", valueCount = 2, B_minValue = "ab", B_maxValue = "abc1", B_nullCount = 0),
IndexRow("file_8", valueCount = 1, B_minValue = "ab", B_maxValue = "ab", B_nullCount = 0),
IndexRow("file_9", valueCount = 2, B_minValue = null, B_maxValue = "abc9"),
IndexRow("file_10", valueCount = 2, B_minValue = "abc1", B_maxValue = null),
IndexRow("file_11", valueCount = 2, B_minValue = null, B_maxValue = null)
),
Seq("file_1", "file_4", "file_5", "file_6", "file_7", "file_9", "file_10", "file_11")),
arguments(
sparkAdapter.getExpressionFromColumn(col("B").startsWith("")),
Seq(
IndexRow("file_1", B_minValue = "", B_maxValue = ""),
IndexRow("file_2", B_minValue = "abc1", B_maxValue = "abc9"),
IndexRow("file_3", B_minValue = null, B_maxValue = null)
),
Seq("file_1", "file_2", "file_3")),
arguments(
sparkAdapter.getExpressionFromColumn(col("B").startsWith("中文")),
Seq(
IndexRow("file_1", B_minValue = "中文1", B_maxValue = "中文9"),
IndexRow("file_2", B_minValue = "甲", B_maxValue = "甲")
),
Seq("file_1")),
arguments(
sparkAdapter.getExpressionFromColumn(col("B").startsWith("😀")),
Seq(
IndexRow("file_1", B_minValue = "😀1", B_maxValue = "😀9"),
IndexRow("file_2", B_minValue = "😁", B_maxValue = "😁")
),
Seq("file_1")),
arguments(
sparkAdapter.getExpressionFromColumn(col("B").startsWith("\uffff")),
Seq(
IndexRow("file_1", B_minValue = "\uffff1", B_maxValue = "\uffff9"),
IndexRow("file_2", B_minValue = "😀", B_maxValue = "😀")
),
Seq("file_1")),
arguments(
sparkAdapter.getExpressionFromColumn((col("A") === 1) && col("B").startsWith("abc")),
Seq(
IndexRow("file_1", A_minValue = 1, A_maxValue = 1, B_minValue = "abc1", B_maxValue = "abc9"),
IndexRow("file_2", A_minValue = 0, A_maxValue = 0, B_minValue = "abc1", B_maxValue = "abc9"),
IndexRow("file_3", A_minValue = 1, A_maxValue = 1, B_minValue = "abd", B_maxValue = "azy")
),
Seq("file_1")),
arguments(
sparkAdapter.getExpressionFromColumn((col("A") === 1) || col("B").startsWith("abc")),
Seq(
IndexRow("file_1", A_minValue = 1, A_maxValue = 1, B_minValue = "abd", B_maxValue = "azy"),
IndexRow("file_2", A_minValue = 0, A_maxValue = 0, B_minValue = "abc1", B_maxValue = "abc9"),
IndexRow("file_3", A_minValue = 0, A_maxValue = 0, B_minValue = "abd", B_maxValue = "azy")
),
Seq("file_1", "file_2")),
arguments(
Not(sparkAdapter.getExpressionFromColumn(col("B").startsWith("abc"))),
Seq(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,56 @@ class TestDataSkippingQuery extends HoodieSparkSqlTestBase {
}
}

test("prefix predicates return the same results with and without data skipping") {
Seq("cow", "mor").foreach { tableType =>
withTempDir { tmp =>
val tableName = generateTableName
withSQLConf(
"hoodie.metadata.enable" -> "true",
"hoodie.metadata.index.column.stats.enable" -> "true",
"hoodie.metadata.index.column.stats.column.list" -> "name",
"hoodie.metadata.index.partition.stats.enable" -> "false"
) {
spark.sql(
s"""
|create table $tableName (id int, name string, dt string)
|using hudi
|tblproperties (primaryKey = 'id', type = '$tableType')
|partitioned by (dt)
|location '${tmp.getCanonicalPath}'
|""".stripMargin)
spark.sql(
s"""
|insert into $tableName values
|(1, 'abc1', 'matching'),
|(2, 'abc9', 'matching'),
|(3, 'abd', 'nonmatching'),
|(4, null, 'nulls')
|""".stripMargin)

Seq(
"name like 'abc%'" -> Seq(1, 2),
"startswith(name, 'abc')" -> Seq(1, 2),
"name like '%'" -> Seq(1, 2, 3),
"name like 'abc%' and id = 1" -> Seq(1),
"name like 'abc%' or id = 3" -> Seq(1, 2, 3),
"name not like 'abc%'" -> Seq(3)
).foreach { case (predicate, expectedIds) =>
val query = s"select id from $tableName where $predicate order by id"
val expected = withSQLConf("hoodie.enable.data.skipping" -> "false") {
spark.sql(query).collect().toSeq
}
val actual = withSQLConf("hoodie.enable.data.skipping" -> "true") {
spark.sql(query).collect().toSeq
}
assert(expected.map(_.getInt(0)) == expectedIds)
assert(actual == expected, s"Incorrect prefix pruning for $tableType: $predicate")
}
}
}
}
}

test("bucket index query") {
Seq("cow", "mor").foreach { tableType =>
// table bucket prop can not be read in the query sql now, so need to set these configs
Expand Down
Loading