This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 6a9e258775 [python] Support centroid sharding, MultiVector, and Bitmap
prefilters (#11374)
6a9e258775 is described below
commit 6a9e258775f0e43431c48b8fb22469b1b02c8ca5
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 23 20:11:38 2026 +0800
[python] Support centroid sharding, MultiVector, and Bitmap prefilters
(#11374)
---
.../global-index/centroid-vector.mdx | 9 +-
docs/docs/multimodal-table/global-index/vector.mdx | 13 +-
docs/docs/pypaimon/multimodal-search.md | 76 +++-
.../pypaimon/common/options/core_options.py | 16 +-
.../native/read/native_full_text_search.py | 9 +-
.../execution/native/read/native_hybrid_search.py | 6 +-
.../execution/native/read/native_search_plan.py | 67 ++-
.../execution/native/read/native_vector_search.py | 63 ++-
paimon-python/pypaimon/execution/native/table.py | 13 +
.../execution/native/write/native_commit.py | 13 +-
.../execution/native/write/native_index_build.py | 24 +-
.../execution/native/write/native_index_drop.py | 6 +
.../execution/python/read/search/factories.py | 6 +
.../python/read/search/vector_search_scan.py | 12 +-
.../write/commit/global_index_source_check.py | 58 ++-
.../execution/python/write/file_store_commit.py | 14 +-
.../pypaimon/globalindex/create_global_index.py | 80 +++-
.../pypaimon/globalindex/global_index_meta.py | 15 +-
.../pypaimon/globalindex/index_dispatch.py | 5 +
.../pypaimon/globalindex/vindex_options.py | 5 +
.../pypaimon/manifest/centroid_index_groups.py | 97 +++++
.../pypaimon/manifest/index_manifest_file.py | 106 +++--
paimon-python/pypaimon/multimodal/table.py | 3 +-
paimon-python/pypaimon/table/file_store_table.py | 3 +-
.../pypaimon/table/source/search_dispatch.py | 121 +++++-
.../pypaimon/table/source/search_types.py | 3 +-
.../pypaimon/table/source/vector_search_builder.py | 36 +-
.../pypaimon/table/source/vector_search_split.py | 3 +
.../pypaimon/tests/global_index_build_test.py | 18 +-
.../tests/hybrid_hook_backend_retention_test.py | 4 +
.../tests/hybrid_search_phase_dispatch_test.py | 4 +
.../pypaimon/tests/lazy_search_execution_test.py | 14 +-
.../tests/native_sorted_index_build_test.py | 6 +-
.../tests/native_vector_index_layout_test.py | 481 +++++++++++++++++++++
.../pypaimon/tests/native_vector_search_test.py | 16 +-
.../public_execution_factory_boundary_test.py | 8 +-
.../tests/vindex_execution_boundary_test.py | 4 +-
37 files changed, 1256 insertions(+), 181 deletions(-)
diff --git a/docs/docs/multimodal-table/global-index/centroid-vector.mdx
b/docs/docs/multimodal-table/global-index/centroid-vector.mdx
index 7ce15ab622..c13e79675f 100644
--- a/docs/docs/multimodal-table/global-index/centroid-vector.mdx
+++ b/docs/docs/multimodal-table/global-index/centroid-vector.mdx
@@ -24,8 +24,8 @@ under the License.
# Centroid Vector Index
Centroid sharding groups indexed vectors by an outer routing model within each
-row-ID range. Spark supports this layout for `ivf-flat`, `ivf-pq`, `ivf-sq`,
`ivf-rq`,
-and `diskann`.
+row-ID range. Spark and PyPaimon support this layout for `ivf-flat`, `ivf-pq`,
+`ivf-sq`, `ivf-rq`, and `diskann`.
## Build in Spark
@@ -236,7 +236,8 @@ build must be retried. Updates to unindexed columns and
appends outside the sour
ranges can proceed. When a row-ID reassignment moves a whole range by a
constant
offset, the router and shards can be reused with the updated manifest range.
-Centroid searches use a Java reader with the vector plugin and a matching
native
-library with centroid model APIs. Install the vector plugin in Spark builds
too.
+Spark builds and Java searches require the vector plugin and a matching native
+library with centroid model APIs. PyPaimon delegates builds and searches to
+`pypaimon-rust`. See the [PyPaimon
guide](../../pypaimon/multimodal-search#centroid-shards-and-bitmap-filters).
Tables that used an earlier centroid development format need a drop and
rebuild.
Measure model-loading cost and total index size alongside recall, latency, and
file reads.
diff --git a/docs/docs/multimodal-table/global-index/vector.mdx
b/docs/docs/multimodal-table/global-index/vector.mdx
index 3d696aa1a3..0e3f58fb92 100644
--- a/docs/docs/multimodal-table/global-index/vector.mdx
+++ b/docs/docs/multimodal-table/global-index/vector.mdx
@@ -347,8 +347,8 @@ for SQL ordering and Java/Python score access.
### Search a List of Vectors
-On a Data Evolution table, Spark SQL, Flink SQL and Java can search a column
containing multiple
-embeddings per row. The native `ivf-flat`, `ivf-pq`, `ivf-sq`, `ivf-rq`, and
`diskann`
+On a Data Evolution append table, Spark SQL, Flink SQL, Java, and PyPaimon can
search a column
+containing multiple embeddings per row. The native `ivf-flat`, `ivf-pq`,
`ivf-sq`, `ivf-rq`, and `diskann`
indexes support these columns with range sharding and cosine similarity.
Omitting the metric selects `cosine`. Index creation rejects any other metric.
The column can be `ARRAY<VECTOR<FLOAT, d>>` or `ARRAY<ARRAY<FLOAT>>`. For the
latter,
@@ -395,8 +395,9 @@ before applying the post-filter.
By default, it requests up to four times the final limit per query vector per
shard.
Set `refine_factor` to select that multiplier for any of the five indexes.
Uncovered rows
included by the search mode are scored with the same MaxSim formula. Java
exposes matrix queries through
-`newVectorSearchBuilder().withMultiVector(float[][])`. For independent top-K
results
-per vector, use `newBatchVectorSearchBuilder().withVectors(float[][])`.
+`newVectorSearchBuilder().withMultiVector(float[][])`. PyPaimon uses
+`new_vector_search_builder().with_multi_vector(vectors)` with a compatible
native runtime.
+For independent top-K results per vector, use the batch vector search builder.
## Search Options
@@ -522,9 +523,9 @@ CALL sys.create_global_index(
Pass the same option keys to Python's `create_global_index(...,
options={...})`.
Use full 768-dimensional query vectors when searching either of these indexes.
-## Centroid-Based Sharding in Spark
+## Centroid-Based Sharding
-[Centroid Vector Index](./centroid-vector) covers Spark builds, probe options,
the
+[Centroid Vector Index](./centroid-vector) covers Spark and PyPaimon builds,
probe options, the
index manifest and router file formats, and the Bitmap filters attached to
each shard.
## Per-Field Options
diff --git a/docs/docs/pypaimon/multimodal-search.md
b/docs/docs/pypaimon/multimodal-search.md
index d5f0f52394..62ed32e199 100644
--- a/docs/docs/pypaimon/multimodal-search.md
+++ b/docs/docs/pypaimon/multimodal-search.md
@@ -46,10 +46,37 @@ Use `create_index` to create the global indexes used by
search APIs. The
index implementation. Use `full-text` for full-text indexes.
```python
-docs.create_index("embedding", index_type="ivf-pq")
+docs.create_index("embedding", index_type="ivf-flat")
docs.create_index("content", index_type="full-text")
```
+### Centroid shards and Bitmap filters
+
+On a Parquet Data Evolution append table, use `ivf-flat.sharding=centroid`
+to train a router and build an index for each centroid. `extra_fields` accepts
+a mapping of scalar column names to `bitmap`. Searches can use these Bitmaps
for
+equality, `IN`, null checks, and their `AND` and `OR` combinations before
ranking.
+Building with `extra_fields` requires `global-index.column-update-action` to
+be `THROW_ERROR` (the default) or `DROP_PARTITION_INDEX`.
+
+```python
+docs.create_index(
+ "embedding", index_type="ivf-flat",
+ options={"ivf-flat.sharding": "centroid", "ivf-flat.centroid.nlist": "16"},
+ extra_fields={"category": "bitmap"},
+)
+neighbors = docs.search([0.1, 0.2, 0.3], column="embedding",
+ pre_filter="category = 'lake'").limit(10).to_arrow()
+```
+
+Builds and searches use native execution on local filesystem and supported REST
+tables. Install a `pypaimon-rust` build with centroid and MultiVector support.
+The source is available on the [paimon-rust main
branch](https://github.com/apache/paimon-rust/tree/main/bindings/python).
+When a search selects both range and centroid indexes of the same type, it uses
+native planning for all selected ranges. With a scalar predicate and no
+applicable scalar index, the search filters the ANN candidates returned by the
probes.
+Probe options and rebuild behavior are described in the [Centroid Vector Index
guide](../multimodal-table/global-index/centroid-vector).
+
### Build vector indexes with Ray
Pass `execution="ray"` to distribute native vector-index shards across Ray
@@ -63,17 +90,17 @@ docs.create_index(
)
```
-The driver plans uncovered row ranges from one snapshot. Workers build files;
-the driver publishes their index entries in one commit after all shards
succeed.
-`concurrency` bounds running shards; `global-index.build.parallelism` controls
-only local thread-based builds. Install the same `pypaimon[ray,vindex]`
-dependencies on every worker and use storage accessible to the entire cluster.
-
-Write tasks require `max_retries=0` and `retry_exceptions=False` (set by
default).
-On a task failure, the driver stops submissions, waits for dispatched tasks,
-and removes their uncommitted output files. Rerun the build after the failure;
-already committed index coverage is skipped. Driver/cluster termination can
-still leave orphan files for normal orphan-file maintenance. Retain the source
+The driver plans row ranges from one snapshot. Range builds skip existing index
+coverage. Centroid builds replace the prior indexes for the selected
partitions.
+Workers build files and the driver commits the additions and replacements after
+all shards succeed. `concurrency` bounds running shards.
+`global-index.build.parallelism` controls local thread-based builds.
+Install the same Python dependencies and native runtime on every worker and use
+storage accessible to the entire cluster.
+
+Write tasks require `max_retries=0` and `retry_exceptions=False` by default.
+On a task failure, the driver stops submissions and waits for dispatched tasks.
+Uncommitted outputs can remain for orphan-file maintenance. Retain the source
snapshot's files until the build and its commit finish.
## Search
@@ -494,6 +521,31 @@ hybrid = docs.search_hybrid(
Dictionary vector routes also accept `anns_field`, `data`, and `param` aliases.
+## Search a list of embeddings with MultiVector
+
+On a Data Evolution append table, a row can store multiple embeddings in an
+`ARRAY<VECTOR<FLOAT, d>>` or `ARRAY<ARRAY<FLOAT>>` column. Build a
range-sharded
+vector index with the cosine metric. For variable-length inner arrays, set the
+embedding dimension when building the index.
+
+`with_multi_vector()` ranks each row by the sum of the best cosine match for
+each query vector. The matrix produces one top-K result.
+
+```python
+table = docs.raw_table
+table.create_global_index("chunks", "ivf-flat", options={"ivf-flat.dimension":
"3"})
+result = (
+ table.new_vector_search_builder()
+ .with_vector_column("chunks")
+ .with_multi_vector([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
+ .with_limit(10)
+ .execute_local()
+)
+read = table.new_read_builder().with_projection(["id"])
+plan = read.new_scan().with_global_index_result(result).plan()
+rows = read.new_read().to_arrow(plan.splits())
+```
+
## Search Vectors
Use `search_vectors` for multiple query vectors against one vector column. It
diff --git a/paimon-python/pypaimon/common/options/core_options.py
b/paimon-python/pypaimon/common/options/core_options.py
index 17ac54e5f3..0893b3d937 100644
--- a/paimon-python/pypaimon/common/options/core_options.py
+++ b/paimon-python/pypaimon/common/options/core_options.py
@@ -1946,6 +1946,13 @@ class CoreOptions:
def _index_columns(columns) -> List[str]:
return [] if columns is None else [column.strip() for column in
str(columns).split(',')]
+ @staticmethod
+ def _field_index_option_keys(index_type: str, column: str):
+ field = "fields.%s." % column
+ family = "vector" if CoreOptions._is_vector_index_type(index_type)
else index_type
+ return (field + "index-options", field +
"global-index.%s.index-options" % family,
+ field + "pk-%s.index.options" % family)
+
def global_index_options(self, index_type: Optional[str], column: str) ->
Options:
"""Resolve the same implementation and field options for either table
mode."""
values = dict(self.options.to_map())
@@ -1954,10 +1961,9 @@ class CoreOptions:
vector = self._is_vector_index_type(index_type)
prefix = index_type + ("." if vector or index_type == "full-text" else
"-index.")
field_prefix = "fields.%s." % column
- shared_key = field_prefix + "index-options"
- shared = values.get(shared_key) is not None
- option_key = shared_key if shared else field_prefix + "pk-" + (
- "vector" if vector else index_type) + ".index.options"
+ keys = self._field_index_option_keys(index_type, column)
+ option_key = next((key for key in keys if values.get(key) is not
None), keys[-1])
+ shared = option_key == keys[0]
serialized = values.get(option_key)
if serialized is not None and str(serialized).strip():
try:
@@ -1980,7 +1986,7 @@ class CoreOptions:
values[qualified] = str(value)
if vector and qualified.startswith(prefix):
short_key = qualified[len(prefix):]
- if shared:
+ if shared or option_key == keys[1] or short_key ==
"sharding":
values[field_prefix + short_key] = str(value)
return Options(values)
diff --git
a/paimon-python/pypaimon/execution/native/read/native_full_text_search.py
b/paimon-python/pypaimon/execution/native/read/native_full_text_search.py
index a24ac04285..001cbcfc4b 100644
--- a/paimon-python/pypaimon/execution/native/read/native_full_text_search.py
+++ b/paimon-python/pypaimon/execution/native/read/native_full_text_search.py
@@ -15,7 +15,7 @@
# specific language governing permissions and limitations
# under the License.
-"""Local REST full-text search delegated to Rust core."""
+"""Local full-text search delegated to Rust core."""
from pypaimon.catalog.table_query_auth import reject_search_under_query_auth
from pypaimon.common.options.core_options import GlobalIndexSearchMode
@@ -24,6 +24,7 @@ from pypaimon.execution.native.read.builder import
(_predicate_to_native)
from pypaimon.execution.native.runtime import (native_runtime_available)
from pypaimon.table.file_store_table import FileStoreTable
from pypaimon.execution.native.read.native_search_plan import
_native_prefilter_options, _result
+from pypaimon.execution.native.read.native_vector_search import
_filesystem_vector_search_supported
from pypaimon.execution.native.write.native_commit import
_rest_catalog_supported
@@ -34,8 +35,10 @@ def _native_full_text_builder(builder, require_limit=True):
if (type(table) is not FileStoreTable
or not table.options.native_read_enabled()
or table.options.file_format() != 'parquet'
- or not native_runtime_available()
- or not _rest_catalog_supported(table)):
+ or not native_runtime_available()):
+ return None
+ if not (_rest_catalog_supported(table) or (getattr(builder,
'_native_hybrid_route', False)
+ and
_filesystem_vector_search_supported(table))):
return None
primary_key = builder._primary_key_full_text_definition() is not None
if not primary_key and (not table.options.row_tracking_enabled()
diff --git
a/paimon-python/pypaimon/execution/native/read/native_hybrid_search.py
b/paimon-python/pypaimon/execution/native/read/native_hybrid_search.py
index a65bc369e9..aa8c9aae15 100644
--- a/paimon-python/pypaimon/execution/native/read/native_hybrid_search.py
+++ b/paimon-python/pypaimon/execution/native/read/native_hybrid_search.py
@@ -22,6 +22,7 @@ from pypaimon.globalindex.vector_search_result import
DictBasedScoredIndexResult
from pypaimon.execution.native.table import (_native_table, _options_to_native)
from pypaimon.execution.native.read.builder import (_predicate_to_native)
from pypaimon.execution.native.read.native_search_plan import
_native_prefilter_options
+from pypaimon.execution.native.read.native_vector_search import
_filesystem_vector_search_supported
from pypaimon.execution.native.runtime import (native_runtime_available)
from pypaimon.table.file_store_table import FileStoreTable
from pypaimon.execution.native.write.native_commit import
_rest_catalog_supported
@@ -38,7 +39,7 @@ def _native_builder(builder, executor=None):
or table.is_primary_key_table
or table.options.file_format() != 'parquet'
or not native_runtime_available()
- or not _rest_catalog_supported(table)):
+ or not (_rest_catalog_supported(table) or
_filesystem_vector_search_supported(table))):
return None
builder._validate_search()
if executor is not None and not table.options.data_evolution_enabled():
@@ -107,6 +108,9 @@ def try_native_hybrid_routes(builder):
execution._table = builder._table._copy_with_snapshot(snapshot)
search = (execution._new_vector_search_builder(route) if
route.is_vector() else
execution._new_full_text_search_builder(route))
+ # Capture the execution engine for separately executed routes,
including
+ # range vector and full-text routes of a filesystem hybrid search.
+ search._native_hybrid_route = True
routes.append(HybridSearchRouteBuilder(route, search))
return routes
diff --git a/paimon-python/pypaimon/execution/native/read/native_search_plan.py
b/paimon-python/pypaimon/execution/native/read/native_search_plan.py
index dba7b7127b..8c7c6533a7 100644
--- a/paimon-python/pypaimon/execution/native/read/native_search_plan.py
+++ b/paimon-python/pypaimon/execution/native/read/native_search_plan.py
@@ -18,6 +18,7 @@
"""Translate ordinary snapshot-and-split plans to and from Rust Core."""
from copy import copy, deepcopy
+import json
from pypaimon.common.json_util import JSON
from pypaimon.common.options.core_options import CoreOptions
@@ -31,6 +32,7 @@ from pypaimon.table.source.search_types import (
PrimaryKeyVectorScanPlan, PrimaryKeyVectorSearchSplit,
)
from pypaimon.table.source.primary_key_scored_result import
PrimaryKeyScoredResult, PrimaryKeySearchPosition
+from pypaimon.table.source.vector_search_split import IndexVectorSearchSplit,
RawVectorSearchSplit
from pypaimon.utils.range import Range
from pypaimon.write.commit_message_serializer import _index_from_row,
_index_row
@@ -56,7 +58,6 @@ def _files(values):
def _split_from_native(table, split, full_text):
from pypaimon_rust import datafusion as sdk
from pypaimon.table.source.full_text_search_split import
IndexFullTextSearchSplit, RawFullTextSearchSplit
- from pypaimon.table.source.vector_search_split import
IndexVectorSearchSplit, RawVectorSearchSplit
native_pk = sdk.PrimaryKeyFullTextSearchSplit if full_text else
sdk.PrimaryKeyVectorSearchSplit
native_index = sdk.IndexFullTextSearchSplit if full_text else
sdk.IndexVectorSearchSplit
@@ -88,13 +89,29 @@ def _plan_from_native(table, native, full_text,
primary_key):
if primary_key:
cls = PrimaryKeyFullTextScanPlan if full_text else
PrimaryKeyVectorScanPlan
return cls(0 if snapshot is None else snapshot.id, splits, snapshot)
- return (FullTextScanPlan if full_text else VectorSearchScanPlan)(splits,
snapshot)
+ if full_text:
+ return FullTextScanPlan(splits, snapshot)
+ # Preserve the candidate filtering chosen by the native planner when a
+ # local reader consumes the captured plan or receives only its splits.
+ for split in splits:
+ split._native_vector_layout = True
+ raw_splits = [split for split in splits if isinstance(split,
RawVectorSearchSplit)]
+ if (raw_splits and hasattr(native, '_from_json')
+ and any(file.global_index_meta is not None and
file.global_index_meta.has_centroid_bitmap_fields()
+ for split in splits if isinstance(split,
IndexVectorSearchSplit)
+ for file in split.vector_index_files)):
+ # The SDK pickle codec also carries the ranges planned solely for
scalar prefiltering.
+ # Keep those ranges with each split so both reader entry points
preserve their purpose.
+ _, (state,) = native.__reduce__()
+ ranges = [Range(value['from'], value['to']) for value in
json.loads(state).get('scalar_prefilter_ranges', ())]
+ for split in raw_splits:
+ split._scalar_prefilter_ranges = Range.and_(split.row_ranges,
ranges)
+ return VectorSearchScanPlan(splits, snapshot)
def _split_to_native(split, full_text, snapshot=None):
from pypaimon_rust import datafusion as sdk
from pypaimon.table.source.full_text_search_split import
IndexFullTextSearchSplit, RawFullTextSearchSplit
- from pypaimon.table.source.vector_search_split import
IndexVectorSearchSplit, RawVectorSearchSplit
expected = ((PrimaryKeyFullTextSearchSplit, IndexFullTextSearchSplit,
RawFullTextSearchSplit) if full_text else
(PrimaryKeyVectorSearchSplit, IndexVectorSearchSplit,
RawVectorSearchSplit))
@@ -134,7 +151,30 @@ def _plan_to_native(plan, full_text):
captured = plan.snapshot()
snapshot = None if captured is None else
sdk.Snapshot._from_json(JSON.to_json(captured))
cls = sdk.FullTextScanPlan if full_text else sdk.VectorScanPlan
- return cls([_split_to_native(split, full_text, captured) for split in
plan.splits()], snapshot)
+ native = cls([_split_to_native(split, full_text, captured) for split in
plan.splits()], snapshot)
+ ranges = _scalar_prefilter_ranges(plan.splits()) if not full_text else []
+ if ranges:
+ restore, (state,) = native.__reduce__()
+ state = json.loads(state)
+ state['scalar_prefilter_ranges'] = [{'from': r.from_, 'to': r.to} for
r in ranges]
+ return restore(json.dumps(state))
+ return native
+
+
+def _scalar_prefilter_ranges(splits):
+ raw_splits = [split for split in splits if isinstance(split,
RawVectorSearchSplit)]
+ if not any(getattr(split, '_scalar_prefilter_ranges', ()) for split in
raw_splits):
+ return []
+ prefilter, scoring = [], []
+ for split in raw_splits:
+ ranges = Range.and_(split.row_ranges, getattr(split,
'_scalar_prefilter_ranges', ()))
+ prefilter.extend(ranges)
+ for row_range in split.row_ranges:
+ scoring.extend(row_range.exclude(ranges))
+ # An explicitly supplied raw split can request scoring over a range that
+ # another split supplied only for scalar prefiltering.
+ scoring = Range.sort_and_merge_overlap(scoring, True, True)
+ return [uncovered for row_range in prefilter for uncovered in
row_range.exclude(scoring)]
def _capture_builder(builder):
@@ -276,13 +316,11 @@ def _builder_to_native(builder, full_text, batch=False,
scan=False):
from pypaimon.execution.native.read.native_full_text_search import
_native_full_text_builder
native = _native_full_text_builder(builder, require_limit=not scan)
else:
- from pypaimon.execution.native.read.native_vector_search import
_native_vector_builder
+ from pypaimon.execution.native.read.native_vector_search import
_native_vector_builder, _set_native_query
native = _native_vector_builder(builder, batch)
if native is not None and not scan:
- if batch:
- native.with_query_vectors(builder._query_vectors)
- else:
- native.with_query_vector(builder._query_vector)
+ queries = builder._query_vectors if batch else
builder._query_vector
+ _set_native_query(native, builder, queries, batch)
if native is None:
raise RuntimeError('Native search runtime is unavailable for the
captured reader configuration')
return native
@@ -297,16 +335,13 @@ def native_vector_scan(builder, batch=False):
def native_vector_read(builder, batch=False):
- from pypaimon.execution.native.read.native_vector_search import
_native_vector_builder
+ from pypaimon.execution.native.read.native_vector_search import
_native_vector_builder, _set_native_query
native = _native_vector_builder(builder, batch)
if native is None:
return None
- if batch:
- native.with_query_vectors(builder._query_vectors)
- reader = native.new_batch_vector_search_read()
- else:
- native.with_query_vector(builder._query_vector)
- reader = native.new_vector_search_read()
+ queries = builder._query_vectors if batch else builder._query_vector
+ _set_native_query(native, builder, queries, batch)
+ reader = native.new_batch_vector_search_read() if batch else
native.new_vector_search_read()
return NativeSearchRead(
builder._table, reader, builder._is_primary_key_vector_search(), False,
_capture_builder(builder), batch)
diff --git
a/paimon-python/pypaimon/execution/native/read/native_vector_search.py
b/paimon-python/pypaimon/execution/native/read/native_vector_search.py
index 871a975673..9ed49d39ac 100644
--- a/paimon-python/pypaimon/execution/native/read/native_vector_search.py
+++ b/paimon-python/pypaimon/execution/native/read/native_vector_search.py
@@ -17,14 +17,52 @@
"""Local vector search through the Rust core Scan -> Plan -> Read path."""
+from importlib import import_module
+
from pypaimon.catalog.table_query_auth import reject_search_under_query_auth
+from pypaimon.globalindex.vindex_options import is_multi_vector_type
from pypaimon.globalindex.vector_search_result import
DictBasedScoredIndexResult
-from pypaimon.execution.native.table import (_catalog_metastore, _native_table)
+from pypaimon.execution.native.table import (_catalog_metastore,
_filesystem_vector_table_supported, _native_table)
from pypaimon.execution.native.read.builder import (_predicate_to_native)
from pypaimon.execution.native.runtime import (native_runtime_available)
from pypaimon.execution.native.read.native_search_plan import
_native_prefilter_options, _result
+def _has_vector_layout_api():
+ sdk = import_module('pypaimon_rust.datafusion')
+ # Check optional exports without invoking module-level attribute
resolution.
+ return hasattr(vars(sdk).get('VectorSearchBuilder'), 'with_multi_vector')
+
+
+def _filesystem_vector_search_supported(table):
+ return (_filesystem_vector_table_supported(table) and
table.options.data_evolution_enabled()
+ and native_runtime_available() and _has_vector_layout_api())
+
+
+def _multi_vector_requested(builder):
+ return (getattr(builder, '_multi_vector', None) is not None
+ or is_multi_vector_type(getattr(builder._vector_column, 'type',
None)))
+
+
+def _filesystem_vector_search_view(table, partition_filter):
+ """Capture the search snapshot and its index entries in the selected
partitions."""
+ from pypaimon.index.index_file_handler import IndexFileHandler
+ from pypaimon.snapshot.time_travel_util import TimeTravelUtil
+
+ snapshot = TimeTravelUtil.resolve_snapshot(table)
+ view = table if hasattr(table, '_read_snapshot') else
table._copy_with_snapshot(snapshot)
+ if snapshot is None or snapshot.index_manifest is None:
+ return view, []
+ predicate = None if partition_filter is None else lambda entry:
partition_filter.test(entry.partition)
+ return view, IndexFileHandler(view).scan(snapshot, predicate)
+
+
+def _has_centroid_indexes(entries, fields):
+ field_ids = {field.id for field in fields}
+ return any(meta is not None and meta.index_field_id in field_ids and
meta.is_centroid_index()
+ for meta in (entry.index_file.global_index_meta for entry in
entries))
+
+
def _native_vector_builder(builder, batch=False):
"""Configure a native builder, or return None before execution.
@@ -37,12 +75,14 @@ def _native_vector_builder(builder, batch=False):
if not callable(native_enabled) or not native_enabled():
return None
loader = getattr(getattr(table, 'catalog_environment', None),
'catalog_loader', None)
- if loader is None or _catalog_metastore(loader) != 'rest':
+ catalog = _catalog_metastore(loader)
+ if catalog != 'rest' and not _filesystem_vector_search_supported(table):
return None
# Python's batch reader currently supports only global row-ID results.
if batch and builder._is_primary_key_vector_search():
return None
- if not native_runtime_available():
+ if catalog == 'rest' and (not native_runtime_available()
+ or (_multi_vector_requested(builder) and not
_has_vector_layout_api())):
return None
native_table = _native_table(table)
native = (native_table.new_batch_vector_search_builder() if batch else
@@ -61,6 +101,15 @@ def _native_vector_builder(builder, batch=False):
return native
+def _set_native_query(native, builder, queries, batch):
+ if batch:
+ native.with_query_vectors(queries)
+ elif getattr(builder, '_multi_vector', None) is not None:
+ native.with_multi_vector(builder._multi_vector)
+ else:
+ native.with_query_vector(queries)
+
+
def try_native_vector_search(builder, queries, batch=False):
native = _native_vector_builder(builder, batch)
if native is None:
@@ -68,10 +117,8 @@ def try_native_vector_search(builder, queries, batch=False):
table = builder._table
# Once the Native route is chosen, errors must not trigger another search
# against a potentially newer snapshot.
- if batch:
- native.with_query_vectors(queries)
- results = native.execute()
- return [DictBasedScoredIndexResult(result.row_ids()) for result in
results]
- native.with_query_vector(queries)
+ _set_native_query(native, builder, queries, batch)
result = native.execute()
+ if batch:
+ return [DictBasedScoredIndexResult(item.row_ids()) for item in result]
return _result(table, result, builder._is_primary_key_vector_search())
diff --git a/paimon-python/pypaimon/execution/native/table.py
b/paimon-python/pypaimon/execution/native/table.py
index 21baf7e111..cd843edb29 100644
--- a/paimon-python/pypaimon/execution/native/table.py
+++ b/paimon-python/pypaimon/execution/native/table.py
@@ -76,6 +76,19 @@ def _catalog_metastore(loader) -> Optional[str]:
return None
+def _filesystem_vector_table_supported(table):
+ from pypaimon.catalog.catalog_environment import CatalogEnvironment
+ from pypaimon.filesystem.local_file_io import LocalFileIO
+ from pypaimon.table.file_store_table import FileStoreTable
+
+ if type(table) is not FileStoreTable or type(table.file_io) is not
LocalFileIO:
+ return False
+ environment = table.catalog_environment
+ return (type(environment) is CatalogEnvironment
+ and _catalog_metastore(environment.catalog_loader) == 'filesystem'
+ and table.options.file_format() == 'parquet')
+
+
def _option_value_to_string(value) -> str:
"""Stringify an option value for the Rust catalog.
diff --git a/paimon-python/pypaimon/execution/native/write/native_commit.py
b/paimon-python/pypaimon/execution/native/write/native_commit.py
index 5f9c5256e3..bf28788ad7 100644
--- a/paimon-python/pypaimon/execution/native/write/native_commit.py
+++ b/paimon-python/pypaimon/execution/native/write/native_commit.py
@@ -36,11 +36,16 @@ def native_messages_supported(table, messages, *,
for_commit=False) -> bool:
or message.compact_changelog_files
or message.compact_index_adds or
message.compact_index_deletes):
return False
- # Native 0.5.0 cannot validate retained field IDs against the schema of
- # each publication attempt. Full-row updates also retain field IDs;
- # write_cols=None does not exempt them. Pure conflict probes are safe.
+ # Python checks retained field IDs and centroid groups against each
+ # publication attempt for changes to existing Data Evolution rows.
if (for_commit and table.options.data_evolution_enabled()
- and any(file.first_row_id is not None for file in
message.new_files)):
+ and any(file.first_row_id is not None for file in
message.new_files + message.deleted_files)):
+ return False
+ if for_commit and any(entry.index_file.global_index_meta is not None
+ and
entry.index_file.global_index_meta.is_centroid_index()
+ for entry in message.index_adds +
message.index_deletes):
+ # Java checks intervening COMPACT snapshots and complete centroid
+ # groups during publication. Keep those checks on each Python CAS
attempt.
return False
partition = tuple(message.partition)
for file in message.new_files + message.changelog_files:
diff --git
a/paimon-python/pypaimon/execution/native/write/native_index_build.py
b/paimon-python/pypaimon/execution/native/write/native_index_build.py
index 6c8d7f9957..551994f8a1 100644
--- a/paimon-python/pypaimon/execution/native/write/native_index_build.py
+++ b/paimon-python/pypaimon/execution/native/write/native_index_build.py
@@ -17,7 +17,7 @@
"""Global-index builds delegated to Rust, retaining Python's commit API."""
-from pypaimon.execution.native.table import (_native_table, _options_to_native)
+from pypaimon.execution.native.table import
(_filesystem_vector_table_supported, _native_table, _options_to_native)
from pypaimon.execution.native.read.builder import (_predicate_to_native)
from pypaimon.execution.native.runtime import (native_runtime_available)
from pypaimon.execution.native.write.native_commit import
_rest_catalog_supported, from_native_commit_messages
@@ -39,18 +39,30 @@ def build_native_global_index(builder, partition_filter, *,
execution="local", c
or table.options.query_auth_enabled
or table.is_primary_key_table
or table.options.file_format() != 'parquet'
- or not native_runtime_available()
- or not _rest_catalog_supported(table)):
+ or not native_runtime_available()):
+ return None
+ native_vector = builder._centroid_sharding or builder._multi_vector
+ if not (_rest_catalog_supported(table) or (native_vector and
_filesystem_vector_table_supported(table))):
return None
from pypaimon_rust.datafusion import GlobalIndexBuildBuilder
if not GlobalIndexBuildBuilder.supports_index_type(builder._index_type):
return None
+ if builder._centroid_sharding:
+ from pypaimon_rust.datafusion import GlobalIndexBuildPlan
+ if not hasattr(GlobalIndexBuildPlan, 'replacement_messages'):
+ return None
+ if builder._multi_vector:
+ from pypaimon_rust.datafusion import VectorSearchBuilder
+ if not hasattr(VectorSearchBuilder, 'with_multi_vector'):
+ return None
# Keep build parameters separate from schema defaults: alias precedence is
# resolved within each source, then explicit build parameters win.
options = _build_options_to_native(builder._user_options)
table_overrides = {key: None for key, value in
builder._user_options.items() if value is None}
parallelism = CoreOptions.GLOBAL_INDEX_BUILD_PARALLELISM.key()
table_values = table.options.options.to_map()
+ if not builder._centroid_sharding and 'extra_fields' in table_values:
+ table_overrides['extra_fields'] = None
if parallelism not in builder._user_options and
isinstance(table_values.get(parallelism), (bool, float)):
table_overrides[parallelism] = _build_options_to_native(
{parallelism: table_values[parallelism]})[parallelism]
@@ -65,7 +77,11 @@ def build_native_global_index(builder, partition_filter, *,
execution="local", c
# Planning may authorize and capture inputs; its errors must not select
# another engine or restart a build that may already have side effects.
plan = native.plan()
- return build_native_vector_index(table, plan, concurrency,
ray_remote_args)
+ messages = build_native_vector_index(table, plan, concurrency,
ray_remote_args)
+ replacements = getattr(plan, 'replacement_messages', None)
+ if replacements is not None:
+ messages.extend(from_native_commit_messages(table, replacements()))
+ return messages
return from_native_commit_messages(table, native.build())
diff --git a/paimon-python/pypaimon/execution/native/write/native_index_drop.py
b/paimon-python/pypaimon/execution/native/write/native_index_drop.py
index ef8bdb0819..47c55cbc8a 100644
--- a/paimon-python/pypaimon/execution/native/write/native_index_drop.py
+++ b/paimon-python/pypaimon/execution/native/write/native_index_drop.py
@@ -23,6 +23,7 @@ def build_native_global_index_drop(builder, partition_filter):
from pypaimon.execution.native.read.builder import (_predicate_to_native)
from pypaimon.execution.native.runtime import (native_runtime_available)
from pypaimon.execution.native.write.native_commit import
_rest_catalog_supported, from_native_commit_messages
+ from pypaimon.globalindex.vindex_options import VINDEX_IDENTIFIERS
table = builder._table
if (not table.options.native_write_enabled()
@@ -33,6 +34,11 @@ def build_native_global_index_drop(builder,
partition_filter):
from pypaimon_rust.datafusion import GlobalIndexDropBuilder
if not GlobalIndexDropBuilder.supports_index_type(builder._index_type):
return None
+ if builder._index_type in VINDEX_IDENTIFIERS and
table.options.data_evolution_enabled():
+ from pypaimon_rust.datafusion import GlobalIndexBuildPlan
+ if not hasattr(GlobalIndexBuildPlan, 'replacement_messages'):
+ # Older cores match the entire field list and miss colocated
Bitmaps.
+ return None
native = _native_table(table).new_global_index_drop_builder()
native.with_index_columns(builder._index_columns).with_index_type(builder._index_type)
if partition_filter is not None:
diff --git a/paimon-python/pypaimon/execution/python/read/search/factories.py
b/paimon-python/pypaimon/execution/python/read/search/factories.py
index 6f81e53a8c..6b252801b5 100644
--- a/paimon-python/pypaimon/execution/python/read/search/factories.py
+++ b/paimon-python/pypaimon/execution/python/read/search/factories.py
@@ -19,6 +19,8 @@
from typing import NamedTuple
+from pypaimon.globalindex.vindex_options import is_multi_vector_type
+
class _VectorSearchTypes(NamedTuple):
scan: type
@@ -27,6 +29,10 @@ class _VectorSearchTypes(NamedTuple):
def _vector_search_types(request):
+ if (getattr(request, '_multi_vector', None) is not None
+ or is_multi_vector_type(getattr(request._vector_column, 'type',
None))):
+ raise NotImplementedError(
+ 'MultiVector search requires read.native.enabled and a supported
pypaimon-rust runtime and table.')
if request._is_primary_key_vector_search():
from pypaimon.execution.python.read.search.primary_key_vector_scan
import PrimaryKeyVectorScan
from pypaimon.execution.python.read.search.primary_key_vector_read
import PrimaryKeyVectorRead
diff --git
a/paimon-python/pypaimon/execution/python/read/search/vector_search_scan.py
b/paimon-python/pypaimon/execution/python/read/search/vector_search_scan.py
index 726980c06f..a85d28da16 100644
--- a/paimon-python/pypaimon/execution/python/read/search/vector_search_scan.py
+++ b/paimon-python/pypaimon/execution/python/read/search/vector_search_scan.py
@@ -53,8 +53,7 @@ class DataEvolutionVectorScan(VectorSearchScan):
self._partition_filter = partition_filter
self._options = dict(options or {})
- def scan(self):
- # type: () -> VectorSearchScanPlan
+ def scan(self, *, partition_entries=None):
from pypaimon.index.index_file_handler import IndexFileHandler
from pypaimon.read.push_down_utils import _get_all_fields
from pypaimon.snapshot.time_travel_util import TimeTravelUtil
@@ -76,8 +75,6 @@ class DataEvolutionVectorScan(VectorSearchScan):
if snapshot is None:
return VectorSearchScanPlan([])
- index_file_handler = IndexFileHandler(table=self._table)
-
partition_filter = self._partition_filter
def contains_field(global_index_meta, field_id):
@@ -88,7 +85,7 @@ class DataEvolutionVectorScan(VectorSearchScan):
return False
def index_file_filter(entry):
- if partition_filter is not None:
+ if partition_entries is None and partition_filter is not None:
if not partition_filter.test(entry.partition):
return False
global_index_meta = entry.index_file.global_index_meta
@@ -104,7 +101,10 @@ class DataEvolutionVectorScan(VectorSearchScan):
return True
return False
- entries = index_file_handler.scan(snapshot, index_file_filter)
+ if partition_entries is None:
+ entries = IndexFileHandler(self._table).scan(snapshot,
index_file_filter)
+ else:
+ entries = [entry for entry in partition_entries if
index_file_filter(entry)]
all_index_files = [entry.index_file for entry in entries]
# Group vector index files by (rowRangeStart, rowRangeEnd).
diff --git
a/paimon-python/pypaimon/execution/python/write/commit/global_index_source_check.py
b/paimon-python/pypaimon/execution/python/write/commit/global_index_source_check.py
index 207f12d55a..e75cdff833 100644
---
a/paimon-python/pypaimon/execution/python/write/commit/global_index_source_check.py
+++
b/paimon-python/pypaimon/execution/python/write/commit/global_index_source_check.py
@@ -16,6 +16,8 @@
"""Revalidate unpublished indexes against the data scanned to build them."""
+from collections import defaultdict
+
from pypaimon.index.data_evolution_index_source_meta import
DataEvolutionIndexSourceMeta
from pypaimon.utils.range import Range
@@ -23,16 +25,23 @@ from pypaimon.utils.range import Range
def check_global_index_sources(detection, latest_snapshot, merged_entries,
delta_entries, index_entries):
if not detection.data_evolution_enabled:
return None
+ snapshots = {latest_snapshot.id: latest_snapshot} if latest_snapshot is
not None else {}
sources = []
for entry in detection.global_index_file_additions(index_entries):
meta = entry.index_file.global_index_meta
+ if meta.is_centroid_index() and not meta.is_centroid_router():
+ # The manifest validates common source metadata and row ranges for
the group.
+ continue
if not
DataEvolutionIndexSourceMeta.is_data_evolution_meta(meta.source_meta):
continue
source_id =
DataEvolutionIndexSourceMeta.deserialize(meta.source_meta).scan_snapshot_id
if latest_snapshot is None or source_id > latest_snapshot.id:
return RuntimeError('Global index source conflict: source snapshot
is not available.')
- if detection.snapshot_manager.get_snapshot_by_id(source_id) is None:
- return RuntimeError('Global index source conflict: source snapshot
{} is missing.'.format(source_id))
+ if source_id not in snapshots:
+ snapshot = detection.snapshot_manager.get_snapshot_by_id(source_id)
+ if snapshot is None:
+ return RuntimeError('Global index source conflict: source
snapshot {} is missing.'.format(source_id))
+ snapshots[source_id] = snapshot
sources.append((source_id, entry))
if not sources:
return None
@@ -43,33 +52,64 @@ def check_global_index_sources(detection, latest_snapshot,
merged_entries, delta
if conflict is not None:
return conflict
earliest = min(source_id for source_id, _ in sources)
+ centroid_sources = [(source_id, entry) for source_id, entry in sources
+ if
entry.index_file.global_index_meta.is_centroid_router()]
for snapshot_id in range(earliest + 1, latest_snapshot.id + 1):
- snapshot = detection.snapshot_manager.get_snapshot_by_id(snapshot_id)
+ snapshot = snapshots.get(snapshot_id) or
detection.snapshot_manager.get_snapshot_by_id(snapshot_id)
if snapshot is None:
return RuntimeError('Global index source conflict: snapshot {} is
missing.'.format(snapshot_id))
- if snapshot.commit_kind == 'COMPACT':
+ compact = snapshot.commit_kind == 'COMPACT'
+ active = [(source_id, entry) for source_id, entry in (centroid_sources
if compact else sources)
+ if source_id < snapshot_id]
+ if not active:
continue
+ # Java's DELTA scan includes removed files. A deleted partial-column
+ # file can expose an older value for a row still covered by other
files.
changes =
detection.commit_scanner.read_incremental_raw_entries_from_changed_partitions(
- snapshot, [], index_entries=[entry for _, entry in sources])
- conflict = _check_column_changes(detection, sources, changes,
snapshot_id)
+ snapshot, [], index_entries=[entry for _, entry in active])
+ conflict = _check_column_changes(detection, active, changes,
snapshot_id)
if conflict is not None:
return conflict
return None
+def check_retained_centroid_indexes(detection, snapshot, existing_row_changes,
index_entries):
+ from pypaimon.index.index_file_handler import IndexFileHandler
+
+ updates = [entry for entry in existing_row_changes if entry.kind == 0]
+ deletes = [entry for entry in existing_row_changes if entry.kind == 1]
+ removed = {entry.index_file.file_name for entry in index_entries if
entry.kind == 1}
+
+ def retained(entry):
+ meta = entry.index_file.global_index_meta
+ return (meta is not None and meta.is_centroid_router() and
entry.index_file.file_name not in removed
+ and (deletes or meta.has_centroid_bitmap_fields()))
+
+ sources = [(snapshot.id, entry) for entry in
IndexFileHandler(detection.table).scan(snapshot, retained)]
+ if deletes and sources and _check_column_changes(detection, sources,
deletes) is not None:
+ raise RuntimeError("Delete affects an active centroid index. Prepare
the delete again or drop the index.")
+ bitmap_sources = [(source_id, entry) for source_id, entry in sources
+ if
entry.index_file.global_index_meta.has_centroid_bitmap_fields()]
+ if updates and bitmap_sources and _check_column_changes(detection,
bitmap_sources, updates) is not None:
+ raise RuntimeError("Update affects an active centroid index with
Bitmap fields. "
+ "Drop the index or use DROP_PARTITION_INDEX before
updating.")
+
+
def _check_column_changes(detection, sources, changes, snapshot_id=None):
from pypaimon.execution.python.write.commit.conflict_detection import
RowIdColumnConflictChecker
field_checker = RowIdColumnConflictChecker([],
detection.table.schema_manager)
+ by_partition = defaultdict(list)
+ for source_id, index in sources:
+ by_partition[tuple(index.partition.values),
index.bucket].append((source_id, index))
for change in changes:
row_range = change.file.row_id_range()
if row_range is None:
continue
- for source_id, index in sources:
+ partition = (tuple(change.partition.values), change.bucket)
+ for source_id, index in by_partition.get(partition, ()):
if snapshot_id is not None and snapshot_id <= source_id:
continue
- if tuple(index.partition.values) != tuple(change.partition.values)
or index.bucket != change.bucket:
- continue
meta = index.index_file.global_index_meta
if not row_range.overlaps(Range(meta.row_range_start,
meta.row_range_end)):
continue
diff --git a/paimon-python/pypaimon/execution/python/write/file_store_commit.py
b/paimon-python/pypaimon/execution/python/write/file_store_commit.py
index 70a22ddfd6..6577693eb3 100644
--- a/paimon-python/pypaimon/execution/python/write/file_store_commit.py
+++ b/paimon-python/pypaimon/execution/python/write/file_store_commit.py
@@ -548,12 +548,16 @@ class FileStoreCommit:
# Automatic rollback can delete snapshots and tags already
used by readers.
raise conflict_exception
- # Capture existing-row updates before assigning row IDs to new appends.
+ # Capture changes to existing rows before assigning row IDs to new
appends.
# Deletion vectors make mixed update/delete commits OVERWRITE.
- update_files = [
- entry.file for entry in commit_entries
- if entry.kind == 0 and entry.file.first_row_id is not None
- ] if commit_kind in ('APPEND', 'OVERWRITE') and
self.table.options.data_evolution_enabled() else []
+ existing_row_changes = (
+ [entry for entry in commit_entries if entry.file.first_row_id is
not None]
+ if commit_kind in ('APPEND', 'OVERWRITE') and
self.table.options.data_evolution_enabled() else [])
+ update_files = [entry.file for entry in existing_row_changes if
entry.kind == 0]
+ if existing_row_changes and latest_snapshot is not None and
latest_snapshot.index_manifest is not None:
+ from
pypaimon.execution.python.write.commit.global_index_source_check import
check_retained_centroid_indexes
+ check_retained_centroid_indexes(
+ self.conflict_detection, latest_snapshot,
existing_row_changes, index_entries)
# Apply row tracking logic after conflict detection (matches Java
ordering)
row_tracking_enabled = self.table.options.row_tracking_enabled()
diff --git a/paimon-python/pypaimon/globalindex/create_global_index.py
b/paimon-python/pypaimon/globalindex/create_global_index.py
index 10b88a2eb8..43937fd419 100644
--- a/paimon-python/pypaimon/globalindex/create_global_index.py
+++ b/paimon-python/pypaimon/globalindex/create_global_index.py
@@ -17,6 +17,7 @@
"""Public global index build API and shared request validation."""
+from collections.abc import Mapping
from typing import Dict, List, Optional, Sequence, Union
from pypaimon.common.options.core_options import CoreOptions
@@ -26,7 +27,7 @@ from pypaimon.common.predicate import Predicate
from pypaimon.common.predicate_builder import PredicateBuilder
from pypaimon.globalindex.index_types import BTREE_IDENTIFIER,
BITMAP_IDENTIFIER
from pypaimon.globalindex.full_text_options import FULL_TEXT_IDENTIFIER
-from pypaimon.globalindex.vindex_options import VINDEX_IDENTIFIERS
+from pypaimon.globalindex.vindex_options import VINDEX_IDENTIFIERS,
is_multi_vector_type
from pypaimon.write.commit_message import CommitMessage
@@ -38,12 +39,15 @@ def create_global_index(
partitions: Optional[Union[Dict[str, object], Sequence[Dict[str,
object]]]] = None,
options: Optional[Dict[str, object]] = None,
*,
+ extra_fields=None,
execution="local",
concurrency=None,
ray_remote_args=None,
) -> int:
"""Build and commit global index files for a table.
+ ``extra_fields`` maps scalar columns to ``bitmap`` for centroid-sharded
+ vector indexes. It can be a mapping or a JSON object string.
Returns the number of index files added to the table snapshot.
"""
@@ -54,6 +58,7 @@ def create_global_index(
partition_filter=partition_filter,
partitions=partitions,
options=options,
+ extra_fields=extra_fields,
)
messages = builder.build(
execution=execution, concurrency=concurrency,
ray_remote_args=ray_remote_args)
@@ -84,6 +89,8 @@ class GlobalIndexBuilder:
partition_filter: Optional[Predicate] = None,
partitions: Optional[Union[Dict[str, object], Sequence[Dict[str,
object]]]] = None,
options: Optional[Dict[str, object]] = None,
+ *,
+ extra_fields=None,
):
self._table = table
self._index_columns = _normalize_index_columns(index_column)
@@ -91,8 +98,14 @@ class GlobalIndexBuilder:
self._partition_filter = partition_filter
self._partitions = partitions
self._user_options = dict(options or {})
- self._options = _merged_options(table, options)
- self._core_options = CoreOptions(self._options)
+ if self._index_type in VINDEX_IDENTIFIERS:
+ self._user_options = _vector_procedure_options(table,
self._user_options)
+ if extra_fields is not None:
+ if self._user_options.get("extra_fields") is not None:
+ raise ValueError("Specify extra_fields only once.")
+ self._user_options["extra_fields"] = (
+ dict(extra_fields) if isinstance(extra_fields, Mapping) else
extra_fields)
+ self._options = _merged_options(table, self._user_options)
if (
self._index_type not in _SORTED_INDEX_IDENTIFIERS
@@ -111,17 +124,14 @@ class GlobalIndexBuilder:
"Python global index build currently supports one column, got
%s."
% self._index_columns
)
- self._options = (VectorIndexOptions.resolve(self._options,
self._index_type, self._index_columns[0]).options
- if
CoreOptions._is_vector_index_type(self._index_type) else
-
self._core_options.global_index_options(self._index_type,
self._index_columns[0]))
- self._core_options = CoreOptions(self._options)
+ column = self._index_columns[0]
+ self._centroid_sharding = False
if self._index_type in VINDEX_IDENTIFIERS:
- key = self._index_type + ".sharding"
- layout = self._options.to_map().get(key, "range")
- if layout == "centroid":
- raise NotImplementedError("Centroid-sharded vector indexes
must be built with Spark.")
- if layout != "range":
- raise ValueError("%s must be range or centroid, got %s" %
(key, layout))
+ self._options, layout = self._resolve_vector_build_options(column)
+ self._centroid_sharding = layout == "centroid"
+ else:
+ self._options =
CoreOptions(self._options).global_index_options(self._index_type, column)
+ self._core_options = CoreOptions(self._options)
if not self._table.options.row_tracking_enabled():
raise ValueError(
"Table '%s' must enable 'row-tracking.enabled=true' before "
@@ -136,6 +146,37 @@ class GlobalIndexBuilder:
self._validate_unaware_bucket_table()
if self._index_type in _GENERIC_INDEX_IDENTIFIERS:
self._validate_generic_index_table()
+ self._multi_vector = (self._index_type in VINDEX_IDENTIFIERS
+ and
is_multi_vector_type(self._table.field_dict[column].type))
+ if self._user_options.get("extra_fields") is not None and not
self._centroid_sharding:
+ raise ValueError("extra_fields requires a centroid-sharded vector
index.")
+
+ def _resolve_vector_build_options(self, column):
+ # Keep flat procedure overrides separate from the table's field JSON.
+ # A procedure can also replace a field JSON definition in the defaults.
+ table_values = dict(self._table.options.options.to_map())
+ field_keys = CoreOptions._field_index_option_keys(self._index_type,
column)
+ for key, value in self._user_options.items():
+ if value is None:
+ table_values.pop(key, None)
+ elif key in field_keys:
+ table_values[key] = value
+ defaults = VectorIndexOptions.resolve(Options(table_values),
self._index_type, column).options.to_map()
+ # Rust treats only values introduced by a field declaration as field
defaults.
+ declared = {key: value for key, value in defaults.items() if value !=
table_values.get(key)}
+ explicit_values = {key: value for key, value in
self._user_options.items() if value is not None}
+ explicit = VectorIndexOptions.resolve(
+ Options(explicit_values), self._index_type, column,
default_metric=False).options.to_map()
+ field_key = "fields.%s.sharding" % column
+ index_key = self._index_type + ".sharding"
+ layout = next((str(value).strip() for value in (
+ explicit.get(field_key), explicit.get(index_key),
explicit.get("sharding"),
+ declared.get(field_key), declared.get(index_key),
declared.get("sharding"),
+ table_values.get(field_key), table_values.get(index_key),
+ ) if value is not None), "range")
+ if layout not in ("range", "centroid"):
+ raise ValueError("%s must be range or centroid, got %s" %
(index_key, layout))
+ return Options({**defaults, **explicit}), layout
def build(self, *, execution="local", concurrency=None,
ray_remote_args=None) -> List[CommitMessage]:
if execution not in ("local", "ray"):
@@ -219,3 +260,16 @@ def _merged_options(table, options: Optional[Dict[str,
object]]) -> Options:
if options:
merged.update(options)
return Options(merged)
+
+
+def _vector_procedure_options(table, options):
+ # A caller can echo the effective table options. Unchanged values keep
+ # their precedence as schema options, as in the Rust vector builder.
+ table_values = table.options.options.to_map()
+ keys = {key for key, value in table_values.items()
+ if value is not None and not key.startswith(('scan.',
'incremental-'))
+ and (key not in options or options[key] is not None)}
+ if keys and keys <= options.keys():
+ return {key: value for key, value in options.items()
+ if value is None or value != table_values.get(key)}
+ return options
diff --git a/paimon-python/pypaimon/globalindex/global_index_meta.py
b/paimon-python/pypaimon/globalindex/global_index_meta.py
index 84e5a6b9dd..703bd0b9ea 100644
--- a/paimon-python/pypaimon/globalindex/global_index_meta.py
+++ b/paimon-python/pypaimon/globalindex/global_index_meta.py
@@ -21,6 +21,9 @@ from dataclasses import dataclass
from typing import List, Optional
+CENTROID_INDEX_MAGIC = b"PAIMCENT"
+
+
@dataclass
class GlobalIndexMeta:
"""Schema for global index metadata."""
@@ -33,7 +36,13 @@ class GlobalIndexMeta:
source_meta: Optional[bytes] = None
def has_centroid_bitmap_fields(self) -> bool:
- return bool(self.extra_field_ids) and
_is_centroid_index(self.index_meta)
+ return bool(self.extra_field_ids) and self.is_centroid_index()
+
+ def is_centroid_index(self) -> bool:
+ return _is_centroid_index(self.index_meta)
+
+ def is_centroid_router(self) -> bool:
+ return self.index_meta is not None and
self.index_meta.startswith(CENTROID_INDEX_MAGIC + b"\x01R")
def __eq__(self, other: object) -> bool:
if not isinstance(other, GlobalIndexMeta):
@@ -88,11 +97,11 @@ class GlobalIndexIOMeta:
def _is_centroid_index(metadata: Optional[bytes]) -> bool:
# Paimon Core prefixes routed manifest metadata with this layout marker.
- return metadata is not None and metadata.startswith(b"PAIMCENT")
+ return metadata is not None and metadata.startswith(CENTROID_INDEX_MAGIC)
def range_vector_index_file(io_metas: List[GlobalIndexIOMeta]) ->
GlobalIndexIOMeta:
if any(_is_centroid_index(meta.metadata) for meta in io_metas):
- raise NotImplementedError("Centroid-sharded vector indexes require the
Java reader.")
+ raise NotImplementedError("Centroid-sharded vector indexes require
table-level search with pypaimon-rust.")
assert len(io_metas) == 1, "Expected exactly one index file per shard"
return io_metas[0]
diff --git a/paimon-python/pypaimon/globalindex/index_dispatch.py
b/paimon-python/pypaimon/globalindex/index_dispatch.py
index 878fcc087d..8e0334b48f 100644
--- a/paimon-python/pypaimon/globalindex/index_dispatch.py
+++ b/paimon-python/pypaimon/globalindex/index_dispatch.py
@@ -90,6 +90,11 @@ def build_global_index(request, partition_filter, *,
execution="local", concurre
ray_remote_args=ray_remote_args)
if messages is not None:
return messages
+ if request._centroid_sharding or request._multi_vector:
+ feature = 'Centroid-sharded vector indexes' if
request._centroid_sharding else 'MultiVector indexes'
+ raise NotImplementedError(
+ '%s require write.native.enabled and a supported pypaimon-rust
runtime and table.'
+ % feature)
from pypaimon.execution.python.globalindex.create_global_index import
PythonGlobalIndexBuilder
return PythonGlobalIndexBuilder(request).build(
partition_filter, execution=execution, concurrency=concurrency,
diff --git a/paimon-python/pypaimon/globalindex/vindex_options.py
b/paimon-python/pypaimon/globalindex/vindex_options.py
index 900c3b6c61..a1019a42f1 100644
--- a/paimon-python/pypaimon/globalindex/vindex_options.py
+++ b/paimon-python/pypaimon/globalindex/vindex_options.py
@@ -83,6 +83,11 @@ def train_sample_ratio(
return ratio
+def is_multi_vector_type(data_type: DataType) -> bool:
+ return (isinstance(data_type, ArrayType) and isinstance(data_type.element,
(ArrayType, VectorType))
+ and _is_float_type(data_type.element.element))
+
+
def validate_vector_type(data_type: DataType) -> None:
if isinstance(data_type, VectorType):
element_type = data_type.element
diff --git a/paimon-python/pypaimon/manifest/centroid_index_groups.py
b/paimon-python/pypaimon/manifest/centroid_index_groups.py
new file mode 100644
index 0000000000..c0188fb3a8
--- /dev/null
+++ b/paimon-python/pypaimon/manifest/centroid_index_groups.py
@@ -0,0 +1,97 @@
+# 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.
+
+"""Validate the centroid index groups written to a Python index manifest."""
+
+from collections import defaultdict
+from struct import Struct
+
+from pypaimon.index.data_evolution_index_source_meta import
DataEvolutionIndexSourceMeta
+
+
+_HEADER = Struct('>8sBci')
+
+
+def centroid_routers(entries):
+ groups = defaultdict(list)
+ for entry in entries:
+ file = entry.index_file
+ meta = file.global_index_meta
+ if entry.kind == 0 and meta is not None and meta.is_centroid_index():
+ key = (tuple(entry.partition.values), entry.bucket,
file.index_type,
+ meta.index_field_id, meta.row_range_start,
meta.row_range_end)
+ groups[key].append(entry)
+ return [_validate_group(group) for group in groups.values()]
+
+
+def _validate_group(entries):
+ invalid = RuntimeError("Incomplete or conflicting centroid generation for
'%s'" % entries[0].index_file.file_name)
+ routers = []
+ shards, bitmaps = {}, {}
+ for entry in entries:
+ file = entry.index_file
+ descriptor = file.global_index_meta.index_meta
+ if len(descriptor) < _HEADER.size:
+ raise invalid
+ _, version, role, number = _HEADER.unpack_from(descriptor)
+ if version != 1 or number < 0 or file.file_size < 0 or file.row_count
< 0:
+ raise invalid
+ if role == b'R':
+ routers.append((entry, number))
+ elif role in (b'S', b'B'):
+ parts = shards if role == b'S' else bitmaps
+ if number in parts or file.file_size == 0:
+ raise invalid
+ parts[number] = file
+ else:
+ raise invalid
+ if len(routers) != 1:
+ raise invalid
+ router, nlist = routers[0]
+ file = router.index_file
+ meta = file.global_index_meta
+ metric = meta.index_meta[_HEADER.size:]
+ extra = meta.extra_field_ids or []
+ range_length = meta.row_range_end - meta.row_range_start + 1
+ vector_count = sum(shard.row_count for shard in shards.values())
+ if (file.row_count != 0 or (file.file_size == 0) != (nlist == 0)
+ or metric not in (b'l2', b'inner_product', b'cosine')
+ or meta.index_field_id in extra or len(set(extra)) != len(extra)
+ or meta.row_range_start < 0 or range_length <= 0 or len(shards) !=
nlist
+ or vector_count > range_length or (nlist > 0 and vector_count == 0)
+ or any(shard_id >= nlist for shard_id in shards)):
+ raise invalid
+ for entry in entries:
+ part = entry.index_file.global_index_meta
+ if part.extra_field_ids != meta.extra_field_ids or part.source_meta !=
meta.source_meta:
+ raise invalid
+ for shard in shards.values():
+ payload = shard.global_index_meta.index_meta[_HEADER.size:]
+ if metric == b'l2' and file.index_type in ('ivf-flat', 'ivf-pq') and
shard.row_count:
+ if len(payload) != 4 or int.from_bytes(payload, 'big',
signed=True) <= 0:
+ raise invalid
+ elif payload:
+ raise invalid
+ expected = {i: shard.row_count for i, shard in shards.items() if extra and
shard.row_count > 0}
+ if {i: bitmap.row_count for i, bitmap in bitmaps.items()} != expected:
+ raise invalid
+ if not
DataEvolutionIndexSourceMeta.is_data_evolution_meta(meta.source_meta):
+ raise invalid
+ source = DataEvolutionIndexSourceMeta.deserialize(meta.source_meta)
+ if bitmaps and (source.source_schema_id is None or source.source_schema_id
< 0):
+ raise invalid
+ return router
diff --git a/paimon-python/pypaimon/manifest/index_manifest_file.py
b/paimon-python/pypaimon/manifest/index_manifest_file.py
index 24e9bcb363..673d01fbb9 100644
--- a/paimon-python/pypaimon/manifest/index_manifest_file.py
+++ b/paimon-python/pypaimon/manifest/index_manifest_file.py
@@ -16,6 +16,7 @@
# under the License.
import uuid
+from collections import defaultdict
from io import BytesIO
from typing import List, Optional
@@ -24,6 +25,7 @@ import fastavro
from pypaimon.globalindex.global_index_meta import GlobalIndexMeta
from pypaimon.index.deletion_vector_meta import DeletionVectorMeta
from pypaimon.index.index_file_meta import IndexFileMeta
+from pypaimon.manifest.centroid_index_groups import centroid_routers
from pypaimon.manifest.index_manifest_entry import IndexManifestEntry
from pypaimon.table.row.generic_row import (GenericRowDeserializer,
GenericRowSerializer)
@@ -256,6 +258,17 @@ class IndexManifestFile:
delete_files = {(e.index_file.index_type, e.index_file.file_name) for
e in deletes}
survivors = [e for e in previous
if (e.index_file.index_type, e.index_file.file_name) not
in delete_files]
+ if any(_is_centroid_entry(entry) for entry in deletes):
+ centroid_routers(survivors)
+ routers = centroid_routers(adds)
+ if routers:
+ ordinary_adds = [entry for entry in adds if not
_is_centroid_entry(entry)]
+ _validate_retained_global_index_files(routers, ordinary_adds)
+ for ranges in _global_index_ranges(routers).values():
+ for retained, added in zip(ranges, ranges[1:]):
+ if
_row_ranges_intersect(retained.index_file.global_index_meta,
+
added.index_file.global_index_meta):
+ _raise_global_index_overlap(retained, added)
_validate_retained_global_index_files(survivors, adds)
combined = _combine_hash_indexes(survivors, adds, deletes)
if not combined:
@@ -342,39 +355,53 @@ def _validate_retained_global_index_files(
retained_entries: List[IndexManifestEntry],
added_entries: List[IndexManifestEntry],
) -> None:
- for retained in retained_entries:
- retained_file = retained.index_file
- retained_meta = retained_file.global_index_meta
- if retained_meta is None or not
_is_global_index(retained_file.index_type):
+ additions = _global_index_ranges(added_entries)
+ if not additions:
+ return
+ for key, ranges in _global_index_ranges(retained_entries).items():
+ candidates = iter(additions.get(key, ()))
+ added = next(candidates, None)
+ for retained in ranges:
+ retained_meta = retained.index_file.global_index_meta
+ while (added is not None
+ and added.index_file.global_index_meta.row_range_end <
retained_meta.row_range_start):
+ added = next(candidates, None)
+ if added is None:
+ break
+ if _row_ranges_intersect(retained_meta,
added.index_file.global_index_meta):
+ _raise_global_index_overlap(retained, added)
+
+
+def _global_index_ranges(entries):
+ groups = defaultdict(list)
+ for entry in entries:
+ file = entry.index_file
+ meta = file.global_index_meta
+ if entry.kind != _ADD or meta is None or not
_is_global_index(file.index_type):
continue
-
- for added in added_entries:
- added_file = added.index_file
- added_meta = added_file.global_index_meta
- if (
- added.kind != _ADD
- or added_meta is None
- or added_file.index_type != retained_file.index_type
- or retained_meta.index_field_id != added_meta.index_field_id
- or _can_keep_existing_global_index(retained_meta, added_meta)
- ):
- continue
-
- raise RuntimeError(
- "Trying to add global index file %s of type %s for index field
%s"
- " with row range [%s, %s], but previous file %s still exists"
- " with overlapping row range [%s, %s]. Remove the previous
file first."
- % (
- added_file.file_name,
- added_file.index_type,
- added_meta.index_field_id,
- added_meta.row_range_start,
- added_meta.row_range_end,
- retained_file.file_name,
- retained_meta.row_range_start,
- retained_meta.row_range_end,
- )
- )
+ # A centroid group has the same range and fields as its router.
+ if meta.is_centroid_index() and not meta.is_centroid_router():
+ continue
+ extra = () if meta.has_centroid_bitmap_fields() else
tuple(meta.extra_field_ids or ())
+ groups[tuple(entry.partition.values), file.index_type,
meta.index_field_id, extra].append(entry)
+ for ranges in groups.values():
+ ranges.sort(key=lambda entry:
entry.index_file.global_index_meta.row_range_start)
+ return groups
+
+
+def _raise_global_index_overlap(retained, added):
+ retained_file = retained.index_file
+ retained_meta = retained_file.global_index_meta
+ added_file = added.index_file
+ added_meta = added_file.global_index_meta
+ raise RuntimeError(
+ "Trying to add global index file %s of type %s for index field %s"
+ " with row range [%s, %s], but previous file %s still exists"
+ " with overlapping row range [%s, %s]. Remove the previous file first."
+ % (added_file.file_name, added_file.index_type,
added_meta.index_field_id,
+ added_meta.row_range_start, added_meta.row_range_end,
retained_file.file_name,
+ retained_meta.row_range_start, retained_meta.row_range_end)
+ )
def _combine_hash_indexes(retained_entries, added_entries, deleted_entries):
@@ -403,18 +430,9 @@ def _is_global_index(index_type: str) -> bool:
return index_type not in (IndexManifestFile.DELETION_VECTORS_INDEX,
_HASH_INDEX)
-def _can_keep_existing_global_index(retained_meta, added_meta) -> bool:
- # The caller has already matched the index type and primary field.
- return (
- _index_definition_extra_field_ids(retained_meta) !=
_index_definition_extra_field_ids(added_meta)
- or not _row_ranges_intersect(retained_meta, added_meta)
- )
-
-
-def _index_definition_extra_field_ids(global_index_meta) ->
Optional[List[int]]:
- if global_index_meta.has_centroid_bitmap_fields():
- return None
- return global_index_meta.extra_field_ids or None
+def _is_centroid_entry(entry: IndexManifestEntry) -> bool:
+ meta = entry.index_file.global_index_meta
+ return meta is not None and meta.is_centroid_index()
def _row_ranges_intersect(left, right) -> bool:
diff --git a/paimon-python/pypaimon/multimodal/table.py
b/paimon-python/pypaimon/multimodal/table.py
index de39dcb5be..26f6668fda 100644
--- a/paimon-python/pypaimon/multimodal/table.py
+++ b/paimon-python/pypaimon/multimodal/table.py
@@ -798,10 +798,11 @@ class MultimodalTable:
pre_filter=pre_filter,
)
- def create_index(self, column, index_type, options=None, *,
execution="local",
+ def create_index(self, column, index_type, options=None, *,
extra_fields=None, execution="local",
concurrency=None, ray_remote_args=None):
return self.raw_table.create_global_index(
column, index_type=_normalize_index_type(index_type),
options=options,
+ extra_fields=extra_fields,
execution=execution, concurrency=concurrency,
ray_remote_args=ray_remote_args)
def _merge(
diff --git a/paimon-python/pypaimon/table/file_store_table.py
b/paimon-python/pypaimon/table/file_store_table.py
index 860307454f..ebf55df4d1 100644
--- a/paimon-python/pypaimon/table/file_store_table.py
+++ b/paimon-python/pypaimon/table/file_store_table.py
@@ -424,7 +424,7 @@ class FileStoreTable(Table):
def create_global_index(self, index_column, index_type: str = "btree",
partition_filter=None, partitions=None,
- options: Optional[dict] = None, *,
execution="local",
+ options: Optional[dict] = None, *,
extra_fields=None, execution="local",
concurrency=None, ray_remote_args=None) -> int:
from pypaimon.globalindex.create_global_index import \
create_global_index
@@ -435,6 +435,7 @@ class FileStoreTable(Table):
partition_filter=partition_filter,
partitions=partitions,
options=options,
+ extra_fields=extra_fields,
execution=execution, concurrency=concurrency,
ray_remote_args=ray_remote_args,
)
diff --git a/paimon-python/pypaimon/table/source/search_dispatch.py
b/paimon-python/pypaimon/table/source/search_dispatch.py
index fda7e15fbd..c2d2df3ed6 100644
--- a/paimon-python/pypaimon/table/source/search_dispatch.py
+++ b/paimon-python/pypaimon/table/source/search_dispatch.py
@@ -95,13 +95,16 @@ class _SearchRead:
self._python_executor = self._python_factory()
return self._python_executor
+ def _reader_for(self, plan=None, splits=()):
+ return self._native_reader
+
def read_plan(self, plan, executor=None):
- return (self._native_reader.read_plan(plan) if executor is None else
- self._native_reader.read_plan(plan, executor=executor))
+ reader = self._reader_for(plan)
+ return reader.read_plan(plan) if executor is None else
reader.read_plan(plan, executor=executor)
def read_batch_plan(self, plan, executor=None):
- return (self._native_reader.read_batch_plan(plan) if executor is None
else
- self._native_reader.read_batch_plan(plan, executor=executor))
+ reader = self._reader_for(plan)
+ return reader.read_batch_plan(plan) if executor is None else
reader.read_batch_plan(plan, executor=executor)
class _SplitSearchRead(_SearchRead):
@@ -114,6 +117,59 @@ class _BatchSearchRead(_SearchRead):
return self._native_reader.read_batch(splits)
+class _FilesystemVectorScan:
+ def __init__(self, builder, batch):
+ self._builder = builder
+ self._batch = batch
+
+ def scan(self):
+ from pypaimon.execution.native.read.native_search_plan import
native_vector_scan
+ from pypaimon.execution.native.read.native_vector_search import (
+ _filesystem_vector_search_view, _has_centroid_indexes,
+ )
+
+ request = copy(self._builder)
+ request._table, entries =
_filesystem_vector_search_view(request._table, request._partition_filter)
+ if _has_centroid_indexes(entries, [request._vector_column]):
+ scan = native_vector_scan(request, self._batch)
+ if scan is not None:
+ return scan.scan()
+ return _python_vector_scan(request).scan(partition_entries=entries)
+
+
+class _FilesystemVectorRead(_SearchRead):
+ def __init__(self, native_factory, python_factory):
+ super().__init__(None, python_factory)
+ self._native_factory = native_factory
+
+ def _reader_for(self, plan=None, splits=()):
+ from pypaimon.table.source.vector_search_split import
IndexVectorSearchSplit
+
+ if plan is not None:
+ splits = plan.splits()
+ native = any(getattr(split, '_native_vector_layout', False) for split
in splits) or any(
+ file.global_index_meta is not None and
file.global_index_meta.is_centroid_index()
+ for split in splits if isinstance(split, IndexVectorSearchSplit)
for file in split.vector_index_files)
+ if native:
+ if self._native_reader is None:
+ self._native_reader = self._native_factory()
+ if self._native_reader is not None:
+ return self._native_reader
+ return self._python_reader()
+
+
+class _FilesystemSingleVectorRead(_FilesystemVectorRead):
+ def read(self, splits):
+ splits = list(splits)
+ return self._reader_for(splits=splits).read(splits)
+
+
+class _FilesystemBatchVectorRead(_FilesystemVectorRead):
+ def read_batch(self, splits):
+ splits = list(splits)
+ return self._reader_for(splits=splits).read_batch(splits)
+
+
def python_search_reader(reader):
"""Select Python explicitly for backend parity and transported-plan
checks."""
return reader._python_reader() if isinstance(reader, _SearchRead) else
reader
@@ -127,11 +183,21 @@ def _native_requested(builder):
return callable(enabled) and enabled()
+def _filesystem_vector_layout_dispatch(builder):
+ from pypaimon.execution.native.read.native_vector_search import (
+ _filesystem_vector_search_supported, _multi_vector_requested,
+ )
+ return (not getattr(builder, '_native_hybrid_route', False)
+ and not _multi_vector_requested(builder) and
_filesystem_vector_search_supported(builder._table))
+
+
def create_vector_scan(builder, execution, batch=False):
python_factory = partial(_python_vector_scan, execution)
if not _native_requested(builder):
return python_factory()
from pypaimon.execution.native.read.native_search_plan import
native_vector_scan
+ if _filesystem_vector_layout_dispatch(builder):
+ return _FilesystemVectorScan(execution, batch)
native = native_vector_scan(builder, batch)
return python_factory() if native is None else _SearchScan(native,
python_factory)
@@ -141,6 +207,9 @@ def create_vector_read(builder, batch=False):
if not _native_requested(builder):
return python_factory()
from pypaimon.execution.native.read.native_search_plan import
native_vector_read
+ if _filesystem_vector_layout_dispatch(builder):
+ reader_type = _FilesystemBatchVectorRead if batch else
_FilesystemSingleVectorRead
+ return reader_type(partial(native_vector_read, builder, batch),
python_factory)
native = native_vector_read(builder, batch)
if native is None:
return python_factory()
@@ -167,7 +236,7 @@ def create_full_text_read(builder, execution):
def execute_vector_search(builder, queries, batch=False):
- if _native_requested(builder):
+ if _native_requested(builder) and not
_filesystem_vector_layout_dispatch(builder):
from pypaimon.execution.native.read.native_vector_search import
try_native_vector_search
result = try_native_vector_search(builder, queries, batch)
if result is not None:
@@ -195,14 +264,40 @@ def _standard_hybrid_builder(builder):
'route_builders', 'to_route_result', 'rank',
'_new_vector_search_builder', '_new_full_text_search_builder'))
+def _hybrid_search_request(builder):
+ from pypaimon.catalog.table_query_auth import
reject_search_under_query_auth
+ from pypaimon.execution.native.read.native_vector_search import (
+ _filesystem_vector_search_supported, _filesystem_vector_search_view,
_has_centroid_indexes,
+ )
+ from pypaimon.globalindex.vindex_options import is_multi_vector_type
+
+ reject_search_under_query_auth(builder._table)
+ if not _filesystem_vector_search_supported(builder._table):
+ return builder, True
+ builder._validate_search()
+ try:
+ fields = [builder._table.field_dict[route.field_name] for route in
builder._routes if route.is_vector()]
+ except KeyError as exc:
+ raise ValueError("Vector column '%s' not found in table schema" %
exc.args[0]) from exc
+ if not fields:
+ return builder, False
+ if any(is_multi_vector_type(field.type) for field in fields):
+ return builder, True
+ request = copy(builder)
+ request._table, entries = _filesystem_vector_search_view(builder._table,
builder._partition_filter)
+ return request, _has_centroid_indexes(entries, fields)
+
+
def execute_hybrid_search(builder, executor=None):
standard = _standard_hybrid_builder(builder)
if standard and _native_requested(builder):
from pypaimon.execution.native.read.native_hybrid_search import
try_native_hybrid_search
- result = (try_native_hybrid_search(builder) if executor is None else
- try_native_hybrid_search(builder, executor=executor))
- if result is not None:
- return result
+ builder, native = _hybrid_search_request(builder)
+ if native:
+ result = (try_native_hybrid_search(builder) if executor is None
else
+ try_native_hybrid_search(builder, executor=executor))
+ if result is not None:
+ return result
from pypaimon.execution.python.read.search.hybrid_search import execute
return execute(builder, executor)
@@ -214,9 +309,11 @@ def hybrid_route_builders(builder):
reject_search_under_query_auth(builder._table)
if _native_requested(builder):
from pypaimon.execution.native.read.native_hybrid_search import
try_native_hybrid_routes
- routes = try_native_hybrid_routes(builder)
- if routes is not None:
- return routes
+ builder, native = _hybrid_search_request(builder)
+ if native:
+ routes = try_native_hybrid_routes(builder)
+ if routes is not None:
+ return routes
from pypaimon.execution.python.read.search.hybrid_search import
route_builders
return route_builders(builder)
diff --git a/paimon-python/pypaimon/table/source/search_types.py
b/paimon-python/pypaimon/table/source/search_types.py
index 5e846f67ee..4fb4288331 100644
--- a/paimon-python/pypaimon/table/source/search_types.py
+++ b/paimon-python/pypaimon/table/source/search_types.py
@@ -31,8 +31,7 @@ class VectorSearchScanPlan:
"""Plan of vector search scan."""
def __init__(self, splits, snapshot=None):
- # type: (list, object) -> None
- self._splits = splits
+ self._splits = splits if isinstance(splits, (list, tuple)) else
list(splits)
self._snapshot = snapshot
def splits(self):
diff --git a/paimon-python/pypaimon/table/source/vector_search_builder.py
b/paimon-python/pypaimon/table/source/vector_search_builder.py
index c20d7428d6..3913de71c4 100644
--- a/paimon-python/pypaimon/table/source/vector_search_builder.py
+++ b/paimon-python/pypaimon/table/source/vector_search_builder.py
@@ -19,12 +19,14 @@
from abc import ABC, abstractmethod
from copy import copy
+from math import isfinite
from pypaimon.common.options.core_options import CoreOptions
from pypaimon.common.options.vector_index_options import VectorIndexOptions
from pypaimon.catalog.table_query_auth import reject_search_under_query_auth
from pypaimon.common.predicate_builder import PredicateBuilder
from pypaimon.common.options.options import Options
+from pypaimon.globalindex.vindex_options import is_multi_vector_type
class VectorSearchBuilder(ABC):
@@ -48,6 +50,10 @@ class VectorSearchBuilder(ABC):
"""The query vector (list of floats)."""
pass
+ def with_multi_vector(self, vectors):
+ """Rank each row's embedding list against a query matrix using cosine
MaxSim."""
+ raise NotImplementedError("%s does not support MultiVector search." %
type(self).__name__)
+
def with_option(self, key, value):
# type: (str, str) -> VectorSearchBuilder
"""Option for vector indexes."""
@@ -223,6 +229,7 @@ class AbstractVectorSearchBuilderImpl:
reject_search_under_query_auth(self._table)
if self._vector_column is None:
raise ValueError("Vector column must be set via
with_vector_column()")
+ self._validate_query_matrix_column()
from pypaimon.table.source.search_dispatch import create_vector_scan
execution = copy(self)
execution._options = dict(self._options)
@@ -233,6 +240,12 @@ class AbstractVectorSearchBuilderImpl:
return False
return self._vector_column.name in
VectorIndexOptions.columns(Options(dict(self._table.table_schema.options)))
+ def _validate_query_matrix_column(self):
+ if getattr(self, '_multi_vector', None) is not None and (
+ not self._table.options.data_evolution_enabled()
+ or not is_multi_vector_type(getattr(self._vector_column,
'type', None))):
+ raise ValueError("A query matrix requires a MultiVector column on
a Data Evolution table.")
+
class VectorSearchBuilderImpl(AbstractVectorSearchBuilderImpl,
VectorSearchBuilder):
"""Implementation for VectorSearchBuilder."""
@@ -240,13 +253,31 @@ class
VectorSearchBuilderImpl(AbstractVectorSearchBuilderImpl, VectorSearchBuild
def __init__(self, table):
super().__init__(table)
self._query_vector = None
+ self._multi_vector = None
def with_query_vector(self, vector):
# type: (list) -> VectorSearchBuilder
self._query_vector = vector
+ self._multi_vector = None
+ return self
+
+ def with_multi_vector(self, vectors):
+ try:
+ query = tuple(tuple(vector) for vector in vectors)
+ valid = (query and query[0] and all(len(vector) == len(query[0])
for vector in query)
+ and all(isfinite(value) for vector in query for value in
vector))
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise ValueError("A query matrix requires numeric vectors with
finite coordinates.") from exc
+ if not valid:
+ raise ValueError("A query matrix requires non-empty, equally sized
vectors with finite coordinates.")
+ self._multi_vector = query
+ self._query_vector = None
return self
def execute_local(self):
+ if self._multi_vector is not None:
+ reject_search_under_query_auth(self._table)
+ self._validate_query_matrix_column()
from pypaimon.table.source.search_dispatch import execute_vector_search
return execute_vector_search(self, self._query_vector)
@@ -257,8 +288,9 @@ class
VectorSearchBuilderImpl(AbstractVectorSearchBuilderImpl, VectorSearchBuild
raise ValueError("Limit must be positive, set via with_limit()")
if self._vector_column is None:
raise ValueError("Vector column must be set via
with_vector_column()")
- if self._query_vector is None:
- raise ValueError("Query vector must be set via
with_query_vector()")
+ self._validate_query_matrix_column()
+ if self._query_vector is None and self._multi_vector is None:
+ raise ValueError("Query must be set via with_query_vector() or
with_multi_vector()")
from pypaimon.table.source.search_dispatch import create_vector_read
execution = copy(self)
execution._options = dict(self._options)
diff --git a/paimon-python/pypaimon/table/source/vector_search_split.py
b/paimon-python/pypaimon/table/source/vector_search_split.py
index a8f2428688..89c939ae2e 100644
--- a/paimon-python/pypaimon/table/source/vector_search_split.py
+++ b/paimon-python/pypaimon/table/source/vector_search_split.py
@@ -33,6 +33,8 @@ class VectorSearchSplit:
``isinstance``.
"""
+ _native_vector_layout = False
+
def __new__(
cls,
row_range_start=None,
@@ -67,3 +69,4 @@ class RawVectorSearchSplit(VectorSearchSplit):
row_ranges: List[Range]
scalar_index_files: List[IndexFileMeta] = field(default_factory=list)
index_type: Optional[str] = None
+ _scalar_prefilter_ranges: List[Range] = field(default_factory=list,
init=False, repr=False)
diff --git a/paimon-python/pypaimon/tests/global_index_build_test.py
b/paimon-python/pypaimon/tests/global_index_build_test.py
index 0617694e87..e73c28320f 100644
--- a/paimon-python/pypaimon/tests/global_index_build_test.py
+++ b/paimon-python/pypaimon/tests/global_index_build_test.py
@@ -230,12 +230,16 @@ class GlobalIndexBuildTest(
'file.format': 'parquet',
}
- def test_centroid_sharding_requires_spark(self):
+ def test_centroid_sharding_requires_native_build(self):
schema = pa.schema([('embedding', pa.list_(pa.float32()))])
- table = self._create_table(pa_schema=schema,
options={**self.table_options, 'ivf-pq.sharding': 'centroid'})
- with self.assertRaisesRegex(NotImplementedError, "built with Spark"):
- GlobalIndexBuilder(table, 'embedding', 'ivf-pq')
- GlobalIndexBuilder(table, 'embedding', 'ivf-pq',
options={'ivf-pq.sharding': 'range'})
+ table = self._create_table(pa_schema=schema, options={
+ **self.table_options, 'fields.embedding.sharding': 'centroid',
'write.native.enabled': 'false',
+ })
+ with self.assertRaisesRegex(NotImplementedError, "pypaimon-rust"):
+ GlobalIndexBuilder(table, 'embedding', 'ivf-pq').build()
+ self.assertEqual([], GlobalIndexBuilder(table, 'embedding', 'ivf-pq',
options={'sharding': 'range'}).build())
+ with self.assertRaisesRegex(ValueError, "extra_fields requires a
centroid-sharded vector index"):
+ GlobalIndexBuilder(table, 'embedding', 'ivf-pq',
options={'sharding': 'range'}, extra_fields={})
def test_centroid_bitmaps_share_the_primary_vector_index_definition(self):
schema = pa.schema([('embedding', pa.list_(pa.float32())), ('status',
pa.string())])
@@ -251,11 +255,13 @@ class GlobalIndexBuildTest(
vector_id = table.field_dict['embedding'].id
status_id = table.field_dict['status'].id
partition = GenericRow([], [])
+ from pypaimon.index.data_evolution_index_source_meta import
DataEvolutionIndexSourceMeta
+ source = DataEvolutionIndexSourceMeta(1,
table.table_schema.id).serialize()
def entry(name, rows, metadata, fields=None):
return IndexManifestEntry(0, partition, 0, IndexFileMeta(
'ivf-flat', name, 100, rows,
- global_index_meta=GlobalIndexMeta(0, 0, vector_id, fields,
metadata)))
+ global_index_meta=GlobalIndexMeta(0, 0, vector_id, fields,
metadata, source)))
centroid_files = []
for role, rows, number, payload in (
diff --git a/paimon-python/pypaimon/tests/hybrid_hook_backend_retention_test.py
b/paimon-python/pypaimon/tests/hybrid_hook_backend_retention_test.py
index 36f828a2f9..62cdaf558c 100644
--- a/paimon-python/pypaimon/tests/hybrid_hook_backend_retention_test.py
+++ b/paimon-python/pypaimon/tests/hybrid_hook_backend_retention_test.py
@@ -155,6 +155,8 @@ def
test_failed_python_hook_does_not_change_standalone_phase_selection(search_ta
del builder.rank
expected_rank, expected_routes = object(), object()
with patch('pypaimon.execution.native.runtime.native_runtime_available',
return_value=True), \
+
patch('pypaimon.execution.native.read.native_vector_search._filesystem_vector_search_supported',
+ return_value=False), \
patch('pypaimon.execution.native.read.native_hybrid_search.rank_hybrid_results',
return_value=expected_rank) as native_rank, \
patch('pypaimon.execution.native.read.native_hybrid_search.try_native_hybrid_routes',
@@ -193,6 +195,8 @@ def
test_active_python_hook_does_not_change_another_threads_phase_selection(sear
return expected_routes
with patch('pypaimon.execution.native.runtime.native_runtime_available',
return_value=True), \
+
patch('pypaimon.execution.native.read.native_vector_search._filesystem_vector_search_supported',
+ return_value=False), \
patch('pypaimon.execution.native.read.native_hybrid_search.rank_hybrid_results',
side_effect=native_rank) as rank, \
patch('pypaimon.execution.native.read.native_hybrid_search.try_native_hybrid_routes',
diff --git a/paimon-python/pypaimon/tests/hybrid_search_phase_dispatch_test.py
b/paimon-python/pypaimon/tests/hybrid_search_phase_dispatch_test.py
index c9b358eaf4..e478ab8576 100644
--- a/paimon-python/pypaimon/tests/hybrid_search_phase_dispatch_test.py
+++ b/paimon-python/pypaimon/tests/hybrid_search_phase_dispatch_test.py
@@ -58,6 +58,8 @@ def
test_native_phase_uses_dispatch_without_python_execution(search_table, phase
target = 'try_native_hybrid_routes' if phase == 'routes' else
'rank_hybrid_results'
with patch('pypaimon.execution.native.read.native_hybrid_search.' +
target, return_value=expected) as native, \
patch('pypaimon.execution.native.runtime.native_runtime_available',
return_value=True), \
+
patch('pypaimon.execution.native.read.native_vector_search._filesystem_vector_search_supported',
+ return_value=False), \
patch('pypaimon.execution.python.read.search.hybrid_search.route_builders',
side_effect=AssertionError('Python route planning')), \
patch('pypaimon.execution.python.read.search.hybrid_search.rank',
@@ -74,6 +76,8 @@ def
test_native_phase_failure_is_not_replayed_in_python(search_table, phase):
builder = _builder(search_table)
with patch('pypaimon.execution.native.read.native_hybrid_search.' +
target, side_effect=failure), \
patch('pypaimon.execution.native.runtime.native_runtime_available',
return_value=True), \
+
patch('pypaimon.execution.native.read.native_vector_search._filesystem_vector_search_supported',
+ return_value=False), \
patch('pypaimon.execution.python.read.search.hybrid_search.route_builders') as
routes, \
patch('pypaimon.execution.python.read.search.hybrid_search.rank')
as rank:
with pytest.raises(RuntimeError) as caught:
diff --git a/paimon-python/pypaimon/tests/lazy_search_execution_test.py
b/paimon-python/pypaimon/tests/lazy_search_execution_test.py
index 5f1d77d3ba..1b7b124704 100644
--- a/paimon-python/pypaimon/tests/lazy_search_execution_test.py
+++ b/paimon-python/pypaimon/tests/lazy_search_execution_test.py
@@ -32,7 +32,7 @@ from pypaimon.table.source.search_types import
FullTextScanPlan, VectorSearchSca
@pytest.fixture
-def search_table(tmp_path):
+def filesystem_search_table(tmp_path):
catalog = CatalogFactory.create({'warehouse': str(tmp_path / 'warehouse')})
catalog.create_database('default', True)
catalog.create_table('default.search', Schema.from_pyarrow_schema(
@@ -42,6 +42,14 @@ def search_table(tmp_path):
return catalog.get_table('default.search')
[email protected]
+def search_table(filesystem_search_table, monkeypatch):
+ # These adapter tests supply the existing native route with test doubles.
+
monkeypatch.setattr('pypaimon.execution.native.read.native_vector_search._filesystem_vector_table_supported',
+ lambda table: False)
+ return filesystem_search_table
+
+
def _builder(table, family):
if family == 'text':
return table.new_full_text_search_builder().with_query('body',
'needle').with_limit(2)
@@ -903,7 +911,7 @@ def
test_search_plan_conversion_rejects_splits_from_the_other_search_family(sear
@pytest.mark.parametrize('family', ['vector', 'batch', 'text'])
-def
test_selected_native_reader_does_not_probe_or_replay_an_older_sdk(search_table,
family):
+def
test_selected_native_reader_does_not_probe_or_replay_an_older_sdk(filesystem_search_table,
family):
class OlderSdk(ModuleType):
def __getattr__(self, name):
if name in ('VectorScanPlan', 'FullTextScanPlan'):
@@ -913,7 +921,7 @@ def
test_selected_native_reader_does_not_probe_or_replay_an_older_sdk(search_tab
sdk, datafusion = ModuleType('pypaimon_rust'),
OlderSdk('pypaimon_rust.datafusion')
sdk.datafusion = datafusion
native, _, core_read = _native_builder(family)
- builder = _builder(search_table, family)
+ builder = _builder(filesystem_search_table, family)
_, read_factory = _factories(builder, family)
with patch.dict('sys.modules', {'pypaimon_rust': sdk,
'pypaimon_rust.datafusion': datafusion}), \
_forbid_python_execution(), patch(_native_factory(family),
return_value=native):
diff --git a/paimon-python/pypaimon/tests/native_sorted_index_build_test.py
b/paimon-python/pypaimon/tests/native_sorted_index_build_test.py
index 6f2ef18dee..50e617d27a 100644
--- a/paimon-python/pypaimon/tests/native_sorted_index_build_test.py
+++ b/paimon-python/pypaimon/tests/native_sorted_index_build_test.py
@@ -514,8 +514,10 @@ def
test_append_and_unrelated_column_changes_do_not_invalidate_staged_index(rest
table = _create(catalog, options={'commit.native.enabled':
str(native_commit).lower()})
_append(table, ROWS)
messages = _build(table, kind)
- assert all(struct.unpack('>iiq', file.global_index_meta.source_meta) ==
(0x44454958, 1, 1)
- for file in _message_files(messages))
+ for file in _message_files(messages):
+ source =
DataEvolutionIndexSourceMeta.deserialize(file.global_index_meta.source_meta)
+ assert source.scan_snapshot_id == 1
+ assert source.source_schema_id in (None, table.table_schema.id)
updater = table.new_batch_write_builder().new_update()
_commit(table, updater.update_by_arrow_with_row_id(pa.table({'_ROW_ID':
[0], 'id': pa.array([10], pa.int32())})))
_append(table, [{'id': 6, 'name': 'a', 'pt': 0}])
diff --git a/paimon-python/pypaimon/tests/native_vector_index_layout_test.py
b/paimon-python/pypaimon/tests/native_vector_index_layout_test.py
new file mode 100644
index 0000000000..2c7dfe5e58
--- /dev/null
+++ b/paimon-python/pypaimon/tests/native_vector_index_layout_test.py
@@ -0,0 +1,481 @@
+# 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.
+
+"""Exercise the public PyPaimon APIs with the Rust centroid and MultiVector
implementations."""
+
+import pickle
+import sys
+from collections import Counter
+from dataclasses import replace
+from unittest.mock import patch
+
+import pyarrow as pa
+import pytest
+
+from pypaimon import CatalogFactory
+from pypaimon.globalindex.create_global_index import GlobalIndexBuilder
+from pypaimon.snapshot.snapshot_manager import SnapshotManager
+from pypaimon.table.source.search_types import VectorSearchScanPlan
+from pypaimon.table.source.vector_search_split import RawVectorSearchSplit
+from pypaimon.tests import native_sorted_index_build_test as indexes
+from pypaimon.tests.native_ray_index_build_test import _Ray
+from pypaimon.tests.native_vector_search_test import _rows, _scores, _single
+from pypaimon.write.commit_message import CommitMessage
+
+rest_catalog = indexes.rest_catalog
+pytestmark = pytest.mark.native_plan
+
+SCHEMA = pa.schema([('id', pa.int32()), ('embedding', pa.list_(pa.float32())),
+ ('status', pa.string()), ('tenant', pa.int32()), ('pt',
pa.int32())])
+ROWS = [dict(id=i, embedding=vector, status=status, tenant=tenant, pt=0)
+ for i, (vector, status, tenant) in enumerate([
+ ([0, 0], 'drop', 1), ([1, 0], None, 2), ([20, 0], 'keep', 1),
+ ([21, 0], 'drop', 2), (None, 'keep', 1)])]
+RANGE = {'ivf-flat.dimension': 2, 'ivf-flat.nlist': 1, 'ivf-flat.metric': 'l2'}
+CENTROID = {**RANGE, 'ivf-flat.sharding': 'centroid',
'ivf-flat.centroid.nlist': 2}
+
+
[email protected](autouse=True)
+def vector_layout_runtime():
+ sdk = pytest.importorskip('pypaimon_rust.datafusion')
+ if not (hasattr(sdk.VectorSearchBuilder, 'with_multi_vector')
+ and hasattr(sdk.GlobalIndexBuildPlan, 'replacement_messages')):
+ pytest.skip('Requires centroid and MultiVector APIs in pypaimon-rust')
+
+
[email protected]
+def filesystem_catalog(tmp_path):
+ catalog = CatalogFactory.create({'warehouse': str(tmp_path)})
+ catalog.create_database('default', True)
+ return catalog
+
+
[email protected](params=['filesystem', 'rest'])
+def catalog(request):
+ if request.param == 'rest':
+ return request.getfixturevalue('rest_catalog')[0]
+ return request.getfixturevalue('filesystem_catalog')
+
+
+def _table(catalog, schema=SCHEMA, partitioned=False, **options):
+ return indexes._create(catalog, schema=schema, partitioned=partitioned,
options={
+ 'read.native.enabled': 'true', 'vector-index.search-mode': 'fast',
+ 'scalar-index.prefilter.search-mode': 'full',
'global-index.column-update-action': 'THROW_ERROR',
+ **options,
+ })
+
+
+def _ids(table, result):
+ return sorted(_rows(table, result).column('id').to_pylist())
+
+
+def test_centroid_shards_and_bitmap_filter(catalog):
+ table = _table(catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ assert table.create_global_index('embedding', 'ivf-flat', options=CENTROID,
+ extra_fields={'status': 'bitmap',
'tenant': 'bitmap'}) == 5
+ files = indexes._files(table)
+ roles = Counter(file.global_index_meta.index_meta[:10] for file in files)
+ assert roles == {b'PAIMCENT\x01R': 1, b'PAIMCENT\x01S': 2,
b'PAIMCENT\x01B': 2}
+ fields = {table.field_dict[name].id for name in ('status', 'tenant')}
+ assert all(set(file.global_index_meta.extra_field_ids) == fields for file
in files)
+ assert sum(file.row_count for file in files if
file.global_index_meta.index_meta[9:10] == b'S') == 4
+
+ p = table.new_read_builder().new_predicate_builder()
+ predicate = p.or_predicates([
+ p.and_predicates([p.equal('status', 'keep'), p.equal('tenant', 1)]),
+ p.and_predicates([p.is_null('status'), p.equal('tenant', 2)]),
+ ])
+ options = {'centroid.nprobe': 2, 'global-index.filter.refine-from-data':
False}
+ single = _single(table, [0, 0],
2).with_filter(predicate).with_options(options)
+ assert not hasattr(single.new_vector_search_read(), 'read_batch')
+ assert _ids(table, single.execute_local()) == [1, 2]
+ batch =
(table.new_batch_vector_search_builder().with_vector_column('embedding').with_limit(1)
+ .with_query_vectors([[0, 0], [21,
0]]).with_filter(predicate).with_options(options))
+ plan = pickle.loads(pickle.dumps(batch.new_vector_search_scan().scan()))
+ assert [_ids(table, result) for result in batch.execute_batch_local()] ==
[[1], [2]]
+ reader = batch.new_batch_vector_search_read()
+ assert not hasattr(reader, 'read')
+ assert [_ids(table, result) for result in reader.read_batch_plan(plan)] ==
[[1], [2]]
+ assert [_ids(table, result) for result in
reader.read_batch(iter(plan.splits()))] == [[1], [2]]
+
+ # A predicate with a non-Bitmap branch still uses exact scalar row checks.
+ residual = p.or_predicates([p.equal('status', 'keep'), p.less_than('id',
1)])
+ assert _ids(table, _single(table, [0, 0], 4).with_filter(residual)
+ .with_option('centroid.nprobe', 2).execute_local()) == [0, 2]
+
+
+def
test_bitmap_plan_does_not_raw_score_rows_outside_probed_shards(filesystem_catalog):
+ table = _table(filesystem_catalog, partitioned=True)
+ indexes._append(table, ROWS + [dict(id=10, embedding=[0, 0],
status='other', tenant=1, pt=1)], SCHEMA)
+ table.create_global_index('embedding', 'ivf-flat', partitions={'pt': 0},
+ options={**CENTROID, 'extra_fields':
'{"status":"bitmap"}'})
+ table.create_global_index('embedding', 'ivf-flat', partitions={'pt': 1},
options=RANGE)
+ table.create_global_index('status', 'btree', partitions={'pt': 1})
+
+ predicate =
table.new_read_builder().new_predicate_builder().equal('status', 'keep')
+ builder = (_single(table, [0, 0],
1).with_filter(predicate).with_option('centroid.nprobe', 1))
+ assert builder.execute_local().is_empty()
+ plan = pickle.loads(pickle.dumps(builder.new_vector_search_scan().scan()))
+ reader = pickle.loads(pickle.dumps(builder.new_vector_search_read()))
+ assert reader.read_plan(plan).is_empty()
+ assert reader.read(plan.splits()).is_empty()
+ assert reader.read_plan(VectorSearchScanPlan(plan.splits(),
plan.snapshot())).is_empty()
+ # A caller-created raw split explicitly requests scoring its ranges.
+ splits = [RawVectorSearchSplit(s.row_ranges, s.scalar_index_files,
s.index_type)
+ if isinstance(s, RawVectorSearchSplit) else s for s in
plan.splits()]
+ assert _ids(table, reader.read_plan(VectorSearchScanPlan(splits,
plan.snapshot()))) == [2]
+
+
+def
test_filesystem_range_search_keeps_scalar_filter_semantics(filesystem_catalog):
+ table = _table(filesystem_catalog, partitioned=True)
+ rows = [dict(id=i, embedding=[i / 1000, 0], status=None, tenant=1, pt=0)
for i in range(50)]
+ rows += [dict(id=i, embedding=[i, 0], status=None, tenant=1, pt=0) for i
in range(100, 150)]
+ indexes._append(table, rows + [dict(ROWS[0], pt=1)], SCHEMA)
+ table.create_global_index('embedding', 'ivf-flat', partitions={'pt': 0},
options={**RANGE, 'ivf-flat.nlist': 4})
+ p = table.new_read_builder().new_predicate_builder()
+ builder = (_single(table, [0, 0], 3).with_filter(p.greater_or_equal('id',
100))
+ .with_partition_filter(p.equal('pt',
0)).with_option('ivf.nprobe', 1))
+ reader = builder.new_vector_search_read()
+ plan = builder.new_vector_search_scan().scan()
+ assert _ids(table, builder.execute_local()) == [100, 101, 102]
+ assert _ids(table, reader.read(iter(plan.splits()))) == [100, 101, 102]
+ assert _ids(table,
reader.read_plan(VectorSearchScanPlan(iter(plan.splits()), plan.snapshot())))
== [100, 101, 102]
+
+ # A centroid build in another partition cannot change the selected range's
reader.
+ table.create_global_index('embedding', 'ivf-flat', partitions={'pt': 1},
options=CENTROID)
+ assert _ids(table, reader.read_plan(plan)) == [100, 101, 102]
+ assert _ids(table, builder.execute_local()) == [100, 101, 102]
+
+ # A query over both layouts uses Java's candidate post-filter semantics.
+ mixed = (_single(table, [0, 0], 3).with_filter(p.greater_or_equal('id',
100))
+ .with_option('ivf.nprobe', 1))
+ assert mixed.execute_local().is_empty()
+ mixed_plan = mixed.new_vector_search_scan().scan()
+ assert mixed.new_vector_search_read().read(mixed_plan.splits()).is_empty()
+
+
+def test_filesystem_hybrid_search_after_centroid_rebuild(filesystem_catalog):
+ table = _table(filesystem_catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ table.create_global_index('embedding', 'ivf-flat', options=RANGE)
+ builder =
table.new_hybrid_search_builder().with_limit(1).add_vector_route('embedding',
[0, 0], 1)
+ assert _ids(table, builder.execute_local()) == [0]
+ table.create_global_index('embedding', 'ivf-flat', options=CENTROID,
extra_fields={'status': 'bitmap'})
+ assert _ids(table, builder.execute_local()) == [0]
+ predicate =
table.new_read_builder().new_predicate_builder().is_null('status')
+ builder.with_filter(predicate)
+ assert _ids(table, builder.execute_local()) == [1]
+ route, = builder.route_builders()
+ assert _ids(table, route.execute_local()) == [1]
+
+
+def
test_captured_hybrid_routes_keep_native_range_semantics(filesystem_catalog):
+ schema = SCHEMA.append(pa.field('second_embedding',
SCHEMA.field('embedding').type))
+ table = _table(filesystem_catalog, schema, partitioned=True)
+ rows = [dict(id=i, embedding=[i / 1000, 0], status=None, tenant=1, pt=0)
for i in range(50)]
+ rows += [dict(id=i, embedding=[i, 0], status=None, tenant=1, pt=0) for i
in range(100, 150)]
+ rows += [dict(ROWS[0], pt=1, second_embedding=[0, 0])]
+ indexes._append(table, rows, schema)
+ table.create_global_index('embedding', 'ivf-flat', partitions={'pt': 0},
options={**RANGE, 'ivf-flat.nlist': 4})
+ table.create_global_index('second_embedding', 'ivf-flat',
partitions={'pt': 1}, options=CENTROID)
+ predicate =
table.new_read_builder().new_predicate_builder().greater_or_equal('id', 100)
+ builder =
(table.new_hybrid_search_builder().with_limit(3).with_filter(predicate)
+ .add_vector_route('embedding', [0, 0], 3,
options={'ivf.nprobe': '1'})
+ .add_vector_route('second_embedding', [0, 0], 3))
+ expected = builder.execute_local()
+ assert expected.is_empty()
+ routes = pickle.loads(pickle.dumps(builder.route_builders()))
+ assert builder.rank([builder.to_route_result(route, route.execute_local())
for route in routes]).is_empty()
+ captured = routes[0].search_builder.new_vector_search_scan().scan()
+ standalone = (_single(table, [0, 0],
3).with_filter(predicate).with_option('ivf.nprobe', 1))
+ assert standalone.new_vector_search_read().read_plan(captured).is_empty()
+
+
+def test_captured_hybrid_text_route_uses_native_index(filesystem_catalog):
+ from pypaimon.execution.native.table import _native_table
+ from pypaimon.execution.native.write.native_commit import
from_native_commit_messages
+
+ table = _table(filesystem_catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ table.create_global_index('embedding', 'ivf-flat', options=CENTROID)
+ build = _native_table(table).new_global_index_build_builder()
+ indexes._commit(table, from_native_commit_messages(
+ table,
build.with_index_column('status').with_index_type('full-text').build()))
+ builder =
(table.new_hybrid_search_builder().with_limit(2).add_vector_route('embedding',
[0, 0], 1)
+ .add_full_text_route('status', '{"match":{"query":"keep"}}', 1))
+ with patch.dict(sys.modules, {'paimon_ftindex': None}):
+ expected = builder.execute_local()
+ routes = pickle.loads(pickle.dumps(builder.route_builders()))
+ actual = builder.rank([builder.to_route_result(route,
route.execute_local()) for route in routes])
+ assert len(expected.results().to_list()) == 2
+ assert _scores(actual) == pytest.approx(_scores(expected))
+
+
+def test_centroid_build_resolves_field_json_and_scopes_extra_fields(catalog):
+ table = _table(catalog, **{
+ 'fields.embedding.global-index.vector.index-options':
'{"sharding":"centroid","centroid.nlist":2}',
+ 'extra_fields': '{"status":"bitmap"}',
+ })
+ indexes._append(table, ROWS, SCHEMA)
+ assert table.create_global_index('embedding', 'ivf-flat', options=RANGE)
== 5
+ assert table.create_global_index('embedding', 'ivf-flat', options=RANGE,
extra_fields={'status': 'bitmap'}) == 5
+ assert table.create_global_index('id', 'btree') > 0
+
+
+def test_explicit_sharding_overrides_legacy_field_defaults(catalog):
+ table = _table(catalog, **{'fields.embedding.pk-vector.index.options':
'{"sharding":"range"}'})
+ indexes._append(table, ROWS, SCHEMA)
+ assert table.create_global_index('embedding', 'ivf-flat',
options=CENTROID) == 3
+
+
+def test_only_changed_field_defaults_override_flat_sharding(catalog):
+ table = _table(catalog, **{
+ 'fields.embedding.sharding': 'centroid',
+ 'fields.embedding.index-options':
'{"sharding":"range","fields.embedding.sharding":"centroid"}',
+ 'extra_fields': '{"status":"bitmap"}',
+ })
+ indexes._append(table, ROWS, SCHEMA)
+ assert table.create_global_index('embedding', 'ivf-flat', options=RANGE)
== 1
+ assert not indexes._files(table)[0].global_index_meta.is_centroid_index()
+
+
+def test_echoed_table_options_keep_table_precedence(catalog):
+ table = _table(catalog, **{'fields.embedding.sharding': 'centroid',
'extra_fields': '{"status":"bitmap"}'})
+ indexes._append(table, ROWS, SCHEMA)
+ options = {**table.options.options.to_map(), **RANGE, 'ivf-flat.sharding':
'range'}
+ assert table.create_global_index('embedding', 'ivf-flat', options=options)
== 1
+ assert not indexes._files(table)[0].global_index_meta.is_centroid_index()
+ with pytest.raises(ValueError, match='extra_fields requires a centroid'):
+ table.create_global_index('embedding', 'ivf-flat', options=options,
extra_fields={'status': 'bitmap'})
+
+
[email protected]('execution', ['local', 'ray'])
+def
test_rebuild_replaces_centroid_generation_and_drop_removes_bitmaps(catalog,
monkeypatch, execution):
+ table = _table(catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ assert table.create_global_index('embedding', 'ivf-flat',
options=CENTROID) == 3
+ assert _ids(table, _single(table, [0, 0], 1).execute_local()) == [0]
+ old = {file.file_name for file in indexes._files(table)}
+ if execution == 'ray':
+ monkeypatch.setitem(sys.modules, 'ray', _Ray())
+ assert table.create_global_index('embedding', 'ivf-flat', options=CENTROID,
+ extra_fields='{"status":"bitmap"}',
execution=execution) == 5
+ assert old.isdisjoint(file.file_name for file in indexes._files(table))
+ assert table.drop_global_index('embedding', 'ivf-flat') == 5
+ assert indexes._files(table) == []
+
+
+def test_drop_matches_centroid_bitmap_fields_with_older_runtime(rest_catalog):
+ table = _table(rest_catalog[0])
+ indexes._append(table, ROWS, SCHEMA)
+ assert table.create_global_index('embedding', 'ivf-flat', options=CENTROID,
+ extra_fields={'status': 'bitmap'}) == 5
+ with patch('pypaimon_rust.datafusion.GlobalIndexBuildPlan', object):
+ assert table.drop_global_index('embedding', 'ivf-flat') == 5
+ assert indexes._files(table) == []
+
+
+def test_centroid_bitmap_commit_checks_source_and_retained_index(catalog):
+ table = _table(catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ build = GlobalIndexBuilder(table, 'embedding', 'ivf-flat',
options=CENTROID, extra_fields={'status': 'bitmap'})
+ staged = build.build()
+
+ def update(target, column, value):
+ updater = target.new_batch_write_builder().new_update()
+ indexes._commit(target,
updater.update_by_arrow_with_row_id(pa.table({'_ROW_ID': [0], column: value})))
+
+ update(table, 'status', ['keep'])
+ with pytest.raises(RuntimeError, match='Global index source conflict'):
+ indexes._commit(table, staged)
+ assert indexes._files(table) == []
+ indexes._commit(table, build.build())
+
+ ignore = table.copy({'global-index.column-update-action': 'IGNORE'})
+ update(ignore, 'tenant', [3])
+ with pytest.raises(RuntimeError, match='active centroid index with Bitmap
fields'):
+ update(ignore, 'status', ['drop'])
+ predicate =
table.new_read_builder().new_predicate_builder().equal('status', 'keep')
+ result = _single(table, [0, 0],
1).with_filter(predicate).with_option('centroid.nprobe', 2).execute_local()
+ assert _ids(table, result) == [0]
+
+
+def
test_python_commit_rejects_conflicting_and_incomplete_centroid_groups(catalog):
+ table = _table(catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ build = GlobalIndexBuilder(table, 'embedding', 'ivf-flat',
options=CENTROID, extra_fields={'status': 'bitmap'})
+ first, second = build.build(), build.build()
+ with pytest.raises(RuntimeError, match='centroid|Centroid'):
+ indexes._commit(table, first + second)
+ assert indexes._files(table) == []
+ indexes._commit(table, first)
+
+ entry = first[0].index_adds[0]
+ with pytest.raises(RuntimeError, match='centroid|Centroid'):
+ indexes._commit(table, [CommitMessage((), 0, [],
index_deletes=[replace(entry, kind=1)])])
+ assert _ids(table, _single(table, [0, 0], 1).execute_local()) == [0]
+
+
+def test_centroid_generation_requires_a_source_snapshot(filesystem_catalog):
+ table = _table(filesystem_catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ messages = GlobalIndexBuilder(table, 'embedding', 'ivf-flat',
options=CENTROID).build()
+ for message in messages:
+ for entry in message.index_adds:
+ entry.index_file.global_index_meta.source_meta = None
+ with pytest.raises(RuntimeError, match='centroid generation'):
+ indexes._commit(table, messages)
+ assert indexes._files(table) == []
+
+
+def test_bitmap_column_update_drops_only_its_partition_index(catalog):
+ table = _table(catalog, partitioned=True,
**{'global-index.column-update-action': 'DROP_PARTITION_INDEX'})
+ indexes._append(table, ROWS + [dict(row, id=10 + row['id'], pt=1) for row
in ROWS], SCHEMA)
+ assert table.create_global_index('embedding', 'ivf-flat', options=CENTROID,
+ extra_fields={'status': 'bitmap'}) == 10
+ from pypaimon.index.index_file_handler import IndexFileHandler
+
+ handler = IndexFileHandler(table)
+ retained = {entry.index_file.file_name for entry in handler.scan(None) if
entry.partition.values == [1]}
+ updater = table.new_batch_write_builder().new_update()
+ indexes._commit(table,
updater.update_by_arrow_with_row_id(pa.table({'_ROW_ID': [0], 'status':
['keep']})))
+ assert len(retained) == 5
+ assert {entry.index_file.file_name for entry in handler.scan(None)} ==
retained
+
+
[email protected]('extra_fields', [None, {'status': 'bitmap'}],
ids=['vector', 'bitmap'])
+def test_staged_partition_delete_rechecks_retained_centroid_index(catalog,
extra_fields):
+ table = _table(catalog, partitioned=True, **{'commit.native.enabled':
'true'})
+ indexes._append(table, ROWS + [dict(row, id=10 + row['id'], pt=1) for row
in ROWS], SCHEMA)
+ partition = table.new_read_builder().new_predicate_builder().equal('pt', 0)
+ staged =
table.new_batch_write_builder().new_update().delete_by_predicate(partition)
+ count = 5 if extra_fields else 3
+ assert table.create_global_index('embedding', 'ivf-flat', options=CENTROID,
+ extra_fields=extra_fields) == 2 * count
+ with pytest.raises(RuntimeError, match='Delete affects an active centroid
index'):
+ indexes._commit(table, staged)
+
+ retried =
table.new_batch_write_builder().new_update().delete_by_predicate(partition)
+ indexes._commit(table, retried)
+ assert len(indexes._files(table)) == count
+ assert _ids(table, _single(table, [0, 0], 1).execute_local()) == [10]
+
+
+def
test_python_commit_reads_a_historical_centroid_source_once(filesystem_catalog):
+ table = _table(filesystem_catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ source_id = table.snapshot_manager().get_latest_snapshot().id
+ build = GlobalIndexBuilder(table, 'embedding', 'ivf-flat',
options=CENTROID, extra_fields={'status': 'bitmap'})
+ staged = build.build()
+ indexes._append(table, [dict(ROWS[0], id=20)], SCHEMA)
+
+ get_snapshot = SnapshotManager.get_snapshot_by_id
+ seen = []
+
+ def track(manager, snapshot_id):
+ seen.append(snapshot_id)
+ return get_snapshot(manager, snapshot_id)
+
+ with patch.object(SnapshotManager, 'get_snapshot_by_id', track):
+ indexes._commit(table, staged)
+ assert seen.count(source_id) == 1
+ assert len(indexes._files(table)) == 5
+
+
[email protected]('column, value, conflicts', [('status', ['keep'],
True), ('tenant', [2], False)])
+def test_centroid_build_checks_compacted_source_columns(catalog, column,
value, conflicts):
+ table = _table(catalog, **{'commit.native.enabled': 'true'})
+ indexes._append(table, ROWS, SCHEMA)
+ build = GlobalIndexBuilder(table, 'embedding', 'ivf-flat',
options=CENTROID, extra_fields={'status': 'bitmap'})
+ staged = build.build()
+ updater = table.new_batch_write_builder().new_update()
+ indexes._commit(table,
updater.update_by_arrow_with_row_id(pa.table({'_ROW_ID': [0], column: value})))
+
+ # Observe a COMPACT snapshot with the real replacement data files and row
IDs.
+ latest = SnapshotManager.get_latest_snapshot
+
+ def compacted(manager):
+ return replace(latest(manager), commit_kind='COMPACT')
+
+ with patch.object(SnapshotManager, 'get_latest_snapshot', compacted):
+ if conflicts:
+ with pytest.raises(RuntimeError, match='Global index source
conflict'):
+ indexes._commit(table, staged)
+ else:
+ indexes._commit(table, staged)
+ assert len(indexes._files(table)) == (0 if conflicts else 5)
+
+
+def
test_centroid_build_rejects_deleted_partial_column_source(filesystem_catalog):
+ table = _table(filesystem_catalog)
+ indexes._append(table, ROWS, SCHEMA)
+ updater = table.new_batch_write_builder().new_update()
+ updates = updater.update_by_arrow_with_row_id(pa.table({'_ROW_ID': [0],
'status': ['keep']}))
+ indexes._commit(table, updates)
+ staged = GlobalIndexBuilder(table, 'embedding', 'ivf-flat',
options=CENTROID,
+ extra_fields={'status': 'bitmap'}).build()
+ indexes._commit(table, [CommitMessage(msg.partition, msg.bucket, [],
deleted_files=msg.new_files)
+ for msg in updates])
+ with pytest.raises(RuntimeError, match='Global index source conflict'):
+ indexes._commit(table, staged)
+ assert indexes._files(table) == []
+
+
[email protected]('inner', [pa.list_(pa.float32()),
pa.list_(pa.float32(), 2)], ids=['array', 'vector'])
+def test_multi_vector_maxsim_and_single_vector_results(catalog, inner):
+ schema = pa.schema([('id', pa.int32()), ('embedding', pa.list_(inner))])
+ table = _table(catalog, schema)
+ rows = [[(1, 0), (1, 0)], [(0, 1)], [(1, 1)], [], None]
+ indexes._append(table, [dict(id=i, embedding=value) for i, value in
enumerate(rows)], schema)
+ assert table.create_global_index('embedding', 'ivf-flat',
options={'dimension': 2, 'nlist': 1}) == 1
+
+ vectors = [[1, 0], [0, 1]]
+ builder =
(table.new_vector_search_builder().with_vector_column('embedding')
+ .with_multi_vector(vectors).with_limit(1))
+ vectors[0][0] = -1
+ result = builder.execute_local()
+ assert _ids(table, result) == [2]
+ assert list(_scores(result).values()) == pytest.approx([2 ** 0.5])
+ plan = builder.new_vector_search_scan().scan()
+ reader = pickle.loads(pickle.dumps(builder.new_vector_search_read()))
+ assert _scores(reader.read_plan(pickle.loads(pickle.dumps(plan)))) ==
pytest.approx(_scores(result))
+ assert _ids(table, builder.with_query_vector([1, 0]).execute_local()) ==
[0]
+
+
+def test_invalid_multi_vector_queries_and_index_layout(tmp_path):
+ catalog = CatalogFactory.create({'warehouse': str(tmp_path)})
+ catalog.create_database('default', True)
+ table = _table(catalog, pa.schema([('embedding',
pa.list_(pa.list_(pa.float32(), 2)))]))
+ builder =
table.new_vector_search_builder().with_vector_column('embedding').with_limit(1)
+ for vectors in ([], [[]], [[1, 0], [1]], [[float('nan'), 0]]):
+ with pytest.raises(ValueError, match='query matrix'):
+ builder.with_multi_vector(vectors)
+ with pytest.raises(Exception, match='dimension'):
+ builder.with_multi_vector([[1, 0, 0]]).new_vector_search_read()
+ with pytest.raises(Exception, match='range sharding'):
+ table.create_global_index('embedding', 'ivf-flat', options=CENTROID)
+ with pytest.raises(Exception, match='cosine'):
+ table.create_global_index('embedding', 'ivf-flat', options=RANGE)
+
+
+def test_matrix_search_requires_an_embedding_list_column(filesystem_catalog):
+ table = _table(filesystem_catalog)
+ builder = _single(table).with_multi_vector([[1, 0], [0, 1]])
+ for operation in (builder.new_vector_search_scan,
builder.new_vector_search_read, builder.execute_local):
+ with pytest.raises(ValueError, match='requires a MultiVector column'):
+ operation()
diff --git a/paimon-python/pypaimon/tests/native_vector_search_test.py
b/paimon-python/pypaimon/tests/native_vector_search_test.py
index 9c85c6b5c2..5073bb465a 100644
--- a/paimon-python/pypaimon/tests/native_vector_search_test.py
+++ b/paimon-python/pypaimon/tests/native_vector_search_test.py
@@ -366,14 +366,17 @@ def
test_unused_context_attributes_preserve_native_search(vector_table, option,
@pytest.mark.parametrize('mode', ['fast', 'full', 'detail'])
-def test_unevaluable_scalar_filter_scores_indexed_ranges_raw(vector_table,
mode):
[email protected]('probes', [1, 4])
+def test_range_filter_without_a_scalar_index(vector_table, mode, probes):
+ from pypaimon_rust.datafusion import VectorSearchBuilder
from pypaimon.globalindex.create_global_index import create_global_index
from pypaimon.execution.python.read.search.vector_search_read import (
DataEvolutionVectorRead,
BatchVectorSearchReadImpl,
)
- # The matching vectors live outside the nearest IVF cluster. Sending a
- # data-derived allow-list to ANN with nprobe=1 silently loses all matches.
+ # The matching vectors live outside the nearest IVF cluster. Java and the
+ # layout-capable Rust runtime filter bounded ANN candidates. The Python
+ # reader and Rust 0.5 score the matching range directly.
_write(vector_table, [
{'id': i, 'embedding': [i / 1000, 0], 'pt': 2} for i in range(50)
] + [
@@ -390,13 +393,16 @@ def
test_unevaluable_scalar_filter_scores_indexed_ranges_raw(vector_table, mode)
partition = predicates.equal('pt', 2)
def configure(builder, direct=False):
- return (builder.with_option('ivf.nprobe', '1')
+ return (builder.with_option('ivf.nprobe', str(probes))
+ .with_option('vector-index.post-filter.candidates-factor',
'40')
.with_filter(_predicate_to_native(predicate) if direct else
predicate)
.with_partition_filter(_predicate_to_native(partition) if
direct else partition))
queries = [[0, 0], [1, 0]]
expected = [_scores(configure(_single(classic, query)).execute_local())
for query in queries]
assert all(len(scores) == 3 for scores in expected)
+ if probes == 1 and hasattr(VectorSearchBuilder, 'with_multi_vector'):
+ expected = [{}, {}]
direct_table = _native_table(native)
direct =
configure(direct_table.new_batch_vector_search_builder().with_vector_column('embedding')
.with_query_vectors(queries).with_limit(3),
direct=True).execute()
@@ -410,7 +416,7 @@ def
test_unevaluable_scalar_filter_scores_indexed_ranges_raw(vector_table, mode)
for single, batched, scores in zip(singles, batch, expected):
_assert_scores(_scores(single), scores)
_assert_scores(_scores(batched), scores)
- assert sorted(_rows(native, singles[0]).column('id').to_pylist()) == [100,
101, 102]
+ assert sorted(_rows(native, singles[0]).column('id').to_pylist()) ==
([100, 101, 102] if expected[0] else [])
@pytest.mark.parametrize('mode', ['fast', 'full', 'detail'])
diff --git
a/paimon-python/pypaimon/tests/public_execution_factory_boundary_test.py
b/paimon-python/pypaimon/tests/public_execution_factory_boundary_test.py
index 6f4b928dbb..61d5ecca25 100644
--- a/paimon-python/pypaimon/tests/public_execution_factory_boundary_test.py
+++ b/paimon-python/pypaimon/tests/public_execution_factory_boundary_test.py
@@ -64,7 +64,9 @@ def
test_search_factories_keep_captured_configuration(tmp_path, kind, phase, nat
with patch('pypaimon.execution.python.read.search.factories.' +
python_name,
return_value=python_execution) as python_factory, \
patch('pypaimon.execution.native.read.native_search_plan.' +
native_name,
- return_value=native_execution) as native_factory:
+ return_value=native_execution) as native_factory, \
+
patch('pypaimon.execution.native.read.native_vector_search._filesystem_vector_search_supported',
+ return_value=False):
if phase == 'scan':
selected = (builder.new_full_text_scan() if kind == 'full-text'
else builder.new_vector_search_scan())
@@ -137,7 +139,9 @@ for name in ['scan', 'read_plan', 'read_batch_plan']:
getattr(native, name).return_value = expected
constructors = {name: Mock(return_value=native) for name in [
'native_vector_scan', 'native_vector_read', 'native_full_text_scan',
'native_full_text_read']}
-with patch.multiple(native_search_plan, **constructors):
+with patch.multiple(native_search_plan, **constructors), \
+
patch('pypaimon.execution.native.read.native_vector_search._filesystem_vector_search_supported',
+ return_value=False):
operations = [
lambda: vector.new_vector_search_scan().scan(),
lambda: vector.new_vector_search_read().read_plan(object()),
diff --git a/paimon-python/pypaimon/tests/vindex_execution_boundary_test.py
b/paimon-python/pypaimon/tests/vindex_execution_boundary_test.py
index 4a5ec35a68..191e3cc390 100644
--- a/paimon-python/pypaimon/tests/vindex_execution_boundary_test.py
+++ b/paimon-python/pypaimon/tests/vindex_execution_boundary_test.py
@@ -42,9 +42,9 @@ def _reader(reader_type=VindexVectorGlobalIndexReader):
return reader_type(SimpleNamespace(), '/indexes',
[GlobalIndexIOMeta('index', 1)], {'option': 'value'})
-def test_centroid_files_require_the_java_reader():
+def test_centroid_files_require_table_level_search():
files = [GlobalIndexIOMeta("router", 100, b"PAIMCENT" + bytes(20))]
- with pytest.raises(NotImplementedError, match="Java reader"):
+ with pytest.raises(NotImplementedError, match="table-level search with
pypaimon-rust"):
VindexVectorGlobalIndexReader(SimpleNamespace(), '/indexes', files)