Skip to content
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
7 changes: 4 additions & 3 deletions docs/docs/multimodal-table/global-index/centroid-vector.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -181,7 +183,9 @@ private static Predicate bind(
Optional<FieldRef> 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())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand All @@ -43,7 +47,7 @@ class PaimonScanBuilder(val table: InnerTable) extends PaimonBaseScanBuilder {
actualTable,
vectorSearch.get,
pushedPartitionFilters,
pushedDataFilters)
dataFilters)
return PaimonLocalScan(
VectorSearchResultUtils.toRows(result, requiredSchema),
requiredSchema,
Expand All @@ -54,7 +58,7 @@ class PaimonScanBuilder(val table: InnerTable) extends PaimonBaseScanBuilder {
actualTable,
requiredSchema,
pushedPartitionFilters,
pushedDataFilters,
dataFilters,
pushedLimit,
pushedTopN,
vectorSearch,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}

Expand Down Expand Up @@ -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 &&
Expand All @@ -157,7 +161,7 @@ class PaimonScanBuilder(val table: InnerTable)
actualTable,
vectorSearch.get,
pushedPartitionFilters,
pushedDataFilters)
dataFilters)
return PaimonLocalScan(
VectorSearchResultUtils.toRows(result, requiredSchema),
requiredSchema,
Expand All @@ -174,7 +178,7 @@ class PaimonScanBuilder(val table: InnerTable)
actualTable,
requiredSchema,
pushedPartitionFilters,
pushedDataFilters,
dataFilters,
pushedLimit,
pushedTopN,
vectorSearch,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<FLOAT>, 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<FLOAT>, 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(
Expand Down
Loading