From 1cebd4625b08a4b43b811345691b21194d9672c9 Mon Sep 17 00:00:00 2001 From: QuakeWang Date: Sun, 22 Nov 2026 23:59:27 +0800 Subject: [PATCH] [core] Support NOT EQUAL and NOT IN filters on centroid shard bitmaps Centroid shard bitmaps cannot apply negated predicates, so the bounded ANN candidate window can fill with rows that the filter excludes. Apply NOT EQUAL and NOT IN before ranking with the existing Bitmap reader. Preserve SQL NULL semantics and use consistent Spark signed-zero comparisons for ranking and row reads. Signed-off-by: QuakeWang --- .../global-index/centroid-vector.mdx | 7 +- .../bitmap/CentroidBitmapIndex.java | 8 ++ .../table/source/CentroidBitmapFilter.java | 4 + .../paimon/spark/PaimonScanBuilder.scala | 8 +- .../paimon/spark/PaimonScanBuilder.scala | 8 +- .../expressions/ExpressionUtils.scala | 24 +++- .../logical/PaimonTableValuedFunctions.scala | 6 +- .../spark/sql/CentroidVectorIndexTest.scala | 128 ++++++++++++++++++ 8 files changed, 183 insertions(+), 10 deletions(-) diff --git a/docs/docs/multimodal-table/global-index/centroid-vector.mdx b/docs/docs/multimodal-table/global-index/centroid-vector.mdx index c13e79675f2d..ec5efbfe13e1 100644 --- a/docs/docs/multimodal-table/global-index/centroid-vector.mdx +++ b/docs/docs/multimodal-table/global-index/centroid-vector.mdx @@ -217,9 +217,10 @@ CALL sys.create_global_index( ); ``` -A vector search can use these Bitmaps for equality, `IN`, `IS NULL`, `IS NOT NULL`, and -combinations of these predicates with `AND` or `OR`, including across columns. It applies the -exact matches before ranking and skips opening the ANN file when no visible vector matches. +Spark and Java vector searches can use these Bitmaps for `=`, `<>`, `IN`, `NOT IN`, +`IS NULL`, `IS NOT NULL`, and combinations of these predicates with `AND` or `OR`, +including across columns. They apply the exact matches before ranking and skip opening +the ANN file when no visible vector matches. If any branch cannot be evaluated exactly by the shard Bitmaps, the filter uses the existing scalar-filter path. diff --git a/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java b/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java index 650560ea8717..5b1c8a01c956 100644 --- a/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java +++ b/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java @@ -35,6 +35,8 @@ import org.apache.paimon.predicate.IsNotNull; import org.apache.paimon.predicate.IsNull; import org.apache.paimon.predicate.LeafPredicate; +import org.apache.paimon.predicate.NotEqual; +import org.apache.paimon.predicate.NotIn; import org.apache.paimon.predicate.Or; import org.apache.paimon.predicate.Predicate; import org.apache.paimon.types.DataField; @@ -102,12 +104,18 @@ private static RoaringNavigableMap64 evaluate( if (Equal.INSTANCE.equals(leaf.function())) { return reader.visitEqual(leaf.literals().get(0)).get().results(); } + if (NotEqual.INSTANCE.equals(leaf.function())) { + return reader.visitNotEqual(leaf.literals().get(0)).get().results(); + } if (IsNull.INSTANCE.equals(leaf.function())) { return reader.visitIsNull().get().results(); } if (IsNotNull.INSTANCE.equals(leaf.function())) { return reader.visitIsNotNull().get().results(); } + if (NotIn.INSTANCE.equals(leaf.function())) { + return reader.visitNotIn(leaf.literals()).get().results(); + } checkArgument( In.INSTANCE.equals(leaf.function()), "Unsupported centroid bitmap predicate %s.", diff --git a/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java b/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java index 5fd1742d18b2..af3f7be5b0cc 100644 --- a/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java +++ b/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java @@ -34,6 +34,8 @@ import org.apache.paimon.predicate.IsNotNull; import org.apache.paimon.predicate.IsNull; import org.apache.paimon.predicate.LeafPredicate; +import org.apache.paimon.predicate.NotEqual; +import org.apache.paimon.predicate.NotIn; import org.apache.paimon.predicate.Or; import org.apache.paimon.predicate.Predicate; import org.apache.paimon.predicate.PredicateBuilder; @@ -181,7 +183,9 @@ private static Predicate bind( Optional fieldRef = leaf.fieldRefOptional(); if (!fieldRef.isPresent() || (!Equal.INSTANCE.equals(leaf.function()) + && !NotEqual.INSTANCE.equals(leaf.function()) && !In.INSTANCE.equals(leaf.function()) + && !NotIn.INSTANCE.equals(leaf.function()) && !IsNotNull.INSTANCE.equals(leaf.function()) && !IsNull.INSTANCE.equals(leaf.function())) || !rowType.containsField(fieldRef.get().name())) { diff --git a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/paimon/spark/PaimonScanBuilder.scala b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/paimon/spark/PaimonScanBuilder.scala index 7e465a06c3c2..5f4fd43ca78d 100644 --- a/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/paimon/spark/PaimonScanBuilder.scala +++ b/paimon-spark/paimon-spark-3.2/src/main/scala/org/apache/paimon/spark/PaimonScanBuilder.scala @@ -18,6 +18,7 @@ package org.apache.paimon.spark +import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionUtils.normalizeVectorSearchFilters import org.apache.paimon.spark.read.{PaimonLocalScan, VectorSearchResultUtils} import org.apache.paimon.table.InnerTable @@ -35,6 +36,9 @@ class PaimonScanBuilder(val table: InnerTable) extends PaimonBaseScanBuilder { (ftst.origin(), None, None, Option(ftst.fullTextSearch())) case _ => (table, pushedVectorSearch, None, pushedFullTextSearch) } + val dataFilters = normalizeVectorSearchFilters( + pushedDataFilters.toSeq, + coreOptions.dataEvolutionEnabled() && (vectorSearch.isDefined || hybridSearch.isDefined)) if ( vectorSearch.isDefined && VectorSearchResultUtils.isVectorSearchMetaOnly(requiredSchema.fieldNames.toSeq) @@ -43,7 +47,7 @@ class PaimonScanBuilder(val table: InnerTable) extends PaimonBaseScanBuilder { actualTable, vectorSearch.get, pushedPartitionFilters, - pushedDataFilters) + dataFilters) return PaimonLocalScan( VectorSearchResultUtils.toRows(result, requiredSchema), requiredSchema, @@ -54,7 +58,7 @@ class PaimonScanBuilder(val table: InnerTable) extends PaimonBaseScanBuilder { actualTable, requiredSchema, pushedPartitionFilters, - pushedDataFilters, + dataFilters, pushedLimit, pushedTopN, vectorSearch, diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonScanBuilder.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonScanBuilder.scala index 565f4b7e82c1..56467471b210 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonScanBuilder.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/PaimonScanBuilder.scala @@ -24,6 +24,7 @@ import org.apache.paimon.partition.PartitionPredicate import org.apache.paimon.predicate._ import org.apache.paimon.predicate.SortValue.{NullOrdering, SortDirection} import org.apache.paimon.spark.aggregate.AggregatePushDownUtils.tryPushdownAggregation +import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionUtils.normalizeVectorSearchFilters import org.apache.paimon.spark.read.{PaimonLocalScan, PaimonSupportsPushDownVariantExtractions, VectorSearchResultUtils} import org.apache.paimon.table.{FileStoreTable, InnerTable} @@ -145,6 +146,9 @@ class PaimonScanBuilder(val table: InnerTable) (ftst.origin(), None, None, Option(ftst.fullTextSearch())) case _ => (table, pushedVectorSearch, None, pushedFullTextSearch) } + val dataFilters = normalizeVectorSearchFilters( + pushedDataFilters.toSeq, + coreOptions.dataEvolutionEnabled() && (vectorSearch.isDefined || hybridSearch.isDefined)) if ( vectorSearch.isDefined && @@ -157,7 +161,7 @@ class PaimonScanBuilder(val table: InnerTable) actualTable, vectorSearch.get, pushedPartitionFilters, - pushedDataFilters) + dataFilters) return PaimonLocalScan( VectorSearchResultUtils.toRows(result, requiredSchema), requiredSchema, @@ -174,7 +178,7 @@ class PaimonScanBuilder(val table: InnerTable) actualTable, requiredSchema, pushedPartitionFilters, - pushedDataFilters, + dataFilters, pushedLimit, pushedTopN, vectorSearch, diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/expressions/ExpressionUtils.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/expressions/ExpressionUtils.scala index c280c41d41bf..1cb6399018f5 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/expressions/ExpressionUtils.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/analysis/expressions/ExpressionUtils.scala @@ -32,7 +32,7 @@ import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation import scala.collection.JavaConverters._ -/** This wrapper is only used in java code, e.g. Procedure. */ +/** Converts and normalizes Spark SQL predicates for Paimon. */ object ExpressionUtils extends ExpressionHelper { def convertPolicyFilter( @@ -72,7 +72,23 @@ object ExpressionUtils extends ExpressionHelper { throw new IllegalArgumentException("Cannot fully convert filter_sql to a predicate.")) } - /** Adapt storage comparison semantics only for SQL-authored policies. */ + /** Use Spark's signed-zero semantics for ranked filters and subsequent reads. */ + private[spark] def normalizeVectorSearchFilters( + filters: Seq[Predicate], + normalizeSignedZeros: Boolean): Seq[Predicate] = { + if (normalizeSignedZeros) filters.map(normalizeVectorSearchPredicate) else filters + } + + private def normalizeVectorSearchPredicate(predicate: Predicate): Predicate = + predicate match { + case compound: CompoundPredicate => + new CompoundPredicate( + compound.function(), + compound.children().asScala.map(normalizeVectorSearchPredicate).asJava) + case _ => normalizeFloatingPointPredicate(predicate) + } + + /** Adapt storage comparison semantics for SQL-authored policies. */ private def normalizePolicyPredicate(predicate: Predicate): Predicate = predicate match { case compound: CompoundPredicate => new CompoundPredicate( @@ -107,6 +123,10 @@ object ExpressionUtils extends ExpressionHelper { // Keep the timestamp type unchanged apart from precision to avoid time-zone conversion. LeafPredicate.of(new CastTransform(field, timestampType), leaf.function(), leaf.literals()) } + case _ => normalizeFloatingPointPredicate(predicate) + } + + private def normalizeFloatingPointPredicate(predicate: Predicate): Predicate = predicate match { case leaf: LeafPredicate if Set(FLOAT, DOUBLE).contains(leaf.transform().outputType().getTypeRoot) => def isZero(value: AnyRef): Boolean = value match { diff --git a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/plans/logical/PaimonTableValuedFunctions.scala b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/plans/logical/PaimonTableValuedFunctions.scala index f7695de821d7..2c6c1d073834 100644 --- a/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/plans/logical/PaimonTableValuedFunctions.scala +++ b/paimon-spark/paimon-spark-common/src/main/scala/org/apache/paimon/spark/catalyst/plans/logical/PaimonTableValuedFunctions.scala @@ -22,6 +22,7 @@ import org.apache.paimon.CoreOptions import org.apache.paimon.globalindex.HybridSearchRanker import org.apache.paimon.predicate.{FullTextSearch, HybridSearch, HybridSearchRoute, Predicate, VectorSearch} import org.apache.paimon.spark.{SparkTable, SparkTypeUtils, SparkV2FilterConverter} +import org.apache.paimon.spark.catalyst.analysis.expressions.ExpressionUtils.normalizeVectorSearchFilters import org.apache.paimon.spark.catalyst.plans.logical.PaimonTableValuedFunctions._ import org.apache.paimon.spark.schema.PaimonMetadataColumn import org.apache.paimon.table.{DataTable, FullTextSearchTable, HybridSearchTable, InnerTable, VectorSearchTable} @@ -285,7 +286,10 @@ object PaimonTableValuedFunctions { case None => return None } } - Some(predicates.toSeq) + Some( + normalizeVectorSearchFilters( + predicates.toSeq, + CoreOptions.fromMap(innerTable.options()).dataEvolutionEnabled())) } catch { case NonFatal(_) => None } diff --git a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidVectorIndexTest.scala b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidVectorIndexTest.scala index 210a562ac2e7..c0ea2913816c 100644 --- a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidVectorIndexTest.scala +++ b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidVectorIndexTest.scala @@ -338,6 +338,134 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase { } } + test("centroid shard bitmaps apply negated predicates before top K") { + withTable("T") { + spark.sql("""CREATE TABLE T (id INT, v ARRAY, status STRING, p INT) + |PARTITIONED BY (p) TBLPROPERTIES ( + |'bucket'='-1', 'row-tracking.enabled'='true', 'data-evolution.enabled'='true', + |'global-index.thread-num'='1')""".stripMargin) + + // In each shard, the deleted rows fill the default post-filter window for top K = 1. + val deletedRows = for (p <- 0 to 1; i <- 0 until 12) yield { + s"(${p * 100 + i}, array($i.0f, 0.0f), 'deleted', $p)" + } + val otherRows = Seq( + "(12, array(12.0f, 0.0f), NULL, 0)", + "(13, array(13.0f, 0.0f), 'archived', 0)", + "(14, array(14.0f, 0.0f), 'active', 0)", + "(112, array(15.0f, 0.0f), NULL, 1)", + "(113, array(16.0f, 0.0f), 'archived', 1)", + "(114, array(17.0f, 0.0f), 'active', 1)" + ) + spark.sql(s"INSERT INTO T VALUES ${(deletedRows ++ otherRows).mkString(", ")}") + spark + .sql("""CALL sys.create_global_index( + |table => 'test.T', index_column => 'v', index_type => 'ivf-flat', + |options => 'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.metric=l2,ivf-flat.centroid.nlist=1,ivf-flat.nlist=1', + |extra_fields => '{"status":"bitmap"}')""".stripMargin) + .collect() + + def nearest(predicate: String): Seq[Int] = + spark + .sql(s"""SELECT id FROM vector_search('T','v',array(0.0f,0.0f),1, + |map('centroid.nprobe','1','ivf.nprobe','1')) WHERE $predicate""".stripMargin) + .collect() + .map(_.getInt(0)) + .toSeq + + val excluded = "'deleted', 'archived'" + // Lists longer than 20 produce a NotIn leaf instead of a conjunction of NotEqual leaves. + val longExcluded = (excluded +: (1 to 19).map(i => s"'unused-$i'")).mkString(", ") + for (distributed <- Seq(false, true)) { + withSparkSQLConf("spark.paimon.vector-search.distribute.enabled" -> distributed.toString) { + assert(nearest("status <> 'deleted'") == Seq(13)) + assert(nearest(s"status NOT IN ($excluded)") == Seq(14)) + assert(nearest(s"status NOT IN ($longExcluded)") == Seq(14)) + assert(nearest(s"status NOT IN ($longExcluded, NULL)").isEmpty) + assert(nearest("status <> 'deleted' OR status IS NULL") == Seq(12)) + assert(nearest("status <> 'deleted' OR id = 0") == Seq(0)) + } + } + } + } + + test("centroid vector search preserves Spark signed-zero comparisons before top K") { + withTable("T") { + spark.sql("""CREATE TABLE T (id INT, v ARRAY, f FLOAT, d DOUBLE, p INT) + |PARTITIONED BY (p) TBLPROPERTIES ( + |'bucket'='-1', 'row-tracking.enabled'='true', 'data-evolution.enabled'='true', + |'global-index.thread-num'='1')""".stripMargin) + spark.sql("""INSERT INTO T VALUES + |(1, array(0.0f, 0.0f), CAST('-0.0' AS FLOAT), CAST('-0.0' AS DOUBLE), 0), + |(2, array(1.0f, 0.0f), 0.0f, 0.0d, 0), + |(3, array(2.0f, 0.0f), 1.0f, 1.0d, 0), + |(4, array(3.0f, 0.0f), 0.0f, 0.0d, 1)""".stripMargin) + val zeros = spark.sql("SELECT f, d FROM T WHERE id IN (1, 2) ORDER BY id").collect() + assert( + zeros.map(row => java.lang.Float.floatToRawIntBits(row.getFloat(0))).toSeq == + Seq(Int.MinValue, 0)) + assert( + zeros.map(row => java.lang.Double.doubleToRawLongBits(row.getDouble(1))).toSeq == + Seq(Long.MinValue, 0L)) + + spark + .sql("""CALL sys.create_global_index( + |table => 'test.T', index_column => 'v', index_type => 'ivf-flat', + |options => 'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.metric=l2,ivf-flat.centroid.nlist=1,ivf-flat.nlist=1', + |extra_fields => '{"f":"bitmap","d":"bitmap"}')""".stripMargin) + .collect() + + val options = "map('centroid.nprobe','1','ivf.nprobe','1')" + def ids(sql: String): Seq[Int] = spark.sql(sql).collect().map(_.getInt(0)).toSeq + def nearest(predicate: String): Seq[Int] = + ids(s"SELECT id FROM vector_search('T','v',array(0.0f,0.0f),1,$options) WHERE $predicate") + + val notZero = "d <> 0.0d" + val mixedEquality = "d = 0.0d OR f <> 0.0f" + val mixedRange = "d >= 0.0d OR f <> 0.0f" + val includesZero = + Seq(mixedEquality, mixedRange, "d = 0.0d", "d IN (0.0d, 99.0d)", "d BETWEEN 0.0d AND 1.0d") + for (distributed <- Seq(false, true)) { + withSparkSQLConf("spark.paimon.vector-search.distribute.enabled" -> distributed.toString) { + includesZero.foreach { + predicate => + withClue(s"distributed=$distributed, $predicate: ") { + assert(nearest(predicate) == Seq(1)) + } + } + assert(nearest("d > 0.0d OR f < 0.0f") == Seq(3)) + + for ((field, dataType) <- Seq("f" -> "FLOAT", "d" -> "DOUBLE")) { + val extra = (99 to 118).map(n => s"CAST($n AS $dataType)") + for (sign <- Seq("0.0", "-0.0")) { + val zero = s"CAST('$sign' AS $dataType)" + val predicates = Seq( + s"$field <> $zero", + s"$field NOT IN ($zero, ${extra.head})", + s"$field NOT IN ($zero, ${extra.mkString(", ")})") + predicates.foreach { + predicate => + withClue(s"distributed=$distributed, $predicate: ") { + assert(nearest(predicate) == Seq(3)) + } + } + } + } + assert(nearest(s"$notZero AND id >= 0") == Seq(3)) + } + } + + assert(ids(s"""SELECT r.id FROM (SELECT v FROM T WHERE id = 1) AS q, LATERAL ( + | SELECT id FROM vector_search('T','v',q.v,1,$options) WHERE $mixedRange + |) AS r""".stripMargin) == Seq(1)) + assert( + ids(s"""SELECT id FROM hybrid_search('T', + |array(named_struct('field','v','query_vector',array(0.0f,0.0f), + |'limit',1,'options',$options)), array(), 1) WHERE $mixedEquality""".stripMargin) == + Seq(1)) + } + } + private def build(): Unit = { spark .sql(