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 0fd7e89958 [core][spark] Store centroid Bitmaps by field (#11402)
0fd7e89958 is described below
commit 0fd7e89958cf1121bac3524aa2980cf54ed68d63
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 24 19:16:53 2026 +0800
[core][spark] Store centroid Bitmaps by field (#11402)
---
.../global-index/centroid-vector.mdx | 37 +--
docs/docs/multimodal-table/global-index/vector.mdx | 2 +-
docs/docs/pypaimon/multimodal-search.md | 8 +-
.../paimon/globalindex/CentroidIndexFile.java | 10 +-
.../bitmap/BitmapGlobalIndexWriter.java | 23 +-
.../globalindex/bitmap/CentroidBitmapIndex.java | 258 +++++++--------------
.../apache/paimon/utils/RoaringNavigableMap64.java | 51 ++++
.../bitmap/LazyFilteredBitmapIndexReaderTest.java | 139 +++++------
.../paimon/utils/RoaringNavigableMap64Test.java | 27 +++
.../paimon/globalindex/CentroidIndexMeta.java | 16 +-
.../paimon/manifest/IndexManifestFileHandler.java | 26 +++
.../paimon/table/source/CentroidBitmapFilter.java | 53 +++--
.../table/source/DataEvolutionVectorScan.java | 3 +-
.../paimon/globalindex/CentroidIndexMetaTest.java | 3 +-
.../pypaimon/manifest/centroid_index_groups.py | 39 +++-
.../pypaimon/manifest/index_manifest_file.py | 5 +-
.../pypaimon/tests/global_index_build_test.py | 14 +-
.../tests/native_vector_index_layout_test.py | 50 ++--
.../CentroidGlobalIndexTopoBuilder.java | 243 ++++++++-----------
.../paimon/spark/sql/CentroidVectorIndexTest.scala | 48 ++--
.../index/NativeCentroidRoutedIndexReader.java | 25 +-
.../index/NativeVectorGlobalIndexWriter.java | 9 +-
.../vector/index/CentroidTableInteropTest.java | 66 ++++--
.../index/CentroidVectorGlobalIndexTest.java | 93 +++++---
.../src/test/resources/centroid-rust-warehouse.zip | Bin 35668 -> 35332 bytes
paimon-vector/src/test/resources/centroid-rust.zip | Bin 1884 -> 1765 bytes
26 files changed, 658 insertions(+), 590 deletions(-)
diff --git a/docs/docs/multimodal-table/global-index/centroid-vector.mdx
b/docs/docs/multimodal-table/global-index/centroid-vector.mdx
index c13e79675f..56c256fb04 100644
--- a/docs/docs/multimodal-table/global-index/centroid-vector.mdx
+++ b/docs/docs/multimodal-table/global-index/centroid-vector.mdx
@@ -31,7 +31,7 @@ row-ID range. Spark and PyPaimon support this layout for
`ivf-flat`, `ivf-pq`,
Use Spark to build centroid indexes on [Data Evolution append
tables](../data-evolution)
without a primary key. Enable row tracking and Data Evolution and set
`bucket=-1`.
-Each source row-ID range in a partition gets a router and one shard per
centroid.
+Each source row-ID range in a partition gets a router and one shard per
populated centroid.
The examples use a 768-dimensional `embedding` column and two optional scalar
filter columns.
@@ -139,7 +139,7 @@ of quantization. For IVF-RQ, calibrate `rq.bits`. For
DiskANN, calibrate both ou
probes and local graph search width.
Calibrate `ivf-pq.centroid.nlist` and `ivf-pq.pq.m` together with the query
probe width.
-Increasing `centroid.nlist` creates more centroid files, each populated file
carrying its own
+Increasing `centroid.nlist` can create more populated shard files, each
carrying its own
local model. With 8-bit PQ codes, `pq.m=64` uses twice the code bytes per
vector
of `pq.m=32`. Record the resolved build options, total index size, query file
reads, and achieved recall when comparing configurations.
@@ -156,7 +156,7 @@ index manifest). The descriptor starts with a 14-byte
header.
| 0 | 8 | ASCII marker `PAIMCENT` |
| 8 | 1 | Numeric format version `1` |
| 9 | 1 | ASCII role `R`, `S`, or `B` |
-| 10 | 4 | Outer `nlist` for `R`, or zero-based centroid ID for `S` and `B`,
stored as a big-endian `int32` |
+| 10 | 4 | Outer `nlist` for `R`, zero-based centroid ID for `S`, or scalar
field ID for `B`, stored as a big-endian `int32` |
The value ranges from `0` to `2,147,483,647`. The role also determines the
payload starting at byte 14.
@@ -164,7 +164,7 @@ The value ranges from `0` to `2,147,483,647`. The role also
determines the paylo
| --- | --- |
| `R` (router) | Build-time distance metric in UTF-8 |
| `S` (vector shard) | The actual local IVF list count as a 32-bit big-endian
integer for populated L2 IVF-FLAT and IVF-PQ shards. Other shards end at the
header. |
-| `B` (Bitmap) | Big-endian 64-bit start offsets of the second and subsequent
Bitmap sections, measured from the start of the Bitmap file. |
+| `B` (Bitmap) | Standard Bitmap key-bound and null metadata. |
The router and its shards share the manifest row-ID range `[_ROW_RANGE_START,
_ROW_RANGE_END]`.
Each shard stores row IDs relative to `_ROW_RANGE_START`. During a query,
Paimon translates
@@ -173,9 +173,10 @@ row-ID filters to this local range and adds the range
start back to matching IDs
### Router and Vector Shard Files
An all-null vector range has one router entry with outer `nlist=0` and a
zero-byte
-router file. Other ranges have one vector shard entry for every centroid ID
from
-`0` through `nlist - 1`. An empty shard file contains the eight ASCII bytes
-`PCEMPTY1` and has manifest row count zero. Queries skip empty files.
+router file. In other ranges, the router defines centroid IDs from `0` through
+`nlist - 1`. Each populated centroid has one vector shard file and a manifest
+entry with a positive row count. A centroid ID absent from the manifest
represents
+an empty shard. Empty centroids still count toward the requested probe width.
A populated router file contains the native `PVROUT01` model bytes.
@@ -193,13 +194,16 @@ loaded model's centroid count matches the manifest.
### Bitmap Files
-When `extra_fields` is configured, each populated centroid gets one Bitmap file
-with one consecutive section per `_EXTRA_FIELD_IDS` entry, in that order. Each
-section uses the standalone [Bitmap file format](./bitmap#file-format), with
block
-offsets relative to the start of the section. The first section starts at byte
zero
-and the last ends at the manifest's `_FILE_SIZE`. For `N` fields, the `B`
descriptor
-stores `N - 1` increasing offsets.
-The build schema ID in `_SOURCE_META` identifies the types of the Bitmap keys.
+Each row-ID range with indexed vectors has one standalone [Bitmap
file](./bitmap#file-format)
+per field in `_EXTRA_FIELD_IDS`. Each Bitmap covers all indexed rows in the
range.
+Its field ID is in the `B` descriptor, and the build schema ID in
`_SOURCE_META`
+identifies the key type. A range with no vectors has no Bitmap files.
+
+For a vector assigned to centroid `c`, a Bitmap stores the position
+`c * range_size + (row_id - row_range_start)`, where `range_size` is
+`row_range_end - row_range_start + 1`. After evaluating a scalar predicate once
+for the range, Paimon uses the quotient to select the shard and the remainder
as
+the row ID relative to the start of the range.
## Scalar Bitmap Filters in Centroid Shards
@@ -220,13 +224,12 @@ CALL sys.create_global_index(
A vector search can use these Bitmaps for equality, `IN`, `IS NULL`, `IS NOT
NULL`, and
combinations of these predicates with `AND` or `OR`, including across columns.
It applies the
exact matches before ranking and skips opening the ANN file when no visible
vector matches.
-If any branch cannot be evaluated exactly by the shard Bitmaps, the filter
uses the existing
+If any branch cannot be evaluated exactly by the field Bitmaps, the filter
uses the existing
scalar-filter path.
To change the scalar columns, run the centroid build again with the new
`extra_fields`. For the selected
partitions, the build replaces the indexes of the same type on the vector
column. Pass just the
-vector column as `index_column` to `sys.drop_global_index` to remove the
group. Drop the group
-before using an older Java reader that lacks support for centroid Bitmap files.
+vector column as `index_column` to `sys.drop_global_index` to remove the group.
## Rebuild and Compatibility
diff --git a/docs/docs/multimodal-table/global-index/vector.mdx
b/docs/docs/multimodal-table/global-index/vector.mdx
index 9ec36b7252..30ef37a9b2 100644
--- a/docs/docs/multimodal-table/global-index/vector.mdx
+++ b/docs/docs/multimodal-table/global-index/vector.mdx
@@ -503,7 +503,7 @@ Use full 768-dimensional query vectors when searching
either of these indexes.
### Centroid-Based Sharding
[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.
+index manifest and router file formats, and the per-field Bitmap files shared
by shards in a row-ID range.
### Per-Field Options
diff --git a/docs/docs/pypaimon/multimodal-search.md
b/docs/docs/pypaimon/multimodal-search.md
index 62ed32e199..788d034223 100644
--- a/docs/docs/pypaimon/multimodal-search.md
+++ b/docs/docs/pypaimon/multimodal-search.md
@@ -53,9 +53,11 @@ 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.
+to train a router and build a vector shard for each populated centroid.
+Use `extra_fields` to map scalar column names to `bitmap`. For each row-ID
range
+with indexed vectors, Paimon writes one Bitmap per configured scalar column.
+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`.
diff --git
a/paimon-common/src/main/java/org/apache/paimon/globalindex/CentroidIndexFile.java
b/paimon-common/src/main/java/org/apache/paimon/globalindex/CentroidIndexFile.java
index e1150ef3bc..9e9f8a3e3e 100644
---
a/paimon-common/src/main/java/org/apache/paimon/globalindex/CentroidIndexFile.java
+++
b/paimon-common/src/main/java/org/apache/paimon/globalindex/CentroidIndexFile.java
@@ -63,12 +63,20 @@ public final class CentroidIndexFile extends
GlobalIndexIOMeta {
/** Centroid to which this shard belongs. */
public int centroid() {
- if (routingModel) {
+ if (routingModel || scalarIndex) {
throw new IllegalStateException("Expected a centroid shard.");
}
return countOrId;
}
+ /** Table field indexed by this Bitmap. */
+ public int fieldId() {
+ if (!scalarIndex) {
+ throw new IllegalStateException("Expected a centroid bitmap.");
+ }
+ return countOrId;
+ }
+
@Override
public boolean equals(Object other) {
if (!super.equals(other)) {
diff --git
a/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/BitmapGlobalIndexWriter.java
b/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/BitmapGlobalIndexWriter.java
index 1b072ac575..85f7a8ded9 100644
---
a/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/BitmapGlobalIndexWriter.java
+++
b/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/BitmapGlobalIndexWriter.java
@@ -105,21 +105,6 @@ public class BitmapGlobalIndexWriter implements
GlobalIndexSingleColumnWriter, C
return Collections.emptyList();
}
- finishSection();
- byte[] meta =
- new SortedIndexFileMeta(
- firstKey == null ? null :
keySerializer.serialize(firstKey),
- lastKey == null ? null :
keySerializer.serialize(lastKey),
- !nullRows.isEmpty())
- .serialize();
- return Collections.singletonList(new ResultEntry(filePath, rowCount,
meta));
- }
-
- /** Finalizes a bitmap section for a reader that loads its directory from
the footer. */
- long finishSection() {
- if (rowCount == 0) {
- return 0;
- }
try {
flushCurrentBitmap();
streamingWriter().finish(nullRows, nonNullRows);
@@ -128,7 +113,13 @@ public class BitmapGlobalIndexWriter implements
GlobalIndexSingleColumnWriter, C
throw new RuntimeException("Error in closing bitmap index
writer.", e);
}
- return rowCount;
+ byte[] meta =
+ new SortedIndexFileMeta(
+ firstKey == null ? null :
keySerializer.serialize(firstKey),
+ lastKey == null ? null :
keySerializer.serialize(lastKey),
+ !nullRows.isEmpty())
+ .serialize();
+ return Collections.singletonList(new ResultEntry(filePath, rowCount,
meta));
}
@Override
diff --git
a/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java
b/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java
index b51994f354..d5bae31c48 100644
---
a/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java
+++
b/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java
@@ -18,16 +18,9 @@
package org.apache.paimon.globalindex.bitmap;
-import org.apache.paimon.fs.CloseShieldOutputStream;
-import org.apache.paimon.fs.OffsetSeekableInputStream;
-import org.apache.paimon.fs.PositionOutputStream;
-import org.apache.paimon.fs.SeekableInputStream;
import org.apache.paimon.globalindex.GlobalIndexIOMeta;
import org.apache.paimon.globalindex.KeySerializer;
-import org.apache.paimon.globalindex.ResultEntry;
import org.apache.paimon.globalindex.io.GlobalIndexFileReader;
-import org.apache.paimon.globalindex.io.GlobalIndexFileWriter;
-import org.apache.paimon.options.Options;
import org.apache.paimon.predicate.And;
import org.apache.paimon.predicate.CompoundPredicate;
import org.apache.paimon.predicate.Equal;
@@ -37,15 +30,13 @@ import org.apache.paimon.predicate.IsNull;
import org.apache.paimon.predicate.LeafPredicate;
import org.apache.paimon.predicate.Or;
import org.apache.paimon.predicate.Predicate;
-import org.apache.paimon.types.DataField;
import org.apache.paimon.types.RowType;
import org.apache.paimon.utils.IOFunction;
+import org.apache.paimon.utils.IOUtils;
+import org.apache.paimon.utils.Range;
import org.apache.paimon.utils.RoaringNavigableMap64;
-import javax.annotation.Nullable;
-
import java.io.IOException;
-import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@@ -53,42 +44,86 @@ import java.util.Map;
import static org.apache.paimon.utils.Preconditions.checkArgument;
import static org.apache.paimon.utils.Preconditions.checkState;
-/**
- * Bitmap sections ordered by the manifest's extra field IDs, with offsets for
sections 2 onward.
- */
+/** Evaluates a scalar predicate across the Bitmap files of a centroid row-ID
range. */
public final class CentroidBitmapIndex {
private CentroidBitmapIndex() {}
- public static RoaringNavigableMap64 match(
+ /** Positions for each centroid occupy a separate copy of the source
row-ID range. */
+ public static long encodeRowId(int centroid, long rowRangeSize, long
relativeRowId) {
+ return Math.addExact(Math.multiplyExact(centroid, rowRangeSize),
relativeRowId);
+ }
+
+ public static IOFunction<Integer, RoaringNavigableMap64> filter(
+ GlobalIndexFileReader files,
+ Map<Integer, ? extends GlobalIndexIOMeta> bitmaps,
+ RowType rowType,
+ RowType buildType,
+ Predicate predicate,
+ long rowRangeSize,
+ int nlist) {
+ checkArgument(rowRangeSize > 0 && nlist > 0, "Invalid centroid bitmap
range.");
+ return new IOFunction<Integer, RoaringNavigableMap64>() {
+ private RoaringNavigableMap64 matches;
+
+ @Override
+ public RoaringNavigableMap64 apply(Integer centroid) throws
IOException {
+ if (centroid < 0 || centroid >= nlist || centroid >
Long.MAX_VALUE / rowRangeSize) {
+ return new RoaringNavigableMap64();
+ }
+ long start = encodeRowId(centroid, rowRangeSize, 0);
+ long end = start + Math.min(rowRangeSize - 1, Long.MAX_VALUE -
start);
+ return matches().relativeRange(new Range(start, end));
+ }
+
+ private synchronized RoaringNavigableMap64 matches() throws
IOException {
+ if (matches == null) {
+ RoaringNavigableMap64 rows =
+ match(files, bitmaps, rowType, buildType,
predicate);
+ // Populate the rank cache before probe tasks share the
encoded matches.
+ if (rows.getLongCardinality() > 0) {
+ long last = rows.last();
+ checkState(
+ last >= 0 && last / rowRangeSize < nlist,
+ "Invalid centroid bitmap position: %s.",
+ last);
+ }
+ matches = rows;
+ }
+ return matches;
+ }
+ };
+ }
+
+ private static RoaringNavigableMap64 match(
GlobalIndexFileReader files,
- GlobalIndexIOMeta bitmap,
- int[] extraFieldIds,
+ Map<Integer, ? extends GlobalIndexIOMeta> bitmaps,
RowType rowType,
RowType buildType,
Predicate predicate)
throws IOException {
- Map<Integer, Section> sections =
- readDirectory(bitmap.metadata(), extraFieldIds,
bitmap.fileSize());
- try (SeekableInputStream input = files.getInputStream(bitmap)) {
+ Map<Integer, BitmapIndexReader> readers = new HashMap<>();
+ try {
return evaluate(
predicate,
fieldName -> {
int fieldId = rowType.getField(fieldName).id();
- Section section = sections.get(fieldId);
- checkState(
- section != null,
- "Missing field %s in %s.",
- fieldId,
- bitmap.filePath());
- KeySerializer serializer =
-
KeySerializer.create(buildType.getField(fieldId).type());
- GlobalIndexIOMeta sectionMeta =
- new GlobalIndexIOMeta(
- bitmap.filePath(), section.length,
bitmap.rowCount(), null);
- return new BitmapIndexReader(
- serializer, ignored -> section.open(input),
sectionMeta);
+ BitmapIndexReader reader = readers.get(fieldId);
+ if (reader == null) {
+ GlobalIndexIOMeta bitmap = bitmaps.get(fieldId);
+ checkState(
+ bitmap != null,
+ "Missing centroid bitmap for field %s.",
+ fieldId);
+ KeySerializer serializer =
+
KeySerializer.create(buildType.getField(fieldId).type());
+ reader = new BitmapIndexReader(serializer, files,
bitmap);
+ readers.put(fieldId, reader);
+ }
+ return reader;
});
+ } finally {
+ IOUtils.closeAllQuietly(readers.values());
}
}
@@ -97,23 +132,21 @@ public final class CentroidBitmapIndex {
throws IOException {
if (predicate instanceof LeafPredicate) {
LeafPredicate leaf = (LeafPredicate) predicate;
- try (BitmapIndexReader reader =
- openReader.apply(leaf.fieldRefOptional().get().name())) {
- if (Equal.INSTANCE.equals(leaf.function())) {
- return
reader.visitEqual(leaf.literals().get(0)).get().results();
- }
- if (IsNull.INSTANCE.equals(leaf.function())) {
- return reader.visitIsNull().get().results();
- }
- if (IsNotNull.INSTANCE.equals(leaf.function())) {
- return reader.visitIsNotNull().get().results();
- }
- checkArgument(
- In.INSTANCE.equals(leaf.function()),
- "Unsupported centroid bitmap predicate %s.",
- leaf.function());
- return reader.visitIn(leaf.literals()).get().results();
+ BitmapIndexReader reader =
openReader.apply(leaf.fieldRefOptional().get().name());
+ if (Equal.INSTANCE.equals(leaf.function())) {
+ return
reader.visitEqual(leaf.literals().get(0)).get().results();
+ }
+ if (IsNull.INSTANCE.equals(leaf.function())) {
+ return reader.visitIsNull().get().results();
+ }
+ if (IsNotNull.INSTANCE.equals(leaf.function())) {
+ return reader.visitIsNotNull().get().results();
}
+ checkArgument(
+ In.INSTANCE.equals(leaf.function()),
+ "Unsupported centroid bitmap predicate %s.",
+ leaf.function());
+ return reader.visitIn(leaf.literals()).get().results();
}
checkArgument(
@@ -137,131 +170,4 @@ public final class CentroidBitmapIndex {
}
return rows;
}
-
- private static Map<Integer, Section> readDirectory(
- @Nullable byte[] metadata, int[] extraFieldIds, long fileSize) {
- ByteBuffer directory =
- metadata == null ? ByteBuffer.allocate(0) :
ByteBuffer.wrap(metadata);
- int fieldCount = extraFieldIds.length;
- checkArgument(
- fieldCount > 0 && directory.remaining() == (fieldCount - 1L) *
Long.BYTES,
- "Invalid centroid bitmap directory length.");
- Map<Integer, Section> sections = new HashMap<>();
- long offset = 0;
- for (int i = 0; i < fieldCount; i++) {
- int fieldId = extraFieldIds[i];
- long end = i == fieldCount - 1 ? fileSize : directory.getLong();
- checkArgument(
- end > offset && end <= fileSize,
- "Invalid centroid bitmap section for field %s.",
- fieldId);
- checkArgument(
- sections.put(fieldId, new Section(offset, end - offset))
== null,
- "Duplicate centroid bitmap field %s.",
- fieldId);
- offset = end;
- }
- return sections;
- }
-
- /** Writes one complete Bitmap per column to the same output stream. */
- public static final class Writer implements AutoCloseable {
-
- private final String filePath;
- private final int fieldCount;
- private final long rowCount;
- private final PositionOutputStream output;
- private final ByteBuffer directory;
- private int written;
-
- public Writer(GlobalIndexFileWriter files, int fieldCount, long
rowCount)
- throws IOException {
- checkArgument(fieldCount > 0 && rowCount > 0, "Empty centroid
bitmap file.");
- this.filePath = files.newFilePath("centroid-bitmap");
- this.fieldCount = fieldCount;
- this.rowCount = rowCount;
- this.directory = ByteBuffer.allocate(Math.multiplyExact(fieldCount
- 1, Long.BYTES));
- this.output = files.newOutputStream(filePath);
- }
-
- public void writeColumn(DataField field, Options options, ColumnRows
rows)
- throws IOException {
- checkState(written < fieldCount, "Too many centroid bitmap
sections.");
- long offset = output.getPos();
- GlobalIndexFileWriter sectionWriter =
- new GlobalIndexFileWriter() {
- @Override
- public String newFilePath(String prefix) {
- return filePath;
- }
-
- @Override
- public PositionOutputStream newOutputStream(String
filePath) {
- return new CloseShieldOutputStream(output) {
- @Override
- public long getPos() throws IOException {
- return super.getPos() - offset;
- }
- };
- }
- };
- long sectionRows;
- try (BitmapGlobalIndexWriter writer =
- new BitmapGlobalIndexer(field,
options).createWriter(sectionWriter)) {
- rows.writeTo(writer);
- sectionRows = writer.finishSection();
- }
- checkState(sectionRows == rowCount, "Centroid bitmap and vector
row counts differ.");
- if (written > 0) {
- directory.putLong(offset);
- }
- written++;
- }
-
- public ResultEntry finish() {
- checkState(written == fieldCount, "Incomplete centroid bitmap
file.");
- return new ResultEntry(filePath, rowCount, fieldCount == 1 ? null
: directory.array());
- }
-
- @Override
- public void close() throws IOException {
- output.close();
- }
- }
-
- /** Sorted rows of one extra field. */
- @FunctionalInterface
- public interface ColumnRows {
- void writeTo(BitmapGlobalIndexWriter writer) throws IOException;
- }
-
- private static final class Section {
- private final long offset;
- private final long length;
-
- private Section(long offset, long length) {
- this.offset = offset;
- this.length = length;
- }
-
- private SeekableInputStream open(SeekableInputStream input) throws
IOException {
- if (offset == 0) {
- input.seek(0);
- }
- return new OffsetSeekableInputStream(input, offset, length) {
- @Override
- public void seek(long desired) throws IOException {
- if (desired < 0 || desired > length) {
- throw new IOException("Seek outside centroid bitmap
section.");
- }
- super.seek(desired);
- }
-
- @Override
- public void close() {
- // The caller owns the shared input stream.
- }
- };
- }
- }
}
diff --git
a/paimon-common/src/main/java/org/apache/paimon/utils/RoaringNavigableMap64.java
b/paimon-common/src/main/java/org/apache/paimon/utils/RoaringNavigableMap64.java
index 418788d9f2..d0439c8a52 100644
---
a/paimon-common/src/main/java/org/apache/paimon/utils/RoaringNavigableMap64.java
+++
b/paimon-common/src/main/java/org/apache/paimon/utils/RoaringNavigableMap64.java
@@ -41,6 +41,8 @@ public class RoaringNavigableMap64 implements Iterable<Long>,
Serializable {
private static final int RANGE_LIST_SELECT_SAMPLE_SIZE = 64;
+ private static final long ROARING_CONTAINER_SPAN = 1L << 16;
+
private final Roaring64NavigableMap roaring64NavigableMap;
public RoaringNavigableMap64() {
@@ -73,6 +75,55 @@ public class RoaringNavigableMap64 implements
Iterable<Long>, Serializable {
return roaring64NavigableMap.rankLong(toExclusive - 1) > before;
}
+ /** Copies the values within {@code range}, subtracting the range start
from each value. */
+ public RoaringNavigableMap64 relativeRange(Range range) {
+ Preconditions.checkArgument(range.from >= 0, "Expected a non-negative
range.");
+ RoaringNavigableMap64 result = new RoaringNavigableMap64();
+ if (isEmpty()) {
+ return result;
+ }
+ long firstIndex = range.from == 0 ? 0 :
roaring64NavigableMap.rankLong(range.from - 1);
+ long endIndex = roaring64NavigableMap.rankLong(range.to);
+ if (firstIndex == endIndex) {
+ return result;
+ }
+
+ long first = roaring64NavigableMap.select(firstIndex);
+ long last = roaring64NavigableMap.select(endIndex - 1);
+ long count = endIndex - firstIndex;
+ if (last - first == count - 1) {
+ result.addRange(new Range(first - range.from, last - range.from));
+ return result;
+ }
+ if ((last - first) / ROARING_CONTAINER_SPAN >= count) {
+ // Selecting sparse values avoids allocating containers across a
wide gap.
+ for (long index = firstIndex; index < endIndex; index++) {
+ result.add(roaring64NavigableMap.select(index) - range.from);
+ }
+ return result;
+ }
+
+ RoaringNavigableMap64 selected = range.from == 0 ? result : new
RoaringNavigableMap64();
+ selected.addRange(new Range(first, last));
+ selected.and(this);
+ if (range.from == 0) {
+ return selected;
+ }
+ if (selected.shouldUseSelectRanges(count)) {
+ for (Range run : selected.toRangeListBySelect(count)) {
+ result.addRange(run.addOffset(-range.from));
+ }
+ } else {
+ selected.roaring64NavigableMap.forEach(row -> result.add(row -
range.from));
+ }
+ return result;
+ }
+
+ /** Last value in bitmap order, which is unsigned. The bitmap must be
nonempty. */
+ public long last() {
+ return roaring64NavigableMap.last();
+ }
+
public void add(long x) {
roaring64NavigableMap.add(x);
}
diff --git
a/paimon-common/src/test/java/org/apache/paimon/globalindex/bitmap/LazyFilteredBitmapIndexReaderTest.java
b/paimon-common/src/test/java/org/apache/paimon/globalindex/bitmap/LazyFilteredBitmapIndexReaderTest.java
index 0f83736f6e..88a60885d3 100644
---
a/paimon-common/src/test/java/org/apache/paimon/globalindex/bitmap/LazyFilteredBitmapIndexReaderTest.java
+++
b/paimon-common/src/test/java/org/apache/paimon/globalindex/bitmap/LazyFilteredBitmapIndexReaderTest.java
@@ -40,7 +40,9 @@ import org.apache.paimon.types.DataField;
import org.apache.paimon.types.DataTypes;
import org.apache.paimon.types.RowType;
import org.apache.paimon.types.VarCharType;
+import org.apache.paimon.utils.IOFunction;
import org.apache.paimon.utils.Pair;
+import org.apache.paimon.utils.RoaringNavigableMap64;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -50,12 +52,13 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
@@ -81,90 +84,62 @@ public class LazyFilteredBitmapIndexReaderTest {
@TempDir java.nio.file.Path tempPath;
@Test
- void centroidBitmapSectionsPreserveSparseRowIdsAndNulls() throws
IOException {
+ void centroidBitmapFilesShareALookupAndPreserveSparseRowIds() throws
IOException {
DataField state = new DataField(5, "state", DataTypes.INT());
RowType fields = RowType.of(dataField, state);
- CentroidBitmapIndex.ColumnRows tags =
- column -> {
- column.write(BinaryString.fromString("blue"), 90);
- column.write(BinaryString.fromString("red"), 90_000);
- };
- ResultEntry result;
- try (CentroidBitmapIndex.Writer writer = new
CentroidBitmapIndex.Writer(fileWriter, 2, 2)) {
- writer.writeColumn(
- state,
- new Options(),
- column -> {
- column.write(1, 90);
- column.write(null, 90_000);
- });
- writer.writeColumn(dataField, new Options(), tags);
- result = writer.finish();
- }
- Path path = new Path(result.filePath());
- GlobalIndexIOMeta meta =
- new GlobalIndexIOMeta(path, fileIO.getFileSize(path), 2,
result.meta());
- assertThat(result.meta()).hasSize(Long.BYTES);
- long secondSectionOffset = ByteBuffer.wrap(result.meta()).getLong();
-
assertThat(secondSectionOffset).isPositive().isLessThan(meta.fileSize());
-
- int[] extraFieldIds = {state.id(), dataField.id()};
+ long rangeSize = 1L << 32;
+ long first = CentroidBitmapIndex.encodeRowId(0, rangeSize, 90);
+ long firstEnd = CentroidBitmapIndex.encodeRowId(0, rangeSize,
rangeSize - 1);
+ long lastStart = CentroidBitmapIndex.encodeRowId(2, rangeSize, 0);
+ long last = CentroidBitmapIndex.encodeRowId(2, rangeSize, 90_000);
+ Map<Integer, GlobalIndexIOMeta> bitmaps = new HashMap<>();
+ bitmaps.put(
+ dataField.id(),
+ writeData(
+ Arrays.asList(
+ Pair.of(str("red"), first),
+ Pair.of(str("red"), firstEnd),
+ Pair.of(str("red"), lastStart),
+ Pair.of(str("red"), last))));
+ try (BitmapGlobalIndexWriter writer =
+ new BitmapGlobalIndexer(state, new
Options()).createWriter(fileWriter)) {
+ writer.write(1, first);
+ writer.write(1, firstEnd);
+ writer.write(null, lastStart);
+ writer.write(null, last);
+ ResultEntry result = writer.finish().get(0);
+ Path path = new Path(result.filePath());
+ bitmaps.put(
+ state.id(),
+ new GlobalIndexIOMeta(
+ path, fileIO.getFileSize(path), result.rowCount(),
result.meta()));
+ }
PredicateBuilder builder = new PredicateBuilder(fields);
- Predicate red = builder.equal(0, BinaryString.fromString("red"));
- Predicate conjunction = PredicateBuilder.and(red, builder.isNull(1));
- assertThat(
- CentroidBitmapIndex.match(
- fileReader, meta, extraFieldIds, fields,
fields, conjunction))
- .containsExactly(90_000L);
- Predicate disjunction = PredicateBuilder.or(red, builder.isNotNull(1),
builder.isNull(1));
- assertThat(
- CentroidBitmapIndex.match(
- fileReader, meta, extraFieldIds, fields,
fields, disjunction))
- .containsExactly(90L, 90_000L);
- GlobalIndexIOMeta incomplete =
- new GlobalIndexIOMeta(path, secondSectionOffset, 2,
result.meta());
- assertThatThrownBy(
- () ->
- CentroidBitmapIndex.match(
- file -> {
- throw new AssertionError(
- "Invalid manifest opened a
file.");
- },
- incomplete,
- extraFieldIds,
- fields,
- fields,
- conjunction))
- .hasMessageContaining("Invalid centroid bitmap section");
- }
-
- @Test
- void singleCentroidBitmapSectionNeedsNoDirectory() throws IOException {
- ResultEntry result;
- try (CentroidBitmapIndex.Writer writer = new
CentroidBitmapIndex.Writer(fileWriter, 1, 2)) {
- writer.writeColumn(
- dataField,
- new Options(),
- column -> {
- column.write(null, 10);
- column.write(BinaryString.fromString("red"), 30);
- });
- result = writer.finish();
- }
- assertThat(result.meta()).isNull();
- Path path = new Path(result.filePath());
- GlobalIndexIOMeta meta =
- new GlobalIndexIOMeta(path, fileIO.getFileSize(path),
result.rowCount(), null);
- RowType rowType = RowType.of(dataField);
- assertThat(
- CentroidBitmapIndex.match(
- fileReader,
- meta,
- new int[] {dataField.id()},
- rowType,
- rowType,
- new PredicateBuilder(rowType).isNull(0)))
- .containsExactly(10L);
+ Predicate predicate =
+ PredicateBuilder.or(
+ PredicateBuilder.and(builder.equal(0, str("red")),
builder.isNull(1)),
+ builder.isNotNull(1));
+ AtomicInteger opens = new AtomicInteger();
+ IOFunction<Integer, RoaringNavigableMap64> filter =
+ CentroidBitmapIndex.filter(
+ file -> {
+ opens.incrementAndGet();
+ return fileReader.getInputStream(file);
+ },
+ bitmaps,
+ fields,
+ fields,
+ predicate,
+ rangeSize,
+ 3);
+ assertThat(opens).hasValue(0);
+ RoaringNavigableMap64 matched = filter.apply(2);
+ assertThat(matched).containsExactly(0L, 90_000L);
+ assertThat(filter.apply(0)).containsExactly(90L, rangeSize - 1);
+ assertThat(filter.apply(1)).isEmpty();
+ matched.clear();
+ assertThat(filter.apply(2)).containsExactly(0L, 90_000L);
+ assertThat(opens).hasValue(2);
}
@BeforeEach
diff --git
a/paimon-common/src/test/java/org/apache/paimon/utils/RoaringNavigableMap64Test.java
b/paimon-common/src/test/java/org/apache/paimon/utils/RoaringNavigableMap64Test.java
index 9f78b0488c..49d6c74ce6 100644
---
a/paimon-common/src/test/java/org/apache/paimon/utils/RoaringNavigableMap64Test.java
+++
b/paimon-common/src/test/java/org/apache/paimon/utils/RoaringNavigableMap64Test.java
@@ -47,6 +47,33 @@ public class RoaringNavigableMap64Test {
assertThat(bitmap.intersects(7, 7)).isFalse();
}
+ @Test
+ public void testRelativeRangeClipsAndRebasesRuns() {
+ long start = (1L << 32) - 100_000;
+ RoaringNavigableMap64 bitmap = new RoaringNavigableMap64();
+ bitmap.addRange(new Range(start - 12, start + 99_999));
+ bitmap.addRange(new Range(start + 100_004, start + 160_000));
+
+ assertThat(bitmap.relativeRange(new Range(start, start +
150_000)).toRangeList())
+ .containsExactly(new Range(0, 99_999), new Range(100_004,
150_000));
+ assertThat(bitmap.relativeRange(new Range(start + 100_000, start +
100_003))).isEmpty();
+ assertThat(bitmap.relativeRange(new Range(start + 140_000, start +
150_000)).toRangeList())
+ .containsExactly(new Range(0, 10_000));
+ assertThat(bitmap.getLongCardinality()).isEqualTo(160_009);
+ }
+
+ @Test
+ public void testRelativeRangeHandlesSparseValuesAtLongBoundary() {
+ RoaringNavigableMap64 bitmap =
+ RoaringNavigableMap64.bitmapOf(1, 7, Long.MAX_VALUE - 4,
Long.MAX_VALUE);
+
+ assertThat(bitmap.relativeRange(new Range(7, Long.MAX_VALUE)))
+ .containsExactly(0L, Long.MAX_VALUE - 11, Long.MAX_VALUE - 7);
+ assertThat(bitmap.relativeRange(new Range(Long.MAX_VALUE - 5,
Long.MAX_VALUE)))
+ .containsExactly(1L, 5L);
+ assertThat(bitmap.relativeRange(new Range(0, 6))).containsExactly(1L);
+ }
+
@Test
public void testAddRangeBasic() {
RoaringNavigableMap64 bitmap = new RoaringNavigableMap64();
diff --git
a/paimon-core/src/main/java/org/apache/paimon/globalindex/CentroidIndexMeta.java
b/paimon-core/src/main/java/org/apache/paimon/globalindex/CentroidIndexMeta.java
index ca30541bc8..28d956b7ec 100644
---
a/paimon-core/src/main/java/org/apache/paimon/globalindex/CentroidIndexMeta.java
+++
b/paimon-core/src/main/java/org/apache/paimon/globalindex/CentroidIndexMeta.java
@@ -62,6 +62,16 @@ public final class CentroidIndexMeta {
return isWrapped(meta) && role(meta) == ROUTER;
}
+ /** Whether the router covers a range with no non-null vectors. */
+ public static boolean isEmptyRouter(IndexFileMeta file) {
+ GlobalIndexMeta meta = file.globalIndexMeta();
+ byte[] descriptor = meta == null ? null : meta.indexMeta();
+ return file.fileSize() == 0
+ && file.rowCount() == 0
+ && isRoutingModel(descriptor)
+ && ByteBuffer.wrap(descriptor).getInt(MAGIC.length + 2) == 0;
+ }
+
/** Whether the index definition includes Bitmap fields, even in an
all-null range. */
public static boolean hasBitmapFields(GlobalIndexMeta meta) {
int[] fields = meta.extraFieldIds();
@@ -73,7 +83,7 @@ public final class CentroidIndexMeta {
return isWrapped(meta) && role(meta) == BITMAP;
}
- /** Scalar sections belong to the primary vector index for create and drop
operations. */
+ /** Scalar Bitmap files belong to the primary vector index for create and
drop operations. */
public static boolean matchesIndexFields(GlobalIndexMeta meta,
List<Integer> fieldIds) {
return meta.getIndexedFieldIds().equals(fieldIds)
|| (fieldIds.size() == 1
@@ -99,8 +109,8 @@ public final class CentroidIndexMeta {
return wrap(file, SHARD, centroid);
}
- public static ResultEntry scalarIndex(ResultEntry file, int centroid) {
- return wrap(file, BITMAP, centroid);
+ public static ResultEntry scalarIndex(ResultEntry file, int fieldId) {
+ return wrap(file, BITMAP, fieldId);
}
private static ResultEntry wrap(ResultEntry file, byte role, int
countOrId) {
diff --git
a/paimon-core/src/main/java/org/apache/paimon/manifest/IndexManifestFileHandler.java
b/paimon-core/src/main/java/org/apache/paimon/manifest/IndexManifestFileHandler.java
index bb772f7609..0ffb4d1ea8 100644
---
a/paimon-core/src/main/java/org/apache/paimon/manifest/IndexManifestFileHandler.java
+++
b/paimon-core/src/main/java/org/apache/paimon/manifest/IndexManifestFileHandler.java
@@ -25,6 +25,7 @@ import org.apache.paimon.index.DeletionVectorMeta;
import org.apache.paimon.index.GlobalIndexMeta;
import org.apache.paimon.index.IndexFileMeta;
import org.apache.paimon.table.BucketMode;
+import org.apache.paimon.utils.Triple;
import org.apache.paimon.shade.guava30.com.google.common.collect.Iterables;
import org.apache.paimon.shade.guava30.com.google.common.collect.Range;
@@ -225,6 +226,8 @@ public class IndexManifestFileHandler {
newIndexFiles.stream()
.filter(f -> f.kind() == FileKind.ADD)
.collect(Collectors.toList());
+ Set<Triple<BucketIdentifier, Integer, Range<Long>>>
removedCentroidRanges =
+ new HashSet<>();
for (IndexManifestEntry entry : removed) {
String fileName = entry.indexFile().fileName();
IndexManifestEntry previous = indexEntries.get(fileName);
@@ -234,6 +237,18 @@ public class IndexManifestFileHandler {
fileName);
checkDeletedIndexFile(previous, entry);
indexEntries.remove(fileName);
+ Triple<BucketIdentifier, Integer, Range<Long>> range =
centroidRange(previous);
+ if (range != null) {
+ removedCentroidRanges.add(range);
+ }
+ }
+ if (!removedCentroidRanges.isEmpty()) {
+ for (IndexManifestEntry retained : indexEntries.values()) {
+ checkState(
+
!removedCentroidRanges.contains(centroidRange(retained)),
+ "Cannot partially delete a centroid index
generation. File %s still exists.",
+ retained.indexFile().fileName());
+ }
}
validateRetainedIndexFiles(indexEntries.values(), added);
for (IndexManifestEntry entry : added) {
@@ -242,6 +257,17 @@ public class IndexManifestFileHandler {
return new ArrayList<>(indexEntries.values());
}
+ private static @Nullable Triple<BucketIdentifier, Integer,
Range<Long>> centroidRange(
+ IndexManifestEntry entry) {
+ GlobalIndexMeta meta = entry.indexFile().globalIndexMeta();
+ return meta != null &&
CentroidIndexMeta.isWrapped(meta.indexMeta())
+ ? Triple.of(
+ identifier(entry),
+ meta.indexFieldId(),
+ Range.closed(meta.rowRangeStart(),
meta.rowRangeEnd()))
+ : null;
+ }
+
private void validateRetainedIndexFiles(
Iterable<IndexManifestEntry> retainedIndexFiles,
List<IndexManifestEntry> addedIndexFiles) {
diff --git
a/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java
b/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java
index 5fd1742d18..180d80c1df 100644
---
a/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java
+++
b/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java
@@ -82,20 +82,22 @@ final class CentroidBitmapFilter {
IndexPathFactory paths =
table.store().pathFactory().globalIndexFileFactory();
Map<Integer, CentroidIndexFile> bitmaps = new HashMap<>();
- Map<Integer, CentroidIndexFile> shards = new HashMap<>();
- boolean hasRouter = false;
+ int nlist = -1;
+ long vectorCount = 0;
long schemaId = -1;
for (IndexFileMeta file : files) {
CentroidIndexFile entry = (CentroidIndexFile)
CentroidIndexMeta.file(file, paths);
if (entry.routingModel()) {
- checkState(!hasRouter, "Multiple centroid routing models.");
- hasRouter = true;
+ checkState(nlist == -1, "Multiple centroid routing models.");
+ nlist = entry.nlist();
} else if (entry.scalarIndex()) {
checkState(
Arrays.equals(extraFieldIds,
file.globalIndexMeta().extraFieldIds()),
"Mixed centroid bitmap fields.");
checkState(
- bitmaps.put(entry.centroid(), entry) == null,
"Duplicate centroid bitmap.");
+ bitmaps.put(entry.fieldId(), entry) == null,
+ "Duplicate centroid bitmap for field %s.",
+ entry.fieldId());
long bitmapSchemaId =
DataEvolutionIndexSourceMeta.fromIndexFile(file).sourceSchemaId();
checkState(bitmapSchemaId >= 0, "Missing centroid bitmap build
schema.");
@@ -103,23 +105,24 @@ final class CentroidBitmapFilter {
schemaId == -1 || schemaId == bitmapSchemaId,
"Mixed centroid bitmap schemas.");
schemaId = bitmapSchemaId;
- } else if (entry.rowCount() > 0) {
- checkState(
- shards.put(entry.centroid(), entry) == null,
"Duplicate centroid shard.");
+ } else {
+ vectorCount = Math.addExact(vectorCount, entry.rowCount());
}
}
- checkState(hasRouter, "Missing centroid routing model.");
- checkState(
- shards.keySet().equals(bitmaps.keySet()),
- "Centroid bitmap files do not cover the shard group.");
- if (bitmaps.isEmpty()) {
+ checkState(nlist >= 0, "Missing centroid routing model.");
+ if (vectorCount == 0) {
+ checkState(bitmaps.isEmpty(), "Unexpected bitmap for an empty
centroid range.");
return null;
}
- for (CentroidIndexFile bitmap : bitmaps.values()) {
- CentroidIndexFile shard = shards.get(bitmap.centroid());
+ checkState(
+ bitmaps.size() == extraFieldIds.length,
+ "Centroid bitmap files do not cover the extra fields.");
+ for (int fieldId : extraFieldIds) {
+ CentroidIndexFile bitmap = bitmaps.get(fieldId);
+ checkState(bitmap != null, "Missing centroid bitmap for field
%s.", fieldId);
checkState(
- bitmap.rowCount() == shard.rowCount(),
- "Centroid bitmap and vector shard row counts differ.");
+ bitmap.rowCount() == vectorCount,
+ "Centroid bitmap row count differs from the total vector
count.");
}
RowType buildType =
@@ -133,14 +136,14 @@ final class CentroidBitmapFilter {
return null;
}
}
- return centroid ->
- CentroidBitmapIndex.match(
- file -> table.fileIO().newInputStream(file.filePath()),
- bitmaps.get(centroid),
- extraFieldIds,
- rowType,
- buildType,
- predicate);
+ return CentroidBitmapIndex.filter(
+ file -> table.fileIO().newInputStream(file.filePath()),
+ bitmaps,
+ rowType,
+ buildType,
+ predicate,
+ meta.rowRange().count(),
+ nlist);
}
@Nullable
diff --git
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
index 7a2412bb74..86c40d5073 100644
---
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
+++
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
@@ -166,8 +166,7 @@ public class DataEvolutionVectorScan implements VectorScan {
vectorCoverage.add(meta.rowRange());
}
// An all-null range still supplies coverage, but has no vectors
to search or score.
- if (files.stream().allMatch(file -> file.rowCount() == 0)
- &&
files.stream().anyMatch(CentroidIndexMeta::isRoutingModel)) {
+ if (files.size() == 1 &&
CentroidIndexMeta.isEmptyRouter(files.get(0))) {
continue;
}
String type = entry.getKey().getRight();
diff --git
a/paimon-core/src/test/java/org/apache/paimon/globalindex/CentroidIndexMetaTest.java
b/paimon-core/src/test/java/org/apache/paimon/globalindex/CentroidIndexMetaTest.java
index da199b95f3..41e5a9f9e9 100644
---
a/paimon-core/src/test/java/org/apache/paimon/globalindex/CentroidIndexMetaTest.java
+++
b/paimon-core/src/test/java/org/apache/paimon/globalindex/CentroidIndexMetaTest.java
@@ -104,7 +104,8 @@ class CentroidIndexMetaTest {
CentroidIndexMeta.file(path, 100, bitmap.rowCount(),
bitmap.meta());
assertThat(decoded.scalarIndex()).isTrue();
assertThat(decoded.routingModel()).isFalse();
- assertThat(decoded.centroid()).isEqualTo(4);
+ assertThat(decoded.fieldId()).isEqualTo(4);
+ assertThatThrownBy(decoded::centroid).hasMessageContaining("Expected a
centroid shard");
assertThat(decoded.metadata()).containsExactly(9);
assertThat(bitmap.meta()[8]).isEqualTo((byte) 1);
diff --git a/paimon-python/pypaimon/manifest/centroid_index_groups.py
b/paimon-python/pypaimon/manifest/centroid_index_groups.py
index c0188fb3a8..06ef2a6ff7 100644
--- a/paimon-python/pypaimon/manifest/centroid_index_groups.py
+++ b/paimon-python/pypaimon/manifest/centroid_index_groups.py
@@ -26,15 +26,32 @@ from pypaimon.index.data_evolution_index_source_meta import
DataEvolutionIndexSo
_HEADER = Struct('>8sBci')
+def _group_key(entry):
+ file = entry.index_file
+ meta = file.global_index_meta
+ if meta is None or not meta.is_centroid_index():
+ return None
+ return (tuple(entry.partition.values), entry.bucket, file.index_type,
+ meta.index_field_id, meta.row_range_start, meta.row_range_end)
+
+
+def check_centroid_deletes(survivors, deletes):
+ deleted_groups = {_group_key(entry) for entry in deletes}
+ deleted_groups.discard(None)
+ if deleted_groups:
+ for entry in survivors:
+ if entry.kind == 0 and _group_key(entry) in deleted_groups:
+ raise RuntimeError("Cannot partially delete centroid
generation for '%s'"
+ % entry.index_file.file_name)
+
+
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)
+ if entry.kind == 0:
+ key = _group_key(entry)
+ if key is not None:
+ groups[key].append(entry)
return [_validate_group(group) for group in groups.values()]
@@ -54,7 +71,7 @@ def _validate_group(entries):
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:
+ if number in parts or file.file_size == 0 or file.row_count == 0:
raise invalid
parts[number] = file
else:
@@ -71,7 +88,7 @@ def _validate_group(entries):
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 meta.row_range_start < 0 or range_length <= 0
or vector_count > range_length or (nlist > 0 and vector_count == 0)
or any(shard_id >= nlist for shard_id in shards)):
raise invalid
@@ -81,13 +98,13 @@ def _validate_group(entries):
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 metric == b'l2' and file.index_type in ('ivf-flat', 'ivf-pq'):
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:
+ expected = dict.fromkeys(extra, vector_count) if vector_count else {}
+ if {field_id: bitmap.row_count for field_id, bitmap in bitmaps.items()} !=
expected:
raise invalid
if not
DataEvolutionIndexSourceMeta.is_data_evolution_meta(meta.source_meta):
raise invalid
diff --git a/paimon-python/pypaimon/manifest/index_manifest_file.py
b/paimon-python/pypaimon/manifest/index_manifest_file.py
index 673d01fbb9..079cf4084d 100644
--- a/paimon-python/pypaimon/manifest/index_manifest_file.py
+++ b/paimon-python/pypaimon/manifest/index_manifest_file.py
@@ -25,7 +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.centroid_index_groups import centroid_routers,
check_centroid_deletes
from pypaimon.manifest.index_manifest_entry import IndexManifestEntry
from pypaimon.table.row.generic_row import (GenericRowDeserializer,
GenericRowSerializer)
@@ -258,8 +258,7 @@ 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)
+ check_centroid_deletes(survivors, deletes)
routers = centroid_routers(adds)
if routers:
ordinary_adds = [entry for entry in adds if not
_is_centroid_entry(entry)]
diff --git a/paimon-python/pypaimon/tests/global_index_build_test.py
b/paimon-python/pypaimon/tests/global_index_build_test.py
index 9bd3f7320a..2ca7524f06 100644
--- a/paimon-python/pypaimon/tests/global_index_build_test.py
+++ b/paimon-python/pypaimon/tests/global_index_build_test.py
@@ -49,6 +49,7 @@ from pypaimon.globalindex.full_text_options import (
NativeFullTextIndexOptions,
)
from pypaimon.globalindex.global_index_meta import GlobalIndexMeta
+from pypaimon.globalindex.sorted_index_file_meta import SortedIndexFileMeta
from pypaimon.execution.python.write.native_full_text_index_writer import
NativeFullTextIndexWriter
from pypaimon.execution.python.globalindex.vindex.vindex_vector_index_writer
import (
VindexVectorIndexWriter,
@@ -250,7 +251,8 @@ class GlobalIndexBuildTest(
'read.native.enabled': 'false',
'scan.native-plan.enabled': 'false',
})
- self._write_arrow(table, pa.table({'embedding': [[1.0, 2.0]],
'status': ['ready']},
+ self._write_arrow(table, pa.table({'embedding': [[1.0, 2.0], [1.0,
2.0]],
+ 'status': ['ready', 'ready']},
schema=schema))
vector_id = table.field_dict['embedding'].id
status_id = table.field_dict['status'].id
@@ -261,13 +263,13 @@ class GlobalIndexBuildTest(
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, source)))
+ global_index_meta=GlobalIndexMeta(0, 1, vector_id, fields,
metadata, source)))
centroid_files = []
for role, rows, number, payload in (
- (b'R', 0, 1, b'l2'),
- (b'S', 1, 0, struct.pack('>i', 1)),
- (b'B', 1, 0, b''),
+ (b'R', 0, 2, b'l2'),
+ (b'S', 2, 0, struct.pack('>i', 1)),
+ (b'B', 2, status_id, SortedIndexFileMeta(b'ready', b'ready',
False).serialize()),
):
header = struct.pack('>8sBci', b'PAIMCENT', 1, role, number)
centroid_files.append(entry(role.decode('ascii'), rows, header +
payload, [status_id]))
@@ -284,7 +286,7 @@ class GlobalIndexBuildTest(
commit = table.new_batch_write_builder().new_commit()
try:
with self.assertRaisesRegex(RuntimeError, "overlapping row range"):
- commit.commit([CommitMessage((), 0, [],
index_adds=[entry('range', 1, b'{}')])])
+ commit.commit([CommitMessage((), 0, [],
index_adds=[entry('range', 2, b'{}')])])
finally:
commit.close()
self.assertEqual(3, table.drop_global_index('embedding', 'ivf-flat'))
diff --git a/paimon-python/pypaimon/tests/native_vector_index_layout_test.py
b/paimon-python/pypaimon/tests/native_vector_index_layout_test.py
index 2c7dfe5e58..940bccfa00 100644
--- a/paimon-python/pypaimon/tests/native_vector_index_layout_test.py
+++ b/paimon-python/pypaimon/tests/native_vector_index_layout_test.py
@@ -93,6 +93,9 @@ def test_centroid_shards_and_bitmap_filter(catalog):
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)
+ bitmaps = [file for file in files if
file.global_index_meta.index_meta[9:10] == b'B']
+ assert {int.from_bytes(file.global_index_meta.index_meta[10:14], 'big')
for file in bitmaps} == fields
+ assert all(file.row_count == 4 for file in bitmaps)
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()
@@ -119,6 +122,22 @@ def test_centroid_shards_and_bitmap_filter(catalog):
.with_option('centroid.nprobe', 2).execute_local()) == [0, 2]
+def test_all_null_centroid_range_has_a_zero_byte_router(catalog):
+ table = _table(catalog)
+ indexes._append(table, [dict(ROWS[-1], id=0)], SCHEMA)
+ assert table.create_global_index('embedding', 'ivf-flat', options=CENTROID,
+ extra_fields={'status': 'bitmap'}) == 1
+ router, = indexes._files(table)
+ meta = router.global_index_meta
+ assert meta.index_meta[:14] == b'PAIMCENT\x01R\x00\x00\x00\x00'
+ assert (meta.row_range_start, meta.row_range_end) == (0, 0)
+ assert router.file_size == router.row_count == 0
+ with table.file_io.new_input_stream(indexes._path(table, router)) as
stream:
+ assert stream.read() == b''
+ assert _single(table, [0, 0], 1).execute_local().is_empty()
+ assert table.drop_global_index('embedding', 'ivf-flat') == 1
+
+
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)
@@ -232,8 +251,8 @@ def
test_centroid_build_resolves_field_json_and_scopes_extra_fields(catalog):
'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('embedding', 'ivf-flat', options=RANGE)
== 4
+ assert table.create_global_index('embedding', 'ivf-flat', options=RANGE,
extra_fields={'status': 'bitmap'}) == 4
assert table.create_global_index('id', 'btree') > 0
@@ -274,9 +293,9 @@ def
test_rebuild_replaces_centroid_generation_and_drop_removes_bitmaps(catalog,
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
+ extra_fields='{"status":"bitmap"}',
execution=execution) == 4
assert old.isdisjoint(file.file_name for file in indexes._files(table))
- assert table.drop_global_index('embedding', 'ivf-flat') == 5
+ assert table.drop_global_index('embedding', 'ivf-flat') == 4
assert indexes._files(table) == []
@@ -284,9 +303,9 @@ 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
+ extra_fields={'status': 'bitmap'}) == 4
with patch('pypaimon_rust.datafusion.GlobalIndexBuildPlan', object):
- assert table.drop_global_index('embedding', 'ivf-flat') == 5
+ assert table.drop_global_index('embedding', 'ivf-flat') == 4
assert indexes._files(table) == []
@@ -315,18 +334,19 @@ def
test_centroid_bitmap_commit_checks_source_and_retained_index(catalog):
assert _ids(table, result) == [0]
-def
test_python_commit_rejects_conflicting_and_incomplete_centroid_groups(catalog):
[email protected]('extra_fields', [None, {'status': 'bitmap'}],
ids=['vector', 'bitmap'])
+def
test_python_commit_rejects_conflicting_and_incomplete_centroid_groups(catalog,
extra_fields):
table = _table(catalog)
indexes._append(table, ROWS, SCHEMA)
- build = GlobalIndexBuilder(table, 'embedding', 'ivf-flat',
options=CENTROID, extra_fields={'status': 'bitmap'})
+ build = GlobalIndexBuilder(table, 'embedding', 'ivf-flat',
options=CENTROID, extra_fields=extra_fields)
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'):
+ entry = next(entry for entry in first[0].index_adds if
entry.index_file.global_index_meta.index_meta[9:10] == b'S')
+ with pytest.raises(RuntimeError, match='Cannot partially delete centroid
generation'):
indexes._commit(table, [CommitMessage((), 0, [],
index_deletes=[replace(entry, kind=1)])])
assert _ids(table, _single(table, [0, 0], 1).execute_local()) == [0]
@@ -347,14 +367,14 @@ 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
+ extra_fields={'status': 'bitmap'}) == 8
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 len(retained) == 4
assert {entry.index_file.file_name for entry in handler.scan(None)} ==
retained
@@ -364,7 +384,7 @@ def
test_staged_partition_delete_rechecks_retained_centroid_index(catalog, extra
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
+ count = 4 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'):
@@ -394,7 +414,7 @@ def
test_python_commit_reads_a_historical_centroid_source_once(filesystem_catalo
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
+ assert len(indexes._files(table)) == 4
@pytest.mark.parametrize('column, value, conflicts', [('status', ['keep'],
True), ('tenant', [2], False)])
@@ -418,7 +438,7 @@ def
test_centroid_build_checks_compacted_source_columns(catalog, column, value,
indexes._commit(table, staged)
else:
indexes._commit(table, staged)
- assert len(indexes._files(table)) == (0 if conflicts else 5)
+ assert len(indexes._files(table)) == (0 if conflicts else 4)
def
test_centroid_build_rejects_deleted_partial_column_source(filesystem_catalog):
diff --git
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidGlobalIndexTopoBuilder.java
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidGlobalIndexTopoBuilder.java
index 40b5968e17..52b50f5e1c 100644
---
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidGlobalIndexTopoBuilder.java
+++
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidGlobalIndexTopoBuilder.java
@@ -25,7 +25,6 @@ import org.apache.paimon.data.BinaryRow;
import org.apache.paimon.data.BinaryString;
import org.apache.paimon.data.GenericRow;
import org.apache.paimon.data.InternalRow;
-import org.apache.paimon.data.serializer.InternalRowSerializer;
import org.apache.paimon.disk.IOManager;
import org.apache.paimon.globalindex.CentroidIndexMeta;
import org.apache.paimon.globalindex.CentroidVectorGlobalIndexer;
@@ -38,15 +37,16 @@ import org.apache.paimon.globalindex.KeySerializer;
import org.apache.paimon.globalindex.ResultEntry;
import org.apache.paimon.globalindex.VectorIndexUtils;
import org.apache.paimon.globalindex.VectorTrainingModel;
+import org.apache.paimon.globalindex.bitmap.BitmapGlobalIndexWriter;
+import org.apache.paimon.globalindex.bitmap.BitmapGlobalIndexer;
import org.apache.paimon.globalindex.bitmap.CentroidBitmapIndex;
import org.apache.paimon.index.DataEvolutionIndexSourceMeta;
import org.apache.paimon.index.IndexFileMeta;
import org.apache.paimon.io.CompactIncrement;
import org.apache.paimon.io.DataIncrement;
-import org.apache.paimon.io.DataInputDeserializer;
-import org.apache.paimon.io.DataOutputSerializer;
import org.apache.paimon.manifest.IndexManifestEntry;
import org.apache.paimon.manifest.ManifestEntry;
+import org.apache.paimon.memory.MemorySlice;
import org.apache.paimon.options.Options;
import org.apache.paimon.partition.PartitionPredicate;
import org.apache.paimon.sort.BinaryExternalSortBuffer;
@@ -319,7 +319,7 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
}
Broadcast<byte[]> broadcast = sc.broadcast(payload);
try {
- int parallelism = Math.min(nlist, slots);
+ int parallelism = (int) Math.min((long) nlist +
context.extraFields().size(), slots);
JavaRDD<InternalRow> routedRows =
context.hasBitmaps()
? inputSplits.mapPartitions(
@@ -338,15 +338,8 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
broadcast.value()));
List<byte[]> results =
assigned.repartitionAndSortWithinPartitions(new
HashPartitioner(parallelism))
- .mapPartitionsWithIndex(
- (partition, input) ->
- writeShards(
-
BuildContext.restore(contextBytes),
- input,
- partition,
- parallelism,
- nlist),
- false)
+ .mapPartitions(
+ input ->
writeFiles(BuildContext.restore(contextBytes), input))
.collect();
List<CommitMessage> messages =
CommitMessageSerializer.deserializeAll(results);
messages.add(writeRouter(context, indexer, payload, nlist));
@@ -467,38 +460,48 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
InternalRow.FieldGetter getter = context.getter(context.readType);
int idPosition =
context.readType.getFieldIndex(SpecialFields.ROW_ID.name());
List<InternalRow.FieldGetter> extraGetters = new ArrayList<>();
+ List<KeySerializer> serializers = new ArrayList<>();
for (DataField field : context.extraFields()) {
extraGetters.add(
InternalRow.createFieldGetter(
field.type(),
context.readType.getFieldIndex(field.name())));
- }
- InternalRowSerializer serializer =
- new InternalRowSerializer(new RowType(context.extraFields()));
- DataOutputSerializer buffer = new DataOutputSerializer(128);
- GenericRow extras = new GenericRow(extraGetters.size());
- return Iterators.transform(
- input,
- row -> {
- float[] vector =
VectorIndexUtils.toFloatArray(getter.getFieldOrNull(row));
- byte[] keys = null;
- if (!extraGetters.isEmpty()) {
- for (int i = 0; i < extraGetters.size(); i++) {
- extras.setField(i,
extraGetters.get(i).getFieldOrNull(row));
- }
- try {
- buffer.clear();
- serializer.serialize(extras, buffer);
- keys = buffer.getCopyOfBuffer();
- } catch (IOException e) {
- throw new UncheckedIOException(e);
- }
- }
- return new Tuple2<>(
- model.assignCentroid(vector),
- new Tuple2<>(
- row.getLong(idPosition) -
context.rowRange.from,
- new Tuple2<>(vector, keys)));
- });
+ serializers.add(KeySerializer.create(field.type()));
+ }
+ long rowRangeSize = context.rowRange.count();
+ return Iterators.concat(
+ Iterators.transform(
+ input,
+ row -> {
+ float[] vector =
+
VectorIndexUtils.toFloatArray(getter.getFieldOrNull(row));
+ int centroid = model.assignCentroid(vector);
+ long rowId = row.getLong(idPosition) -
context.rowRange.from;
+ Tuple2<Integer, Tuple2<Long, Tuple2<float[],
byte[]>>> vectorRow =
+ new Tuple2<>(
+ centroid,
+ new Tuple2<>(rowId, new
Tuple2<>(vector, null)));
+ if (extraGetters.isEmpty()) {
+ return Iterators.singletonIterator(vectorRow);
+ }
+ // Each negative key owns one complete Bitmap,
independent of vector
+ // shards.
+ long bitmapRowId =
+ CentroidBitmapIndex.encodeRowId(centroid,
rowRangeSize, rowId);
+ List<Tuple2<Integer, Tuple2<Long, Tuple2<float[],
byte[]>>>> entries =
+ new ArrayList<>(1 + extraGetters.size());
+ for (int i = 0; i < extraGetters.size(); i++) {
+ Object value =
extraGetters.get(i).getFieldOrNull(row);
+ byte[] key =
+ value == null ? null :
serializers.get(i).serialize(value);
+ entries.add(
+ new Tuple2<>(
+ -1 - i,
+ new Tuple2<>(
+ bitmapRowId, new
Tuple2<>(null, key))));
+ }
+ entries.add(vectorRow);
+ return entries.iterator();
+ }));
}
private static void closeOnTaskCompletion(AutoCloseable resource) {
@@ -515,42 +518,32 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
});
}
- private static Iterator<byte[]> writeShards(
+ private static Iterator<byte[]> writeFiles(
BuildContext context,
- Iterator<Tuple2<Integer, Tuple2<Long, Tuple2<float[], byte[]>>>>
rows,
- int partition,
- int parallelism,
- int nlist)
+ Iterator<Tuple2<Integer, Tuple2<Long, Tuple2<float[], byte[]>>>>
rows)
throws Exception {
List<byte[]> commits = new ArrayList<>();
PeekingIterator<Tuple2<Integer, Tuple2<Long, Tuple2<float[],
byte[]>>>> input =
Iterators.peekingIterator(rows);
CentroidVectorGlobalIndexer indexer = context.indexer();
GlobalIndexFileReadWrite io = context.io();
- // HashPartitioner assigns nonnegative integer keys by modulo. Emit
empty shards here
- // as well, without a second set of input tasks to shuffle sentinel
records.
- for (int centroid = partition; centroid < nlist; centroid +=
parallelism) {
+ while (input.hasNext() && input.peek()._1() < 0) {
+ int key = input.peek()._1();
+ DataField field = context.extraFields().get(-1 - key);
+ commits.add(context.finish(writeBitmap(context, io, input, key,
field)));
+ }
+ while (input.hasNext()) {
+ int centroid = input.peek()._1();
GlobalIndexSingleColumnWriter writer =
indexer.createCentroidWriter(io);
- try (BitmapSorters bitmapSorters =
- context.hasBitmaps() && input.hasNext() &&
input.peek()._1() == centroid
- ? new BitmapSorters(context)
- : null) {
+ try {
while (input.hasNext() && input.peek()._1() == centroid) {
Tuple2<Long, Tuple2<float[], byte[]>> row =
input.next()._2();
writer.write(row._2()._1(), row._1());
- if (bitmapSorters != null) {
- bitmapSorters.add(row._1(), row._2()._2());
- }
}
List<ResultEntry> files = new ArrayList<>();
for (ResultEntry file : writer.finish()) {
files.add(CentroidIndexMeta.shard(file, centroid));
}
- if (bitmapSorters != null) {
- files.add(
- CentroidIndexMeta.scalarIndex(
- bitmapSorters.finish(context, io),
centroid));
- }
commits.add(context.finish(files));
} finally {
close(writer);
@@ -559,97 +552,59 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
return commits.iterator();
}
- private static final class BitmapSorters implements AutoCloseable {
- private final IOManager ioManager;
- private final List<BinaryExternalSortBuffer> buffers = new
ArrayList<>();
- private final List<InternalRow.FieldGetter> getters = new
ArrayList<>();
- private final InternalRowSerializer serializer;
- private final DataInputDeserializer input = new
DataInputDeserializer();
- private long count;
-
- BitmapSorters(BuildContext context) throws Exception {
- List<DataField> fields = context.extraFields();
- this.serializer = new InternalRowSerializer(new RowType(fields));
- CoreOptions options = new CoreOptions(context.options);
- long memory =
- Math.max(3L * options.pageSize(),
options.writeBufferSize() / fields.size());
- this.ioManager =
IOManager.create(System.getProperty("java.io.tmpdir"));
+ private static List<ResultEntry> writeBitmap(
+ BuildContext context,
+ GlobalIndexFileReadWrite files,
+ PeekingIterator<Tuple2<Integer, Tuple2<Long, Tuple2<float[],
byte[]>>>> input,
+ int key,
+ DataField field)
+ throws Exception {
+ CoreOptions options = new CoreOptions(context.options);
+ KeySerializer serializer = KeySerializer.create(field.type());
+ try (IOManager ioManager =
IOManager.create(System.getProperty("java.io.tmpdir"))) {
+ BinaryExternalSortBuffer buffer =
+ BinaryExternalSortBuffer.create(
+ ioManager,
+ RowType.of(field, SpecialFields.ROW_ID),
+ new int[] {0},
+ Math.max(3L * options.pageSize(),
options.writeBufferSize()),
+ options.pageSize(),
+ options.localSortMaxNumFileHandles(),
+ options.spillCompressOptions(),
+ options.writeBufferSpillDiskSize());
try {
- for (int i = 0; i < fields.size(); i++) {
- DataField field = fields.get(i);
- getters.add(InternalRow.createFieldGetter(field.type(),
i));
- buffers.add(
- BinaryExternalSortBuffer.create(
- ioManager,
- RowType.of(field, SpecialFields.ROW_ID),
- new int[] {0},
- memory,
- options.pageSize(),
- options.localSortMaxNumFileHandles(),
- options.spillCompressOptions(),
- options.writeBufferSpillDiskSize()));
- }
- } catch (Exception | Error failure) {
- try {
- close();
- } catch (Exception cleanupFailure) {
- failure.addSuppressed(cleanupFailure);
+ while (input.hasNext() && input.peek()._1() == key) {
+ Tuple2<Long, Tuple2<float[], byte[]>> row =
input.next()._2();
+ byte[] bytes = row._2()._2();
+ Object value =
+ bytes == null ? null :
serializer.deserialize(MemorySlice.wrap(bytes));
+ checkArgument(
+ buffer.write(GenericRow.of(value, row._1())),
+ "Centroid bitmap sort buffer could not accept a
row.");
}
- throw failure;
- }
- }
-
- void add(long rowId, byte[] keys) throws IOException {
- input.setBuffer(keys);
- InternalRow row = serializer.deserialize(input);
- for (int i = 0; i < buffers.size(); i++) {
- Object value = getters.get(i).getFieldOrNull(row);
- checkArgument(
- buffers.get(i).write(GenericRow.of(value, rowId)),
- "Centroid bitmap sort buffer could not accept a row.");
- }
- count++;
- }
-
- ResultEntry finish(BuildContext context, GlobalIndexFileReadWrite
files)
- throws IOException {
- List<DataField> fields = context.extraFields();
- try (CentroidBitmapIndex.Writer writer =
- new CentroidBitmapIndex.Writer(files, fields.size(),
count)) {
- for (int i = 0; i < fields.size(); i++) {
- DataField field = fields.get(i);
- BinaryExternalSortBuffer buffer = buffers.get(i);
+ BitmapGlobalIndexer indexer =
+ new BitmapGlobalIndexer(
+ field, options.globalIndexOptions("bitmap",
field.name()));
+ try (BitmapGlobalIndexWriter bitmap =
indexer.createWriter(files)) {
Iterator<InternalRow> rows =
new MutableObjectIteratorAdapter<>(
buffer.sortedIterator(), new BinaryRow(2));
InternalRow.FieldGetter getter =
InternalRow.createFieldGetter(field.type(), 0);
- writer.writeColumn(
- field,
- new CoreOptions(context.options)
- .globalIndexOptions("bitmap",
field.name()),
- bitmap -> {
- while (rows.hasNext()) {
- InternalRow row = rows.next();
- Object value = getter.getFieldOrNull(row);
- bitmap.write(
- value instanceof BinaryString
- ? ((BinaryString)
value).copy()
- : value,
- row.getLong(1));
- }
- });
- buffer.clear();
+ while (rows.hasNext()) {
+ InternalRow row = rows.next();
+ Object value = getter.getFieldOrNull(row);
+ bitmap.write(
+ value instanceof BinaryString
+ ? ((BinaryString) value).copy()
+ : value,
+ row.getLong(1));
+ }
+ return bitmap.finish().stream()
+ .map(file -> CentroidIndexMeta.scalarIndex(file,
field.id()))
+ .collect(Collectors.toList());
}
- return writer.finish();
- }
- }
-
- @Override
- public void close() throws Exception {
- try {
- buffers.forEach(BinaryExternalSortBuffer::clear);
} finally {
- ioManager.close();
+ buffer.clear();
}
}
}
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidVectorIndexTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidVectorIndexTest.scala
index 210a562ac2..465fc520e9 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidVectorIndexTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidVectorIndexTest.scala
@@ -36,7 +36,7 @@ import scala.collection.JavaConverters._
/** End-to-end centroid build over nonzero, disjoint source row-ID ranges. */
class CentroidVectorIndexTest extends PaimonSparkTestBase {
- test("centroid interchange tables carry empty files and canonical metrics") {
+ test("centroid interchange tables omit empty shards and carry canonical
metrics") {
val bitmapTable = "centroid_bitmap"
val metricsTable = "centroid_metrics"
withTable(bitmapTable, metricsTable) {
@@ -58,7 +58,7 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase {
spark
.sql(
s"""CALL sys.create_global_index(table=>'$dbName0.$bitmapTable',
index_column=>'v',
- |index_type=>'ivf-flat', extra_fields=>'{"status":"bitmap"}',
+ |index_type=>'ivf-flat',
extra_fields=>'{"id":"bitmap","status":"bitmap"}',
|options=>'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.metric=$paddedL2,ivf-flat.centroid.nlist=2,ivf-flat.nlist=1,ivf-flat.train.sample-ratio=1')""".stripMargin)
.collect()
@@ -93,21 +93,26 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase {
.map(_.indexFile())
val routers = files.filter(CentroidIndexMeta.isRoutingModel)
assert(routers.map(_.fileSize() == 0).toSet == Set(true, false))
+ val paths = table.store().pathFactory().globalIndexFileFactory()
+ assert(
+ routers.forall(file => table.fileIO().getFileSize(paths.toPath(file))
== file.fileSize()))
+ assert(
+ routers
+ .map(file =>
ByteBuffer.wrap(file.globalIndexMeta().indexMeta()).getInt(10))
+ .toSet == Set(0, 2))
assert(routers.forall(
file =>
new String(file.globalIndexMeta().indexMeta().drop(14),
StandardCharsets.UTF_8) == "l2"))
val shards = files.filterNot(
file => CentroidIndexMeta.isRoutingModel(file) ||
CentroidIndexMeta.isScalarIndex(file))
- assert(shards.count(_.rowCount() == 0) == 1)
- assert(
- shards
- .filter(_.rowCount() > 0)
- .forall(file =>
ByteBuffer.wrap(file.globalIndexMeta().indexMeta()).getInt(14) == 1))
+ assert(shards.size == 1)
+ assert(shards.head.rowCount() == 4)
+
assert(ByteBuffer.wrap(shards.head.globalIndexMeta().indexMeta()).getInt(14) ==
1)
assert(
files
.filter(CentroidIndexMeta.isScalarIndex)
- .map(_.globalIndexMeta().indexMeta().length)
- .toSeq == Seq(14))
+ .map(file =>
ByteBuffer.wrap(file.globalIndexMeta().indexMeta()).getInt(10))
+ .toSet == Set(0, 2))
sys.env.get("PAIMON_JAVA_CENTROID_FIXTURE").foreach {
directory =>
@@ -179,10 +184,11 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase
{
.map(_.indexFile())
.toSeq
}
- def nearest(predicate: String): Seq[Int] =
+ def nearest(predicate: String, probes: Int = 2): Seq[Int] =
spark
- .sql(s"""SELECT id FROM vector_search('T','v',array(0.0f,0.0f),1,
- |map('centroid.nprobe','2','ivf.nprobe','1')) WHERE
$predicate""".stripMargin)
+ .sql(
+ s"""SELECT id FROM vector_search('T','v',array(0.0f,0.0f),1,
+ |map('centroid.nprobe','$probes','ivf.nprobe','1')) WHERE
$predicate""".stripMargin)
.collect()
.map(_.getInt(0))
.toSeq
@@ -209,9 +215,17 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase {
build("""{"tenant":"bitmap","status":"bitmap"}""")
assert(files.count(CentroidIndexMeta.isRoutingModel) == 1)
- assert(files.count(CentroidIndexMeta.isScalarIndex) == 2)
-
assert(files.filter(CentroidIndexMeta.isScalarIndex).map(_.rowCount()).sum ==
64)
- val coveredPlan = loadTable("T")
+ val table = loadTable("T")
+ val paths = table.store().pathFactory().globalIndexFileFactory()
+ val bitmaps = files.filter(CentroidIndexMeta.isScalarIndex).map {
+ file => CentroidIndexMeta.file(file,
paths).asInstanceOf[CentroidIndexFile]
+ }
+ assert(bitmaps.size == 2)
+ assert(
+ bitmaps.map(_.fieldId()).toSet ==
+ Set(table.rowType().getField("tenant").id(),
table.rowType().getField("status").id()))
+ assert(bitmaps.forall(_.rowCount() == 64))
+ val coveredPlan = table
.newVectorSearchBuilder()
.withVectorColumn("v")
.withVector(Array(0f, 0f))
@@ -221,9 +235,11 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase {
assert(!coveredPlan.splits().asScala.exists(_.isInstanceOf[RawVectorSearchSplit]))
assert(nearest("tenant IN ('red', 'green') AND status IS NULL") ==
Seq(48))
assert(nearest("tenant = 'blue' AND status IS NULL").isEmpty)
+ assert(nearest("status IS NULL", probes = 1).isEmpty)
build("""{"status":"bitmap"}""")
assert(files.count(CentroidIndexMeta.isRoutingModel) == 1)
+ assert(files.count(CentroidIndexMeta.isScalarIndex) == 1)
assert(files.forall(_.globalIndexMeta().extraFieldIds().length == 1))
assert(nearest("status IS NULL") == Seq(48))
for (inReader <- Seq(false, true)) {
@@ -291,7 +307,7 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase {
}
}
- test("centroid shard bitmaps apply cross-column OR before top K") {
+ test("centroid field bitmaps apply cross-column OR before top K") {
withTable("T") {
spark.sql("""CREATE TABLE T (id INT, v ARRAY<FLOAT>, tenant_id INT,
status STRING, p INT)
|PARTITIONED BY (p) TBLPROPERTIES (
diff --git
a/paimon-vector/src/main/java/org/apache/paimon/vector/index/NativeCentroidRoutedIndexReader.java
b/paimon-vector/src/main/java/org/apache/paimon/vector/index/NativeCentroidRoutedIndexReader.java
index bab29dc7e2..d28f834dd9 100644
---
a/paimon-vector/src/main/java/org/apache/paimon/vector/index/NativeCentroidRoutedIndexReader.java
+++
b/paimon-vector/src/main/java/org/apache/paimon/vector/index/NativeCentroidRoutedIndexReader.java
@@ -55,7 +55,6 @@ import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;
import static org.apache.paimon.utils.Preconditions.checkArgument;
-import static org.apache.paimon.utils.Preconditions.checkNotNull;
/** Routes queries to shard files using row IDs relative to their shared
range. */
final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexReader
@@ -102,8 +101,7 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
checkArgument(modelMeta == null, "Multiple routing models.");
modelMeta = meta;
} else {
- checkArgument(
- file.rowCount() >= 0, "Centroid shards must record
their vector count.");
+ checkArgument(file.rowCount() > 0, "Centroid shards must
contain vectors.");
checkArgument(
shards.put(meta.centroid(), file) == null,
"Duplicate centroid shard %s.",
@@ -116,15 +114,14 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
this.metric =
NativeCentroidVectorGlobalIndexer.routingMetric(modelMeta);
this.vectorCount = count;
int nlist = routing.nlist();
- checkArgument(
- shards.size() == nlist, "Centroid shards do not cover all
routing centroids.");
+ checkArgument(nlist == 0 || count > 0, "Centroid routing model has no
vector shards.");
boolean storesLocalNlist = storesLocalNlist(indexType, metric);
for (Map.Entry<Integer, GlobalIndexIOMeta> shard : shards.entrySet()) {
int centroid = shard.getKey();
checkArgument(
centroid >= 0 && centroid < nlist, "Invalid shard centroid
%s.", centroid);
byte[] local = shard.getValue().metadata();
- if (storesLocalNlist && shard.getValue().rowCount() > 0) {
+ if (storesLocalNlist) {
checkArgument(
local != null && local.length == Integer.BYTES,
"Invalid centroid shard metadata.");
@@ -166,10 +163,6 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
return model;
}
- private GlobalIndexIOMeta shard(int centroid) {
- return checkNotNull(shards.get(centroid), "Missing routed centroid
shard %s.", centroid);
- }
-
private NativeVectorGlobalIndexReader openShard(GlobalIndexIOMeta shard) {
return new NativeVectorGlobalIndexReader(
files, Collections.singletonList(shard), fieldType, executor,
indexType);
@@ -289,8 +282,10 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
boolean joint = considerJoint;
for (int i = 0; joint && i < JOINT_OUTER_PROBES; i++) {
int centroid = nearest[i];
+ GlobalIndexIOMeta shard = shards.get(centroid);
joint =
- shard(centroid).rowCount()
+ shard != null
+ && shard.rowCount()
>= (long)
NativeVectorGlobalIndexReader.JOINT_INNER_PROBES
* query.limit()
&& jointLayout.contains(centroid);
@@ -473,8 +468,8 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
}
Map<Boolean, List<Integer>> policy =
Collections.singletonMap(false, indices);
for (int centroid : plans.get(0).centers) {
- GlobalIndexIOMeta file = shard(centroid);
- if (file.rowCount() > 0) {
+ GlobalIndexIOMeta file = shards.get(centroid);
+ if (file != null) {
groups.put(file, policy);
}
}
@@ -487,8 +482,8 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
Route route = plans.get(i);
for (int centroid : route.centers) {
if (route.visited.add(centroid)) {
- GlobalIndexIOMeta file = shard(centroid);
- if (file.rowCount() > 0) {
+ GlobalIndexIOMeta file = shards.get(centroid);
+ if (file != null) {
groups.computeIfAbsent(file, ignored -> new
LinkedHashMap<>())
.computeIfAbsent(route.joint, ignored -> new
ArrayList<>())
.add(i);
diff --git
a/paimon-vector/src/main/java/org/apache/paimon/vector/index/NativeVectorGlobalIndexWriter.java
b/paimon-vector/src/main/java/org/apache/paimon/vector/index/NativeVectorGlobalIndexWriter.java
index 0a5ed7862b..20d7b679d9 100644
---
a/paimon-vector/src/main/java/org/apache/paimon/vector/index/NativeVectorGlobalIndexWriter.java
+++
b/paimon-vector/src/main/java/org/apache/paimon/vector/index/NativeVectorGlobalIndexWriter.java
@@ -307,14 +307,7 @@ public class NativeVectorGlobalIndexWriter implements
GlobalIndexSingleColumnWri
}
try {
if (count == 0) {
- if (!centroidShard) {
- return Collections.emptyList();
- }
- String filePath = fileWriter.newFilePath(fileNamePrefix());
- try (PositionOutputStream out =
fileWriter.newOutputStream(filePath)) {
- out.write(new byte[] {'P', 'C', 'E', 'M', 'P', 'T', 'Y',
'1'});
- }
- return Collections.singletonList(new ResultEntry(filePath, 0,
null));
+ return Collections.emptyList();
}
flushWriteBuffer();
writeChannel.close();
diff --git
a/paimon-vector/src/test/java/org/apache/paimon/vector/index/CentroidTableInteropTest.java
b/paimon-vector/src/test/java/org/apache/paimon/vector/index/CentroidTableInteropTest.java
index b6ddd8df0f..38115a0b2d 100644
---
a/paimon-vector/src/test/java/org/apache/paimon/vector/index/CentroidTableInteropTest.java
+++
b/paimon-vector/src/test/java/org/apache/paimon/vector/index/CentroidTableInteropTest.java
@@ -18,12 +18,16 @@
package org.apache.paimon.vector.index;
+import org.apache.paimon.data.BinaryRow;
import org.apache.paimon.fs.FileIO;
import org.apache.paimon.fs.Path;
import org.apache.paimon.fs.local.LocalFileIO;
+import org.apache.paimon.globalindex.CentroidIndexFile;
import org.apache.paimon.globalindex.CentroidIndexMeta;
import org.apache.paimon.index.DataEvolutionIndexSourceMeta;
import org.apache.paimon.index.IndexFileMeta;
+import org.apache.paimon.io.CompactIncrement;
+import org.apache.paimon.io.DataIncrement;
import org.apache.paimon.manifest.IndexManifestEntry;
import org.apache.paimon.predicate.Predicate;
import org.apache.paimon.predicate.PredicateBuilder;
@@ -31,6 +35,8 @@ import org.apache.paimon.schema.FileSystemSchemaManager;
import org.apache.paimon.schema.SchemaChange;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.FileStoreTableFactory;
+import org.apache.paimon.table.sink.CommitMessageImpl;
+import org.apache.paimon.table.sink.TableCommitImpl;
import org.apache.paimon.table.source.RawVectorSearchSplit;
import org.apache.paimon.table.source.VectorScan;
import org.apache.paimon.table.source.VectorSearchBuilder;
@@ -48,10 +54,12 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
+import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Opens Data Evolution tables and centroid manifests written by paimon-rust.
*/
class CentroidTableInteropTest {
@@ -69,27 +77,32 @@ class CentroidTableInteropTest {
Path location = tablePath("centroid_bitmap");
FileStoreTable table = FileStoreTableFactory.create(fileIO, location);
List<IndexFileMeta> files = indexFiles(table, "v", "ivf-flat");
- assertThat(files).hasSize(5);
+ assertThat(files).hasSize(4);
IndexFileMeta emptyRouter =
- files.stream()
- .filter(CentroidIndexMeta::isRoutingModel)
- .filter(file -> file.fileSize() == 0)
- .findFirst()
- .get();
+
files.stream().filter(CentroidIndexMeta::isEmptyRouter).findFirst().get();
assertThat(ByteBuffer.wrap(descriptor(emptyRouter)).getInt(10)).isZero();
assertThat(metric(emptyRouter)).isEqualTo("l2");
- IndexFileMeta emptyShard =
- files.stream()
- .filter(file -> descriptor(file)[9] == 'S' &&
file.rowCount() == 0)
- .findFirst()
- .get();
- assertThat(descriptor(emptyShard)).hasSize(14);
- assertThat(payload(table, emptyShard))
- .isEqualTo("PCEMPTY1".getBytes(StandardCharsets.US_ASCII));
+ assertThat(fileIO.getFileSize(indexPath(table, emptyRouter))).isZero();
+ assertThat(files)
+ .filteredOn(file -> CentroidIndexMeta.isRoutingModel(file) &&
file.fileSize() > 0)
+ .singleElement()
+ .satisfies(
+ file ->
+
assertThat(ByteBuffer.wrap(descriptor(file)).getInt(10))
+ .isEqualTo(2));
+ assertThat(files)
+ .filteredOn(file -> descriptor(file)[9] == 'S')
+ .singleElement()
+ .satisfies(file -> assertThat(file.rowCount()).isEqualTo(4));
IndexFileMeta bitmap =
files.stream().filter(CentroidIndexMeta::isScalarIndex).findFirst().get();
- assertThat(descriptor(bitmap)).hasSize(14);
+ CentroidIndexFile bitmapFile =
+ (CentroidIndexFile)
+ CentroidIndexMeta.file(
+ bitmap,
table.store().pathFactory().globalIndexFileFactory());
+ assertThat(bitmapFile.fieldId()).isEqualTo(2);
+ assertThat(bitmapFile.metadata()).isNotEmpty();
assertThat(bitmap.globalIndexMeta().extraFieldIds()).containsExactly(2);
assertThat(DataEvolutionIndexSourceMeta.fromIndexFile(bitmap).sourceSchemaId())
.isEqualTo(1)
@@ -149,6 +162,29 @@ class CentroidTableInteropTest {
return new Path(warehouse.resolve("test.db").resolve(table).toUri());
}
+ @Test
+ void rejectsCommitsThatOnlyDeleteCentroidShards() throws Exception {
+ FileStoreTable table = FileStoreTableFactory.create(fileIO,
tablePath("centroid_metrics"));
+ List<IndexFileMeta> shards =
+ indexFiles(table, "cos", "ivf-flat").stream()
+ .filter(file ->
!CentroidIndexMeta.isRoutingModel(file))
+ .collect(Collectors.toList());
+ assertThat(shards).isNotEmpty();
+ CommitMessageImpl delete =
+ new CommitMessageImpl(
+ BinaryRow.EMPTY_ROW,
+ 0,
+ null,
+ DataIncrement.deleteIndexIncrement(
+ Collections.singletonList(shards.get(0))),
+ CompactIncrement.emptyIncrement());
+ try (TableCommitImpl commit =
table.newCommit("delete-centroid-shards")) {
+ assertThatThrownBy(() ->
commit.commit(Collections.singletonList(delete)))
+ .hasStackTraceContaining("Cannot partially delete a
centroid index generation");
+ }
+ assertThat(search(table, "cos", null, 1)).containsExactly(0);
+ }
+
private static List<IndexFileMeta> indexFiles(
FileStoreTable table, String column, String type) {
int id = table.rowType().getField(column).id();
diff --git
a/paimon-vector/src/test/java/org/apache/paimon/vector/index/CentroidVectorGlobalIndexTest.java
b/paimon-vector/src/test/java/org/apache/paimon/vector/index/CentroidVectorGlobalIndexTest.java
index 17c191a2ef..f3956a84da 100644
---
a/paimon-vector/src/test/java/org/apache/paimon/vector/index/CentroidVectorGlobalIndexTest.java
+++
b/paimon-vector/src/test/java/org/apache/paimon/vector/index/CentroidVectorGlobalIndexTest.java
@@ -293,7 +293,6 @@ class CentroidVectorGlobalIndexTest {
}
List<GlobalIndexIOMeta> metas = new ArrayList<>();
int[] centroidByRow = new int[256];
- GlobalIndexIOMeta emptyMeta;
try (VectorGlobalModelTrainer trainer =
indexer.createGlobalModelTrainer()) {
for (int i = 0; i < vectors.length; i++) {
trainer.write(vectors[i], BASE + 101L * i);
@@ -320,10 +319,8 @@ class CentroidVectorGlobalIndexTest {
assertThat(empty)
.extracting("tempVectorFile", "spillBuffer")
.containsOnlyNulls();
- ResultEntry result = empty.finish().get(0);
- Path path = new Path(result.filePath());
- emptyMeta = toIOMeta(io, directory,
CentroidIndexMeta.shard(result, 0));
- assertThat(io.getFileSize(path)).isEqualTo(8);
+ assertThat(empty.finish()).isEmpty();
+ assertThat(io.listStatus(directory)).hasSize(1);
} finally {
((Closeable) empty).close();
}
@@ -411,18 +408,23 @@ class CentroidVectorGlobalIndexTest {
};
};
long rowCount = 101L * (vectors.length - 1) + 1;
+ ResultEntry emptyRouterEntry =
+ CentroidIndexMeta.router(
+ indexer.writeRoutingModel(files,
files.newFilePath("routing"), new byte[0]),
+ 0);
+ GlobalIndexIOMeta emptyRouter = toIOMeta(io, directory,
emptyRouterEntry);
try (GlobalIndexReader reader =
new OffsetGlobalIndexReader(
indexer.createReader(fileReader, metas, rowCount,
null, executor),
BASE,
BASE + rowCount - 1)) {
try (GlobalIndexReader empty =
- new NativeVectorGlobalIndexReader(
+ indexer.createReader(
fileReader,
- Collections.singletonList(emptyMeta),
- new ArrayType(new FloatType()),
- executor,
- type)) {
+ Collections.singletonList(emptyRouter),
+ rowCount,
+ null,
+ executor)) {
assertThat(empty.visitVectorSearch(new
VectorSearch(vectors[0], 1, "v")).get())
.isEmpty();
assertThat(
@@ -553,6 +555,29 @@ class CentroidVectorGlobalIndexTest {
}
}
+ GlobalIndexIOMeta farShard = metas.get(1 + centroidByRow[200]);
+ try (GlobalIndexReader sparse =
+ indexer.createReader(
+ fileReader,
+ Arrays.asList(router, farShard),
+ rowCount,
+ null,
+ executor)) {
+ opened.clear();
+ assertThat(
+ sparse.visitVectorSearch(
+ new VectorSearch(vectors[0],
1, "v", search))
+ .get(30, TimeUnit.SECONDS))
+ .isEmpty();
+ assertThat(opened.keySet()).containsExactly(router.filePath());
+ assertThat(
+ sparse.visitVectorSearch(new
VectorSearch(vectors[0], 1, "v"))
+ .get(30, TimeUnit.SECONDS))
+ .isPresent();
+ assertThat(opened.keySet())
+ .containsExactlyInAnyOrder(router.filePath(),
farShard.filePath());
+ }
+
RoaringNavigableMap64 include = new RoaringNavigableMap64();
include.add(BASE - 1);
include.add(BASE + 101L * 200);
@@ -648,12 +673,6 @@ class CentroidVectorGlobalIndexTest {
assertThat(shard.centroid()).isEqualTo(id);
assertThat(ByteBuffer.wrap(shard.metadata()).getInt()).isEqualTo(1);
files.add(shard);
- CentroidIndexFile bitmap = rustFixtureFile("bitmap-" + id, rows);
- assertThat(bitmap.scalarIndex()).isTrue();
- assertThat(bitmap.centroid()).isEqualTo(id);
- assertThat(bitmap.rowCount()).isEqualTo(shard.rowCount());
- bitmaps.put(id, bitmap);
- files.add(bitmap);
}
RowType fields =
@@ -661,6 +680,14 @@ class CentroidVectorGlobalIndexTest {
new DataField(2, "status", DataTypes.INT()),
new DataField(0, "id", DataTypes.INT()));
int[] extraFieldIds = {0, 2};
+ for (int fieldId : extraFieldIds) {
+ CentroidIndexFile bitmap = rustFixtureFile("bitmap-" + fieldId,
rows);
+ assertThat(bitmap.scalarIndex()).isTrue();
+ assertThat(bitmap.fieldId()).isEqualTo(fieldId);
+ assertThat(bitmap.rowCount()).isEqualTo(5);
+ bitmaps.put(fieldId, bitmap);
+ files.add(bitmap);
+ }
PredicateBuilder predicates = new PredicateBuilder(fields);
Predicate filter = PredicateBuilder.or(predicates.equal(1, 2),
predicates.isNull(0));
FileIO io = new LocalFileIO();
@@ -673,14 +700,8 @@ class CentroidVectorGlobalIndexTest {
try (GlobalIndexReader reader = indexer.createReader(input, files, 5,
null, executor)) {
((CentroidShardFilterReader) reader)
.withShardFilter(
- id ->
- CentroidBitmapIndex.match(
- input,
- bitmaps.get(id),
- extraFieldIds,
- fields,
- fields,
- filter));
+ CentroidBitmapIndex.filter(
+ input, bitmaps, fields, fields, filter, 5,
router.nlist()));
OffsetGlobalIndexReader offset = new
OffsetGlobalIndexReader(reader, BASE, BASE + 4);
ScoredGlobalIndexResult result =
offset.visitVectorSearch(
@@ -708,7 +729,7 @@ class CentroidVectorGlobalIndexTest {
}
@Test
- void rejectsMissingShardsBeforeOpeningFiles() {
+ void rejectsIncompleteCentroidGroupsBeforeOpeningFiles() {
CentroidIndexFile router =
new CentroidIndexFile(
new Path("router"),
@@ -719,19 +740,31 @@ class CentroidVectorGlobalIndexTest {
false,
2);
CentroidIndexFile shard =
- new CentroidIndexFile(new Path("shard"), 100, 1, null, false,
false, 0);
+ new CentroidIndexFile(new Path("shard"), 100, 1, null, false,
false, 2);
+ GlobalIndexFileReader input =
+ file -> {
+ throw new AssertionError("Opened an invalid group.");
+ };
assertThatThrownBy(
() ->
new NativeCentroidRoutedIndexReader(
- file -> {
- throw new AssertionError("Opened
an incomplete group.");
- },
+ input,
Arrays.asList(router, shard),
new ArrayType(new FloatType()),
null,
"diskann"))
.isInstanceOf(IllegalArgumentException.class)
- .hasMessageContaining("do not cover all routing centroids");
+ .hasMessageContaining("Invalid shard centroid 2");
+ assertThatThrownBy(
+ () ->
+ new NativeCentroidRoutedIndexReader(
+ input,
+ Collections.singletonList(router),
+ new ArrayType(new FloatType()),
+ null,
+ "diskann"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Centroid routing model has no vector
shards.");
}
@ParameterizedTest
diff --git a/paimon-vector/src/test/resources/centroid-rust-warehouse.zip
b/paimon-vector/src/test/resources/centroid-rust-warehouse.zip
index 1122b2fd42..99ac6fcefd 100644
Binary files a/paimon-vector/src/test/resources/centroid-rust-warehouse.zip and
b/paimon-vector/src/test/resources/centroid-rust-warehouse.zip differ
diff --git a/paimon-vector/src/test/resources/centroid-rust.zip
b/paimon-vector/src/test/resources/centroid-rust.zip
index d94dcfbc73..50d54fe20a 100644
Binary files a/paimon-vector/src/test/resources/centroid-rust.zip and
b/paimon-vector/src/test/resources/centroid-rust.zip differ