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 0f25b7cd8d [spark] Add Bitmap fields to existing centroid vector
indexes (#11396)
0f25b7cd8d is described below
commit 0f25b7cd8d33b62ea8848d6379c46a906c374603
Author: Jingsong Lee <[email protected]>
AuthorDate: Tue Nov 24 20:08:09 2026 +0800
[spark] Add Bitmap fields to existing centroid vector indexes (#11396)
---
.../global-index/centroid-vector.mdx | 10 +-
docs/docs/spark/procedures.md | 1 +
docs/docs/spark/procedures/indexes.md | 25 +
.../globalindex/bitmap/CentroidBitmapIndex.java | 16 +
.../metastore/GlobalIndexVisibilityChecker.java | 49 +-
.../GlobalIndexVisibilityCheckerTest.java | 129 ++++
.../org/apache/paimon/spark/SparkProcedures.java | 2 +
.../globalindex/CentroidBitmapFieldAppender.java | 686 +++++++++++++++++++++
.../CentroidGlobalIndexTopoBuilder.java | 27 +-
.../procedure/AddGlobalIndexFieldsProcedure.java | 141 +++++
.../procedure/CreateGlobalIndexProcedure.java | 4 +-
.../paimon/spark/sql/CentroidKryoBuildTest.scala | 80 ++-
.../paimon/spark/sql/CentroidVectorIndexTest.scala | 240 ++++++-
13 files changed, 1383 insertions(+), 27 deletions(-)
diff --git a/docs/docs/multimodal-table/global-index/centroid-vector.mdx
b/docs/docs/multimodal-table/global-index/centroid-vector.mdx
index 56c256fb04..cc8bebf0f7 100644
--- a/docs/docs/multimodal-table/global-index/centroid-vector.mdx
+++ b/docs/docs/multimodal-table/global-index/centroid-vector.mdx
@@ -227,9 +227,13 @@ exact matches before ranking and skips opening the ANN
file when no visible vect
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.
+Use Spark's
[`sys.add_global_index_fields`](../../spark/procedures/indexes#add_global_index_fields)
+to add scalar columns to existing centroid ranges with Bitmap fields. The
procedure writes the
+new fields' Bitmap files and reuses the existing Bitmap, router, and vector
shard files. To set
+the full list of scalar columns, including the first Bitmap on a vector-only
index, run the
+centroid build with `extra_fields`. For the selected partitions, the build
replaces the indexes
+of the same type on the vector column. Pass the vector column as
`index_column` to
+`sys.drop_global_index` to remove the group.
## Rebuild and Compatibility
diff --git a/docs/docs/spark/procedures.md b/docs/docs/spark/procedures.md
index f0312fbfc4..fde935ac32 100644
--- a/docs/docs/spark/procedures.md
+++ b/docs/docs/spark/procedures.md
@@ -107,6 +107,7 @@ Choose a group, then use the page contents to jump to a
procedure:
[`rewrite_file_index`](./procedures/indexes#rewrite_file_index),
[`create_global_index`](./procedures/indexes#create_global_index),
+[`add_global_index_fields`](./procedures/indexes#add_global_index_fields),
[`drop_global_index`](./procedures/indexes#drop_global_index),
[`reassign_row_id`](./procedures/indexes#reassign_row_id)
diff --git a/docs/docs/spark/procedures/indexes.md
b/docs/docs/spark/procedures/indexes.md
index ea4032bf23..fc30b6f1ad 100644
--- a/docs/docs/spark/procedures/indexes.md
+++ b/docs/docs/spark/procedures/indexes.md
@@ -97,6 +97,31 @@ CALL sys.create_global_index(
);
```
+## add_global_index_fields
+
+Append scalar Bitmap fields to existing [Centroid Vector
indexes](../../multimodal-table/global-index/centroid-vector)
+on a Data Evolution table. Each eligible row-ID range already has Bitmap
fields configured.
+The procedure writes one Bitmap file per new field in each range with vectors
and reuses its
+existing Bitmap, router, and vector shard files.
+It returns `true` on success, including when all requested fields already have
compatible Bitmaps.
+Rebuild the centroid index if a Bitmap being reused was built with a different
field type.
+
+Pass the table identifier in `table`, the vector column in `index_column`, and
the
+existing vector index type in `index_type`. Set `extra_fields` to a JSON object
+mapping existing scalar column names to `bitmap`. Use the optional `partitions`
+argument to select partitions with the same syntax as `create_global_index`.
+At least one selected range must have a centroid index with Bitmap fields.
+
+```sql
+CALL sys.add_global_index_fields(
+ table => 'db.model_embeddings',
+ index_column => 'embedding',
+ index_type => 'ivf-pq',
+ extra_fields => '{"region":"bitmap"}',
+ partitions => 'dt="2026-11-17"'
+);
+```
+
## drop_global_index
Drop global index files for a given column.
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 d5bae31c48..570d11df08 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
@@ -30,6 +30,7 @@ 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;
@@ -54,6 +55,21 @@ public final class CentroidBitmapIndex {
return Math.addExact(Math.multiplyExact(centroid, rowRangeSize),
relativeRowId);
}
+ /** Returns the encoded positions of all vectors in the range, including
null scalar keys. */
+ public static RoaringNavigableMap64 rowIds(
+ GlobalIndexFileReader files, GlobalIndexIOMeta bitmap, DataField
field)
+ throws IOException {
+ try (BitmapIndexReader reader =
+ new BitmapIndexReader(KeySerializer.create(field.type()),
files, bitmap)) {
+ RoaringNavigableMap64 rows = reader.visitIsNull().get().results();
+ rows.or(reader.visitIsNotNull().get().results());
+ checkState(
+ rows.getLongCardinality() == bitmap.rowCount(),
+ "Centroid bitmap does not cover the range's vectors.");
+ return rows;
+ }
+ }
+
public static IOFunction<Integer, RoaringNavigableMap64> filter(
GlobalIndexFileReader files,
Map<Integer, ? extends GlobalIndexIOMeta> bitmaps,
diff --git
a/paimon-core/src/main/java/org/apache/paimon/metastore/GlobalIndexVisibilityChecker.java
b/paimon-core/src/main/java/org/apache/paimon/metastore/GlobalIndexVisibilityChecker.java
index bf34d03c49..1be5242617 100644
---
a/paimon-core/src/main/java/org/apache/paimon/metastore/GlobalIndexVisibilityChecker.java
+++
b/paimon-core/src/main/java/org/apache/paimon/metastore/GlobalIndexVisibilityChecker.java
@@ -20,6 +20,7 @@ package org.apache.paimon.metastore;
import org.apache.paimon.Snapshot;
import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.globalindex.CentroidIndexMeta;
import org.apache.paimon.index.GlobalIndexMeta;
import org.apache.paimon.io.DataFileMeta;
import org.apache.paimon.manifest.FileKind;
@@ -90,11 +91,18 @@ class GlobalIndexVisibilityChecker {
}
GlobalIndexIdentifier identifier = identifierOf(entry);
- if (identifiers.contains(identifier)) {
- indexedRangesByPartition
- .computeIfAbsent(entry.partition().copy(), k -> new
HashMap<>())
- .computeIfAbsent(identifier, k -> new ArrayList<>())
- .add(entry.indexFile().globalIndexMeta().rowRange());
+ Map<GlobalIndexIdentifier, List<Range>> indexed =
+ indexedRangesByPartition.computeIfAbsent(
+ entry.partition().copy(), k -> new HashMap<>());
+ Range range = globalIndex.rowRange();
+ if (identifier.centroidBitmap) {
+ for (GlobalIndexIdentifier required : identifiers) {
+ if (identifier.coversCentroidBitmap(required)) {
+ indexed.computeIfAbsent(required, k -> new
ArrayList<>()).add(range);
+ }
+ }
+ } else if (identifiers.contains(identifier)) {
+ indexed.computeIfAbsent(identifier, k -> new
ArrayList<>()).add(range);
}
}
@@ -171,7 +179,14 @@ class GlobalIndexVisibilityChecker {
FileStoreTable table, Snapshot snapshot) {
return table.store()
.newIndexFileHandler()
- .scan(snapshot, entry -> entry.indexFile().globalIndexMeta()
!= null);
+ .scan(
+ snapshot,
+ entry -> {
+ GlobalIndexMeta meta =
entry.indexFile().globalIndexMeta();
+ return meta != null
+ &&
(!CentroidIndexMeta.hasBitmapFields(meta)
+ ||
CentroidIndexMeta.isRoutingModel(meta.indexMeta()));
+ });
}
private static GlobalIndexIdentifier identifierOf(IndexManifestEntry
entry) {
@@ -179,7 +194,8 @@ class GlobalIndexVisibilityChecker {
return new GlobalIndexIdentifier(
entry.indexFile().indexType(),
globalIndex.indexFieldId(),
- globalIndex.extraFieldIds());
+ globalIndex.extraFieldIds(),
+ CentroidIndexMeta.hasBitmapFields(globalIndex));
}
private static class GlobalIndexIdentifier {
@@ -187,14 +203,28 @@ class GlobalIndexVisibilityChecker {
private final String indexType;
private final int indexFieldId;
private final int[] extraFieldIds;
+ private final boolean centroidBitmap;
- private GlobalIndexIdentifier(String indexType, int indexFieldId,
int[] extraFieldIds) {
+ private GlobalIndexIdentifier(
+ String indexType, int indexFieldId, int[] extraFieldIds,
boolean centroidBitmap) {
this.indexType = indexType;
this.indexFieldId = indexFieldId;
this.extraFieldIds =
extraFieldIds == null
? null
: Arrays.copyOf(extraFieldIds,
extraFieldIds.length);
+ this.centroidBitmap = centroidBitmap;
+ }
+
+ private boolean coversCentroidBitmap(GlobalIndexIdentifier required) {
+ return required.centroidBitmap
+ && indexFieldId == required.indexFieldId
+ && indexType.equals(required.indexType)
+ && Arrays.stream(required.extraFieldIds)
+ .allMatch(
+ field ->
+ Arrays.stream(extraFieldIds)
+ .anyMatch(id -> id ==
field));
}
@Override
@@ -208,13 +238,14 @@ class GlobalIndexVisibilityChecker {
GlobalIndexIdentifier that = (GlobalIndexIdentifier) o;
return indexFieldId == that.indexFieldId
+ && centroidBitmap == that.centroidBitmap
&& Objects.equals(indexType, that.indexType)
&& Arrays.equals(extraFieldIds, that.extraFieldIds);
}
@Override
public int hashCode() {
- int result = Objects.hash(indexType, indexFieldId);
+ int result = Objects.hash(indexType, indexFieldId, centroidBitmap);
result = 31 * result + Arrays.hashCode(extraFieldIds);
return result;
}
diff --git
a/paimon-core/src/test/java/org/apache/paimon/metastore/GlobalIndexVisibilityCheckerTest.java
b/paimon-core/src/test/java/org/apache/paimon/metastore/GlobalIndexVisibilityCheckerTest.java
new file mode 100644
index 0000000000..5fbc22bed8
--- /dev/null
+++
b/paimon-core/src/test/java/org/apache/paimon/metastore/GlobalIndexVisibilityCheckerTest.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.paimon.metastore;
+
+import org.apache.paimon.FileStore;
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.globalindex.CentroidIndexMeta;
+import org.apache.paimon.globalindex.ResultEntry;
+import org.apache.paimon.index.GlobalIndexMeta;
+import org.apache.paimon.index.IndexFileHandler;
+import org.apache.paimon.index.IndexFileMeta;
+import org.apache.paimon.io.DataFileMeta;
+import org.apache.paimon.manifest.FileKind;
+import org.apache.paimon.manifest.FileSource;
+import org.apache.paimon.manifest.IndexManifestEntry;
+import org.apache.paimon.manifest.ManifestEntry;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.utils.Filter;
+import org.apache.paimon.utils.Range;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentMatchers;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/** Visibility checks for global index generations. */
+class GlobalIndexVisibilityCheckerTest {
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void addedCentroidBitmapFieldsPreserveCoverage(boolean centroid) {
+ FileStoreTable table = mock(FileStoreTable.class);
+ FileStore<?> store = mock(FileStore.class);
+ IndexFileHandler files = mock(IndexFileHandler.class);
+ doReturn(store).when(table).store();
+ when(store.newIndexFileHandler()).thenReturn(files);
+
+ Map<Snapshot, List<IndexManifestEntry>> entries = new HashMap<>();
+ when(files.scan(any(Snapshot.class),
ArgumentMatchers.<Filter<IndexManifestEntry>>any()))
+ .thenAnswer(
+ invocation -> {
+ Filter<IndexManifestEntry> filter =
invocation.getArgument(1);
+ return
entries.get(invocation.getArgument(0)).stream()
+ .filter(filter::test)
+ .collect(Collectors.toList());
+ });
+ Snapshot beforeCoverage = snapshot(entries, index(0, 9, centroid, 2));
+ GlobalIndexVisibilityChecker checker =
+ GlobalIndexVisibilityChecker.create(
+ table, beforeCoverage,
Collections.singletonList(appendedRows()));
+ assertThat(checker.noNeedToWait()).isFalse();
+ assertThat(checker.visibleIn(beforeCoverage)).isFalse();
+
+ assertThat(checker.visibleIn(snapshot(entries, index(0, 20, centroid,
2)))).isTrue();
+ assertThat(checker.visibleIn(snapshot(entries, index(0, 20, centroid,
2, 3))))
+ .isEqualTo(centroid);
+ assertThat(checker.visibleIn(snapshot(entries, index(0, 20, centroid,
3)))).isFalse();
+ assertThat(checker.visibleIn(snapshot(entries, index(0, 19, centroid,
2, 3)))).isFalse();
+ }
+
+ private static Snapshot snapshot(
+ Map<Snapshot, List<IndexManifestEntry>> entries,
IndexManifestEntry index) {
+ Snapshot snapshot = mock(Snapshot.class);
+ entries.put(snapshot, Collections.singletonList(index));
+ return snapshot;
+ }
+
+ private static IndexManifestEntry index(
+ long start, long end, boolean centroid, int... extraFields) {
+ byte[] meta =
+ centroid
+ ? CentroidIndexMeta.router(new ResultEntry("index", 0,
null), 0).meta()
+ : null;
+ return new IndexManifestEntry(
+ FileKind.ADD,
+ BinaryRow.EMPTY_ROW,
+ 0,
+ new IndexFileMeta(
+ centroid ? "ivf-flat" : "btree",
+ "index",
+ 0,
+ 0,
+ new GlobalIndexMeta(start, end, 1, extraFields, meta),
+ null));
+ }
+
+ private static ManifestEntry appendedRows() {
+ DataFileMeta file = mock(DataFileMeta.class);
+ when(file.firstRowId()).thenReturn(10L);
+ when(file.rowCount()).thenReturn(11L);
+ when(file.fileSource()).thenReturn(Optional.of(FileSource.APPEND));
+ when(file.fileName()).thenReturn("data.parquet");
+ when(file.nonNullRowIdRange()).thenReturn(new Range(10, 20));
+ ManifestEntry entry = mock(ManifestEntry.class);
+ when(entry.file()).thenReturn(file);
+ when(entry.kind()).thenReturn(FileKind.ADD);
+ when(entry.partition()).thenReturn(BinaryRow.EMPTY_ROW);
+ return entry;
+ }
+}
diff --git
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkProcedures.java
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkProcedures.java
index 41f84711a9..babfb257c9 100644
---
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkProcedures.java
+++
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/SparkProcedures.java
@@ -18,6 +18,7 @@
package org.apache.paimon.spark;
+import org.apache.paimon.spark.procedure.AddGlobalIndexFieldsProcedure;
import org.apache.paimon.spark.procedure.AlterFunctionProcedure;
import org.apache.paimon.spark.procedure.AlterViewDialectProcedure;
import org.apache.paimon.spark.procedure.ClearConsumersProcedure;
@@ -118,6 +119,7 @@ public class SparkProcedures {
procedureBuilders.put("expire_tags", ExpireTagsProcedure::builder);
procedureBuilders.put("create_branch", CreateBranchProcedure::builder);
procedureBuilders.put("create_global_index",
CreateGlobalIndexProcedure::builder);
+ procedureBuilders.put("add_global_index_fields",
AddGlobalIndexFieldsProcedure::builder);
procedureBuilders.put("drop_global_index",
DropGlobalIndexProcedure::builder);
procedureBuilders.put("delete_branch", DeleteBranchProcedure::builder);
procedureBuilders.put("rename_branch", RenameBranchProcedure::builder);
diff --git
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidBitmapFieldAppender.java
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidBitmapFieldAppender.java
new file mode 100644
index 0000000000..3e8ba1ac53
--- /dev/null
+++
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/globalindex/CentroidBitmapFieldAppender.java
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.paimon.spark.globalindex;
+
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.data.serializer.InternalRowSerializer;
+import org.apache.paimon.fs.Path;
+import org.apache.paimon.globalindex.CentroidIndexFile;
+import org.apache.paimon.globalindex.CentroidIndexMeta;
+import org.apache.paimon.globalindex.GlobalIndexBuilderUtils;
+import org.apache.paimon.globalindex.GlobalIndexFileReadWrite;
+import org.apache.paimon.globalindex.GlobalIndexIOMeta;
+import org.apache.paimon.globalindex.IndexedSplit;
+import org.apache.paimon.globalindex.KeySerializer;
+import org.apache.paimon.globalindex.ResultEntry;
+import org.apache.paimon.globalindex.bitmap.CentroidBitmapIndex;
+import org.apache.paimon.index.DataEvolutionIndexSourceMeta;
+import org.apache.paimon.index.GlobalIndexMeta;
+import org.apache.paimon.index.IndexFileMeta;
+import org.apache.paimon.index.IndexPathFactory;
+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.options.Options;
+import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.SpecialFields;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.CommitMessageImpl;
+import org.apache.paimon.table.sink.CommitMessageSerializer;
+import org.apache.paimon.table.source.TableRead;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.CloseableIterator;
+import org.apache.paimon.utils.InstantiationUtil;
+import org.apache.paimon.utils.Pair;
+import org.apache.paimon.utils.ProjectedRow;
+import org.apache.paimon.utils.Range;
+
+import org.apache.paimon.shade.guava30.com.google.common.collect.Iterators;
+import
org.apache.paimon.shade.guava30.com.google.common.collect.PeekingIterator;
+
+import org.apache.spark.HashPartitioner;
+import org.apache.spark.api.java.JavaPairRDD;
+import org.apache.spark.api.java.JavaSparkContext;
+import org.apache.spark.broadcast.Broadcast;
+import org.apache.spark.sql.SparkSession;
+
+import javax.annotation.Nullable;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.io.UncheckedIOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import scala.Tuple2;
+
+import static
org.apache.paimon.spark.globalindex.CentroidGlobalIndexTopoBuilder.closeOnTaskCompletion;
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+import static org.apache.paimon.utils.Preconditions.checkState;
+
+/** Adds Bitmap columns to centroid ranges using their persisted vector
positions. */
+public final class CentroidBitmapFieldAppender {
+
+ private CentroidBitmapFieldAppender() {}
+
+ public static List<CommitMessage> build(
+ SparkSession spark,
+ FileStoreTable table,
+ String indexType,
+ DataField vectorField,
+ List<DataField> requestedFields,
+ @Nullable PartitionPredicate partitionFilter)
+ throws IOException {
+ checkArgument(
+ table.coreOptions().dataEvolutionEnabled(),
+ "Centroid Bitmap fields require a Data Evolution table.");
+ checkArgument(!requestedFields.isEmpty(), "Specify at least one extra
field.");
+ requestedFields.forEach(field -> KeySerializer.create(field.type()));
+
+ Snapshot snapshot = table.snapshotManager().latestSnapshot();
+ List<IndexManifestEntry> entries =
+ snapshot == null
+ ? Collections.emptyList()
+ : table.store()
+ .newIndexFileHandler()
+ .scan(
+ snapshot,
+ entry -> {
+ IndexFileMeta file =
entry.indexFile();
+ GlobalIndexMeta meta =
file.globalIndexMeta();
+ return
indexType.equals(file.indexType())
+ && meta != null
+ && meta.indexFieldId() ==
vectorField.id()
+ &&
CentroidIndexMeta.hasBitmapFields(meta)
+ && (partitionFilter == null
+ ||
partitionFilter.test(
+
entry.partition()));
+ });
+ Map<Pair<BinaryRow, Range>, List<IndexManifestEntry>> groups = new
HashMap<>();
+ for (IndexManifestEntry entry : entries) {
+ groups.computeIfAbsent(
+ Pair.of(
+ entry.partition(),
+
entry.indexFile().globalIndexMeta().rowRange()),
+ ignored -> new ArrayList<>())
+ .add(entry);
+ }
+ checkArgument(
+ !groups.isEmpty(),
+ "No centroid %s index with Bitmap fields on column '%s' in the
selected partitions.",
+ indexType,
+ vectorField.name());
+
+ List<CommitMessage> messages = new ArrayList<>();
+ List<BitmapRange> ranges = new ArrayList<>();
+ int bitmapCount = 0;
+ Set<DataField> projectedFields = new LinkedHashSet<>();
+ Map<Long, RowType> buildSchemas = new HashMap<>();
+ RowType rowType = table.rowType();
+ buildSchemas.put(table.schema().id(), rowType);
+ Map<Integer, DataField> requestedById =
+ requestedFields.stream()
+ .collect(Collectors.toMap(DataField::id,
Function.identity()));
+ long snapshotId = snapshot.id();
+ byte[] sourceMeta =
+ new DataEvolutionIndexSourceMeta(snapshotId,
table.schema().id()).serialize();
+ IndexPathFactory paths =
table.store().pathFactory().globalIndexFileFactory();
+ for (List<IndexManifestEntry> group : groups.values()) {
+ GlobalIndexMeta meta = group.get(0).indexFile().globalIndexMeta();
+ int[] oldFieldIds = meta.extraFieldIds();
+ List<DataField> addedFields =
+ requestedFields.stream()
+ .filter(
+ field ->
+ Arrays.stream(oldFieldIds)
+ .noneMatch(id -> id ==
field.id()))
+ .collect(Collectors.toList());
+ if (addedFields.isEmpty()) {
+ for (IndexManifestEntry entry : group) {
+ IndexFileMeta file = entry.indexFile();
+ if (!CentroidIndexMeta.isScalarIndex(file)) {
+ continue;
+ }
+ CentroidIndexFile bitmap =
+ (CentroidIndexFile) CentroidIndexMeta.file(file,
paths);
+ DataField field = requestedById.get(bitmap.fieldId());
+ if (field != null) {
+ checkBitmapFieldType(table, buildSchemas, file, field);
+ }
+ }
+ continue;
+ }
+ checkArgument(
+ table.coreOptions().globalIndexColumnUpdateAction()
+ !=
CoreOptions.GlobalIndexColumnUpdateAction.IGNORE,
+ "Centroid Bitmap fields require THROW_ERROR or
DROP_PARTITION_INDEX.");
+
+ List<DataField> fields = new ArrayList<>();
+ fields.add(vectorField);
+ for (int id : oldFieldIds) {
+ checkArgument(
+ rowType.containsField(id),
+ "Existing Bitmap field ID %s is missing. Rebuild the
centroid index.",
+ id);
+ fields.add(rowType.getField(id));
+ }
+ fields.addAll(addedFields);
+ int[] extraFieldIds =
fields.stream().skip(1).mapToInt(DataField::id).toArray();
+ List<IndexFileMeta> replaced = new ArrayList<>(group.size());
+ List<IndexFileMeta> retained = new ArrayList<>(group.size());
+ Map<Integer, CentroidIndexFile> bitmaps = new HashMap<>();
+ long vectorCount = 0;
+ long bitmapSchemaId = -1;
+ int nlist = -1;
+ for (IndexManifestEntry entry : group) {
+ IndexFileMeta file = entry.indexFile();
+ GlobalIndexMeta current = file.globalIndexMeta();
+ checkState(
+ Arrays.equals(oldFieldIds, current.extraFieldIds()),
+ "Mixed centroid Bitmap fields.");
+ replaced.add(file);
+ CentroidIndexFile descriptor =
+ (CentroidIndexFile) CentroidIndexMeta.file(file,
paths);
+ if (descriptor.routingModel()) {
+ checkState(nlist == -1, "Duplicate centroid router.");
+ nlist = descriptor.nlist();
+ } else if (descriptor.scalarIndex()) {
+ int fieldId = descriptor.fieldId();
+ checkState(
+ Arrays.stream(oldFieldIds).anyMatch(id -> id ==
fieldId)
+ && bitmaps.put(fieldId, descriptor) ==
null,
+ "Unexpected centroid Bitmap file for field %s.",
+ fieldId);
+ long schemaId =
+ checkBitmapFieldType(
+ table, buildSchemas, file,
rowType.getField(fieldId));
+ checkState(
+ bitmapSchemaId == -1 || bitmapSchemaId == schemaId,
+ "Mixed centroid Bitmap schemas.");
+ bitmapSchemaId = schemaId;
+ } else {
+ vectorCount = Math.addExact(vectorCount, file.rowCount());
+ }
+ retained.add(
+ new IndexFileMeta(
+ file.indexType(),
+ file.fileName(),
+ file.fileSize(),
+ file.rowCount(),
+ new GlobalIndexMeta(
+ current.rowRangeStart(),
+ current.rowRangeEnd(),
+ current.indexFieldId(),
+ extraFieldIds,
+ current.indexMeta(),
+ sourceMeta),
+ file.externalPath()));
+ }
+ IndexManifestEntry first = group.get(0);
+ checkState(nlist >= 0, "Missing centroid routing model.");
+ if (vectorCount == 0) {
+ checkState(bitmaps.isEmpty(), "Unexpected Bitmap for an empty
centroid range.");
+ } else {
+ checkState(
+ nlist > 0 && bitmaps.size() == oldFieldIds.length,
+ "Centroid Bitmap files do not cover the range's
fields.");
+ for (CentroidIndexFile bitmap : bitmaps.values()) {
+ checkState(
+ bitmap.rowCount() == vectorCount,
+ "Centroid Bitmap row count differs from the total
vector count.");
+ }
+ ranges.add(
+ new BitmapRange(
+ first,
+ bitmaps.get(oldFieldIds[0]),
+ fields,
+ oldFieldIds.length,
+ nlist,
+ bitmapCount));
+ bitmapCount += addedFields.size();
+ projectedFields.addAll(addedFields);
+ }
+ messages.add(
+ message(first.partition(), first.bucket(), retained,
replaced, snapshotId));
+ }
+
+ if (!ranges.isEmpty()) {
+ List<ManifestEntry> dataFiles =
+ table.store()
+ .newScan()
+ .withSnapshot(snapshot)
+ .withPartitionFilter(partitionFilter)
+ .plan()
+ .files();
+ List<Range> indexedRanges =
+ ranges.stream()
+ .map(range -> range.range)
+ .distinct()
+ .collect(Collectors.toList());
+ Options options = new Options(table.options());
+ List<IndexedSplit> splits =
+ GlobalIndexBuilderUtils.createShardIndexedSplits(
+ table,
+ dataFiles,
+
DefaultGlobalIndexTopoBuilder.rowsPerShard(options),
+ indexedRanges);
+ messages.addAll(
+ writeBitmaps(
+ spark,
+ table,
+ options,
+ snapshotId,
+ sourceMeta,
+ ranges,
+ bitmapCount,
+ splits,
+ new RowType(new ArrayList<>(projectedFields))));
+ }
+ return messages;
+ }
+
+ private static long checkBitmapFieldType(
+ FileStoreTable table,
+ Map<Long, RowType> buildSchemas,
+ IndexFileMeta file,
+ DataField field) {
+ long schemaId =
DataEvolutionIndexSourceMeta.fromIndexFile(file).sourceSchemaId();
+ checkState(schemaId >= 0, "Missing centroid Bitmap build schema.");
+ RowType buildType =
+ buildSchemas.computeIfAbsent(
+ schemaId, id ->
table.schemaManager().schema(id).logicalRowType());
+ checkArgument(
+ buildType.containsField(field.id())
+ &&
field.type().equalsIgnoreNullable(buildType.getField(field.id()).type()),
+ "Bitmap field '%s' has changed type. Rebuild the centroid
index.",
+ field.name());
+ return schemaId;
+ }
+
+ private static List<CommitMessage> writeBitmaps(
+ SparkSession spark,
+ FileStoreTable table,
+ Options options,
+ long snapshotId,
+ byte[] sourceMeta,
+ List<BitmapRange> ranges,
+ int bitmapCount,
+ List<IndexedSplit> splits,
+ RowType keyType)
+ throws IOException {
+ checkState(!splits.isEmpty(), "No source rows for centroid Bitmap
fields.");
+ JavaSparkContext sc = new JavaSparkContext(spark.sparkContext());
+ int writeTasks =
DefaultGlobalIndexTopoBuilder.parallelism(bitmapCount, options);
+ int readTasks =
DefaultGlobalIndexTopoBuilder.parallelism(splits.size(), options);
+ List<byte[]> splitBytes = new ArrayList<>(splits.size());
+ for (IndexedSplit split : splits) {
+ splitBytes.add(InstantiationUtil.serializeObject(split));
+ }
+ List<Integer> ordinals =
+ IntStream.range(0,
ranges.size()).boxed().collect(Collectors.toList());
+ int[] outputRanges = new int[bitmapCount];
+ int[] rangeOutputOffsets = new int[ranges.size() + 1];
+ int[] outputFieldPositions = new int[bitmapCount];
+ for (int i = 0; i < ranges.size(); i++) {
+ BitmapRange range = ranges.get(i);
+ int outputId = range.firstOutputId;
+ rangeOutputOffsets[i] = outputId;
+ for (DataField field : range.addedFields()) {
+ outputRanges[outputId] = i;
+ outputFieldPositions[outputId] =
keyType.getFieldIndex(field.name());
+ outputId++;
+ }
+ }
+ rangeOutputOffsets[ranges.size()] = bitmapCount;
+ Broadcast<Tuple2<byte[], int[]>> rangePlans =
sc.broadcast(serializeRanges(ranges));
+ try {
+ JavaPairRDD<Long, Tuple2<Integer, Long>> membership =
+ sc.parallelize(ordinals, Math.min(writeTasks,
ranges.size()))
+ .mapPartitionsToPair(
+ ids -> {
+ Tuple2<byte[], int[]> plans =
rangePlans.value();
+ GlobalIndexFileReadWrite files =
indexFiles(table);
+ return Iterators.concat(
+ Iterators.transform(
+ ids,
+ id ->
+
rangePlan(plans, id)
+
.rows(files, id)));
+ });
+ JavaPairRDD<Long, byte[]> values =
+ sc.parallelize(splitBytes, readTasks)
+ .mapPartitionsToPair(ids -> new ScalarRows(table,
keyType, ids));
+
+ // Read each source split once and repartition its values by
Bitmap output file.
+ JavaPairRDD<Integer, Tuple2<Long, byte[]>> rowsByBitmap =
+ values.join(membership, Math.max(writeTasks, readTasks))
+ .mapPartitionsToPair(
+ rows ->
+ bitmapValues(
+ keyType,
+ rangeOutputOffsets,
+ outputFieldPositions,
+ rows));
+ List<byte[]> outputs =
+ rowsByBitmap
+ .repartitionAndSortWithinPartitions(new
HashPartitioner(writeTasks))
+ .mapPartitions(
+ rows -> {
+ Tuple2<byte[], int[]> plans =
rangePlans.value();
+ GlobalIndexFileReadWrite files =
indexFiles(table);
+ PeekingIterator<Tuple2<Integer,
Tuple2<Long, byte[]>>>
+ input =
Iterators.peekingIterator(rows);
+ List<byte[]> finished = new
ArrayList<>();
+ while (input.hasNext()) {
+ int id = input.peek()._1();
+ finished.add(
+ rangePlan(plans,
outputRanges[id])
+ .write(
+ table,
+ files,
+ id,
+ input,
+ snapshotId,
+
sourceMeta));
+ }
+ return finished.iterator();
+ })
+ .collect();
+ checkState(outputs.size() == bitmapCount, "Missing source rows for
a centroid Bitmap.");
+ return CommitMessageSerializer.deserializeAll(outputs);
+ } finally {
+ rangePlans.destroy();
+ }
+ }
+
+ private static Iterator<Tuple2<Integer, Tuple2<Long, byte[]>>>
bitmapValues(
+ RowType keyType,
+ int[] rangeOutputOffsets,
+ int[] outputFieldPositions,
+ Iterator<Tuple2<Long, Tuple2<byte[], Tuple2<Integer, Long>>>>
rows) {
+ InternalRowSerializer rowSerializer = new
InternalRowSerializer(keyType);
+ DataInputDeserializer input = new DataInputDeserializer();
+ InternalRow.FieldGetter[] getters = new
InternalRow.FieldGetter[keyType.getFieldCount()];
+ KeySerializer[] serializers = new
KeySerializer[keyType.getFieldCount()];
+ for (int i = 0; i < getters.length; i++) {
+ getters[i] = InternalRow.createFieldGetter(keyType.getTypeAt(i),
i);
+ serializers[i] = KeySerializer.create(keyType.getTypeAt(i));
+ }
+ return Iterators.concat(
+ Iterators.transform(
+ rows,
+ row -> {
+ Tuple2<Integer, Long> position = row._2()._2();
+ int rangeId = position._1();
+ int from = rangeOutputOffsets[rangeId];
+ int to = rangeOutputOffsets[rangeId + 1];
+ List<Tuple2<Integer, Tuple2<Long, byte[]>>> values
=
+ new ArrayList<>(to - from);
+ input.setBuffer(row._2()._1());
+ InternalRow keys;
+ try {
+ keys = rowSerializer.deserialize(input);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ for (int outputId = from; outputId < to;
outputId++) {
+ int column = outputFieldPositions[outputId];
+ Object value =
getters[column].getFieldOrNull(keys);
+ byte[] bytes =
+ value == null ? null :
serializers[column].serialize(value);
+ values.add(
+ new Tuple2<>(outputId, new
Tuple2<>(position._2(), bytes)));
+ }
+ return values.iterator();
+ }));
+ }
+
+ private static CommitMessage message(
+ BinaryRow partition,
+ int bucket,
+ List<IndexFileMeta> added,
+ List<IndexFileMeta> deleted,
+ long snapshotId) {
+ return new CommitMessageImpl(
+ partition,
+ bucket,
+ null,
+ new DataIncrement(
+ Collections.emptyList(),
+ Collections.emptyList(),
+ Collections.emptyList(),
+ added,
+ deleted),
+ CompactIncrement.emptyIncrement())
+ .withCheckFromSnapshot(snapshotId);
+ }
+
+ private static GlobalIndexFileReadWrite indexFiles(FileStoreTable table) {
+ return new GlobalIndexFileReadWrite(
+ table.fileIO(),
table.store().pathFactory().globalIndexFileFactory());
+ }
+
+ private static Tuple2<byte[], int[]> serializeRanges(List<BitmapRange>
ranges)
+ throws IOException {
+ ByteArrayOutputStream payload = new ByteArrayOutputStream();
+ int[] offsets = new int[ranges.size() + 1];
+ for (int i = 0; i < ranges.size(); i++) {
+ payload.write(InstantiationUtil.serializeObject(ranges.get(i)));
+ offsets[i + 1] = payload.size();
+ }
+ return new Tuple2<>(payload.toByteArray(), offsets);
+ }
+
+ private static BitmapRange rangePlan(Tuple2<byte[], int[]> plans, int id) {
+ int[] offsets = plans._2();
+ try {
+ return InstantiationUtil.deserializeObject(
+ new ByteArrayInputStream(
+ plans._1(), offsets[id], offsets[id + 1] -
offsets[id]),
+ CentroidBitmapFieldAppender.class.getClassLoader());
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Cannot deserialize centroid
Bitmap range plan.", e);
+ }
+ }
+
+ private static <T> T deserialize(byte[] bytes) throws IOException,
ClassNotFoundException {
+ return InstantiationUtil.deserializeObject(
+ bytes, CentroidBitmapFieldAppender.class.getClassLoader());
+ }
+
+ private static final class BitmapRange implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final BinaryRow partition;
+ private final int bucket;
+ private final Range range;
+ private final String indexType;
+ private final int nlist;
+ private final Path path;
+ private final long fileSize;
+ private final long rowCount;
+ private final byte[] bitmapMetadata;
+ private final List<DataField> fields;
+ private final int oldFieldCount;
+ private final int firstOutputId;
+
+ private BitmapRange(
+ IndexManifestEntry entry,
+ CentroidIndexFile descriptor,
+ List<DataField> fields,
+ int oldFieldCount,
+ int nlist,
+ int firstOutputId) {
+ this.partition = entry.partition();
+ this.bucket = entry.bucket();
+ this.range = entry.indexFile().globalIndexMeta().rowRange();
+ this.indexType = entry.indexFile().indexType();
+ this.nlist = nlist;
+ this.path = descriptor.filePath();
+ this.fileSize = descriptor.fileSize();
+ this.rowCount = descriptor.rowCount();
+ this.bitmapMetadata = descriptor.metadata();
+ this.fields = fields;
+ this.oldFieldCount = oldFieldCount;
+ this.firstOutputId = firstOutputId;
+ }
+
+ private List<DataField> addedFields() {
+ return fields.subList(oldFieldCount + 1, fields.size());
+ }
+
+ private Iterator<Tuple2<Long, Tuple2<Integer, Long>>> rows(
+ GlobalIndexFileReadWrite files, int id) {
+ GlobalIndexIOMeta bitmap =
+ new GlobalIndexIOMeta(path, fileSize, rowCount,
bitmapMetadata);
+ long rangeSize = range.count();
+ try {
+ return Iterators.transform(
+ CentroidBitmapIndex.rowIds(files, bitmap,
fields.get(1)).iterator(),
+ encoded -> {
+ checkState(
+ encoded >= 0 && encoded / rangeSize <
nlist,
+ "Invalid centroid Bitmap position: %s.",
+ encoded);
+ long rowId = range.from + encoded % rangeSize;
+ return new Tuple2<>(rowId, new Tuple2<>(id,
encoded));
+ });
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ private byte[] write(
+ FileStoreTable table,
+ GlobalIndexFileReadWrite files,
+ int id,
+ PeekingIterator<Tuple2<Integer, Tuple2<Long, byte[]>>> rows,
+ long snapshotId,
+ byte[] sourceMeta)
+ throws Exception {
+ DataField field = addedFields().get(id - firstOutputId);
+ List<ResultEntry> entries =
+ CentroidGlobalIndexTopoBuilder.writeBitmap(
+ table.coreOptions(), files, rows, id, field,
Function.identity());
+ checkState(
+ entries.size() == 1 && entries.get(0).rowCount() ==
rowCount,
+ "Source rows do not cover the centroid Bitmap for field
'%s'.",
+ field.name());
+ List<IndexFileMeta> added =
+ GlobalIndexBuilderUtils.toIndexFileMetas(
+ table.fileIO(),
+ table.coreOptions(),
+ range,
+ fields,
+ indexType,
+ entries,
+ sourceMeta);
+ return new CommitMessageSerializer()
+ .serialize(
+ message(partition, bucket, added,
Collections.emptyList(), snapshotId));
+ }
+ }
+
+ private static final class ScalarRows implements Iterator<Tuple2<Long,
byte[]>>, AutoCloseable {
+
+ private final Iterator<byte[]> splits;
+ private final TableRead read;
+ private final int rowIdPosition;
+ private final ProjectedRow keys;
+ private final InternalRowSerializer serializer;
+ private final DataOutputSerializer output = new
DataOutputSerializer(128);
+
+ private CloseableIterator<InternalRow> rows =
CloseableIterator.empty();
+
+ private ScalarRows(FileStoreTable table, RowType keyType,
Iterator<byte[]> splits) {
+ this.splits = splits;
+ this.read =
+ table.newReadBuilder()
+
.withReadType(SpecialFields.rowTypeWithRowId(keyType))
+ .newRead();
+ this.rowIdPosition = keyType.getFieldCount();
+ this.keys = ProjectedRow.from(IntStream.range(0,
rowIdPosition).toArray());
+ this.serializer = new InternalRowSerializer(keyType);
+ closeOnTaskCompletion(this);
+ }
+
+ @Override
+ public boolean hasNext() {
+ try {
+ while (!rows.hasNext()) {
+ close();
+ if (!splits.hasNext()) {
+ return false;
+ }
+ IndexedSplit split = deserialize(splits.next());
+ rows = read.createReader(split).toCloseableIterator();
+ }
+ return true;
+ } catch (Exception e) {
+ throw new RuntimeException("Cannot read centroid Bitmap source
rows.", e);
+ }
+ }
+
+ @Override
+ public Tuple2<Long, byte[]> next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ InternalRow row = rows.next();
+ try {
+ output.clear();
+ serializer.serialize(keys.replaceRow(row), output);
+ return new Tuple2<>(row.getLong(rowIdPosition),
output.getCopyOfBuffer());
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ CloseableIterator<InternalRow> current = rows;
+ rows = CloseableIterator.empty();
+ current.close();
+ }
+ }
+}
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 52b50f5e1c..01c5e221c3 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
@@ -94,6 +94,7 @@ import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
+import java.util.function.Function;
import java.util.stream.Collectors;
import scala.Tuple2;
@@ -504,7 +505,7 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
}));
}
- private static void closeOnTaskCompletion(AutoCloseable resource) {
+ static void closeOnTaskCompletion(AutoCloseable resource) {
TaskContext.get()
.addTaskCompletionListener(
(TaskCompletionListener)
@@ -530,7 +531,15 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
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)));
+ commits.add(
+ context.finish(
+ writeBitmap(
+ new CoreOptions(context.options),
+ io,
+ input,
+ key,
+ field,
+ Tuple2::_2)));
}
while (input.hasNext()) {
int centroid = input.peek()._1();
@@ -552,14 +561,14 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
return commits.iterator();
}
- private static List<ResultEntry> writeBitmap(
- BuildContext context,
+ static <T> List<ResultEntry> writeBitmap(
+ CoreOptions options,
GlobalIndexFileReadWrite files,
- PeekingIterator<Tuple2<Integer, Tuple2<Long, Tuple2<float[],
byte[]>>>> input,
+ PeekingIterator<Tuple2<Integer, Tuple2<Long, T>>> input,
int key,
- DataField field)
+ DataField field,
+ Function<T, byte[]> encodedValue)
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 =
@@ -574,8 +583,8 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
options.writeBufferSpillDiskSize());
try {
while (input.hasNext() && input.peek()._1() == key) {
- Tuple2<Long, Tuple2<float[], byte[]>> row =
input.next()._2();
- byte[] bytes = row._2()._2();
+ Tuple2<Long, T> row = input.next()._2();
+ byte[] bytes = encodedValue.apply(row._2());
Object value =
bytes == null ? null :
serializer.deserialize(MemorySlice.wrap(bytes));
checkArgument(
diff --git
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/AddGlobalIndexFieldsProcedure.java
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/AddGlobalIndexFieldsProcedure.java
new file mode 100644
index 0000000000..546b094233
--- /dev/null
+++
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/AddGlobalIndexFieldsProcedure.java
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.paimon.spark.procedure;
+
+import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.spark.globalindex.CentroidBitmapFieldAppender;
+import org.apache.paimon.spark.utils.SparkProcedureUtils;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.CommitMessage;
+import org.apache.paimon.table.sink.TableCommitImpl;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.RowType;
+
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.Identifier;
+import org.apache.spark.sql.connector.catalog.TableCatalog;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Metadata;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+
+import java.util.List;
+import java.util.Locale;
+import java.util.UUID;
+
+import static
org.apache.paimon.spark.procedure.CreateGlobalIndexProcedure.parseExtraFields;
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+import static org.apache.spark.sql.types.DataTypes.StringType;
+
+/** Appends Bitmap filter fields to existing centroid vector indexes. */
+public class AddGlobalIndexFieldsProcedure extends BaseProcedure {
+
+ private static final ProcedureParameter[] PARAMETERS = {
+ ProcedureParameter.required("table", StringType),
+ ProcedureParameter.required("index_column", StringType),
+ ProcedureParameter.required("index_type", StringType),
+ ProcedureParameter.required("extra_fields", StringType),
+ ProcedureParameter.optional("partitions", StringType)
+ };
+
+ private static final StructType OUTPUT_TYPE =
+ new StructType(
+ new StructField[] {
+ new StructField("result", DataTypes.BooleanType, true,
Metadata.empty())
+ });
+
+ protected AddGlobalIndexFieldsProcedure(TableCatalog tableCatalog) {
+ super(tableCatalog);
+ }
+
+ @Override
+ public ProcedureParameter[] parameters() {
+ return PARAMETERS;
+ }
+
+ @Override
+ public StructType outputType() {
+ return OUTPUT_TYPE;
+ }
+
+ @Override
+ public String description() {
+ return "Add Bitmap fields to existing centroid vector indexes.";
+ }
+
+ @Override
+ public InternalRow[] call(InternalRow args) {
+ Identifier identifier = toIdentifier(args.getString(0),
PARAMETERS[0].name());
+ String column = args.getString(1);
+ String indexType = args.getString(2).toLowerCase(Locale.ROOT).trim();
+ checkArgument(!args.isNullAt(3), "Specify the extra_fields to add.");
+ String extraFields = args.getString(3);
+ String partitions = args.isNullAt(4) ? null : args.getString(4);
+
+ return modifySparkTableRefreshingCacheOnFailure(
+ identifier,
+ sparkTable -> {
+ org.apache.paimon.table.Table t = sparkTable.getTable();
+ checkArgument(t instanceof FileStoreTable, "Expected a
FileStoreTable.");
+ FileStoreTable table = (FileStoreTable) t;
+ RowType rowType = table.rowType();
+ checkArgument(
+ rowType.containsField(column), "Column '%s' does
not exist.", column);
+ DataField vectorField = rowType.getField(column);
+ PartitionPredicate partitionFilter =
+
SparkProcedureUtils.convertPartitionsToPartitionPredicate(
+ partitions, table, spark());
+ try {
+ List<DataField> fields =
+ parseExtraFields(extraFields, rowType,
vectorField);
+ List<CommitMessage> messages =
+ CentroidBitmapFieldAppender.build(
+ spark(),
+ table,
+ indexType,
+ vectorField,
+ fields,
+ partitionFilter);
+ if (!messages.isEmpty()) {
+ try (TableCommitImpl commit =
+ table.newCommit(
+ "global-index-add-fields-" +
UUID.randomUUID())) {
+ commit.commit(messages);
+ }
+ }
+ return new InternalRow[] {newInternalRow(true)};
+ } catch (Exception e) {
+ throw new RuntimeException(
+ String.format(
+ "Failed to add fields to %s index on
column '%s' in table '%s'.",
+ indexType, column, identifier),
+ e);
+ }
+ });
+ }
+
+ public static ProcedureBuilder builder() {
+ return new BaseProcedure.Builder<AddGlobalIndexFieldsProcedure>() {
+ @Override
+ public AddGlobalIndexFieldsProcedure doBuild() {
+ return new AddGlobalIndexFieldsProcedure(tableCatalog());
+ }
+ };
+ }
+}
diff --git
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CreateGlobalIndexProcedure.java
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CreateGlobalIndexProcedure.java
index 0fbf071378..b747fae063 100644
---
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CreateGlobalIndexProcedure.java
+++
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/CreateGlobalIndexProcedure.java
@@ -116,8 +116,8 @@ public class CreateGlobalIndexProcedure extends
BaseProcedure {
return new Options(tableOptions, parsedOptions);
}
- private static List<DataField> parseExtraFields(
- String json, RowType rowType, DataField vectorField) throws
IOException {
+ static List<DataField> parseExtraFields(String json, RowType rowType,
DataField vectorField)
+ throws IOException {
JsonNode fields =
JsonSerdeUtil.OBJECT_MAPPER_INSTANCE
.reader()
diff --git
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidKryoBuildTest.scala
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidKryoBuildTest.scala
index 334690cfb0..b4a009f9b9 100644
---
a/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidKryoBuildTest.scala
+++
b/paimon-spark/paimon-spark-ut/src/test/scala/org/apache/paimon/spark/sql/CentroidKryoBuildTest.scala
@@ -18,7 +18,7 @@
package org.apache.paimon.spark.sql
-import org.apache.paimon.data.{GenericArray, GenericRow}
+import org.apache.paimon.data.{BinaryString, GenericArray, GenericRow}
import org.apache.paimon.predicate.PredicateBuilder
import org.apache.paimon.spark.PaimonSparkTestBase
@@ -33,7 +33,7 @@ class CentroidKryoBuildTest extends PaimonSparkTestBase {
test("centroid sampling and shuffle work with strict Kryo registration") {
withTable("T") {
- spark.sql("""CREATE TABLE T (v ARRAY<FLOAT>, tag INT) TBLPROPERTIES (
+ spark.sql("""CREATE TABLE T (v ARRAY<FLOAT>, tag INT, rank INT)
TBLPROPERTIES (
|'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true',
|'global-index.row-count-per-shard'='8')""".stripMargin)
val table = loadTable("T")
@@ -42,7 +42,9 @@ class CentroidKryoBuildTest extends PaimonSparkTestBase {
val commit = builder.newCommit()
try {
(0 until 32).foreach(
- i => write.write(GenericRow.of(new GenericArray(Array(i.toFloat,
1f)), Int.box(i))))
+ i =>
+ write.write(
+ GenericRow.of(new GenericArray(Array(i.toFloat, 1f)),
Int.box(i), Int.box(32 - i))))
commit.commit(write.prepareCommit())
} finally {
write.close()
@@ -72,6 +74,78 @@ class CentroidKryoBuildTest extends PaimonSparkTestBase {
.withFilter(new PredicateBuilder(table.rowType()).equal(1, Int.box(7)))
.executeLocal()
assert(filtered.results().toArray(1).toSeq == Seq(7L))
+ spark.sql("""CALL sys.add_global_index_fields(table=>'test.T',
index_column=>'v',
+ |index_type=>'ivf-flat',
extra_fields=>'{"rank":"bitmap"}')""".stripMargin)
+ val appended = table
+ .newVectorSearchBuilder()
+ .withVectorColumn("v")
+ .withVector(Array(0f, 1f))
+ .withLimit(1)
+ .withFilter(new PredicateBuilder(table.rowType()).equal(2,
Int.box(25)))
+ .executeLocal()
+ assert(appended.results().toArray(1).toSeq == Seq(7L))
+ }
+ }
+
+ test("route appended fields for ranges with different existing Bitmap
fields") {
+ withTable("T") {
+ spark.sql(
+ """CREATE TABLE T (id INT, v ARRAY<FLOAT>, tenant INT, status STRING,
priority INT, p INT)
+ |PARTITIONED BY (p) TBLPROPERTIES (
+ |'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true',
+ |'vector-index.search-mode'='fast',
'vector-index.post-filter.candidates-factor'='1')""".stripMargin)
+ val builder = loadTable("T").newBatchWriteBuilder()
+ val write = builder.newWrite()
+ val commit = builder.newCommit()
+ try {
+ Seq(
+ (10, 0f, 1, "pending", Int.box(0), 0),
+ (11, 8f, 1, "ready", Int.box(7), 0),
+ (20, 0f, 2, "pending", Int.box(0), 1),
+ (21, 9f, 2, "ready", null, 1)).foreach {
+ case (id, x, tenant, status, priority, partition) =>
+ write.write(
+ GenericRow.of(
+ Int.box(id),
+ new GenericArray(Array(x, 0f)),
+ Int.box(tenant),
+ BinaryString.fromString(status),
+ priority,
+ Int.box(partition)))
+ }
+ commit.commit(write.prepareCommit())
+ } finally {
+ write.close()
+ commit.close()
+ }
+
+ def build(partition: Int, fields: String): Unit = {
+ spark
+ .sql(
+ s"""CALL sys.create_global_index(table=>'test.T',
index_column=>'v',
+ |index_type=>'ivf-flat', extra_fields=>'$fields',
partitions=>'p=$partition',
+
|options=>'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.metric=l2,ivf-flat.centroid.nlist=1')""".stripMargin)
+ .collect()
+ }
+ build(0, """{"tenant":"bitmap"}""")
+ build(1, """{"tenant":"bitmap","status":"bitmap"}""")
+ assert(
+ spark
+ .sql("""CALL sys.add_global_index_fields(table=>'test.T',
index_column=>'v', index_type=>'ivf-flat',
+
|extra_fields=>'{"status":"bitmap","priority":"bitmap"}')""".stripMargin)
+ .head()
+ .getBoolean(0))
+
+ def nearest(partition: Int, predicate: String): Seq[Int] =
+ spark
+ .sql(s"""SELECT id FROM vector_search('T', 'v', array(0.0f, 0.0f), 1)
+ |WHERE p = $partition AND $predicate""".stripMargin)
+ .collect()
+ .map(_.getInt(0))
+ .toSeq
+
+ assert(nearest(0, "status = 'ready' AND priority = 7") == Seq(11))
+ assert(nearest(1, "status = 'ready' AND priority IS NULL") == Seq(21))
}
}
}
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 465fc520e9..79efb0bb00 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
@@ -21,11 +21,16 @@ package org.apache.paimon.spark.sql
import org.apache.paimon.append.dataevolution.DataEvolutionRowIdReassigner
import org.apache.paimon.globalindex.{CentroidIndexFile, CentroidIndexMeta}
import org.apache.paimon.index.IndexFileMeta
+import org.apache.paimon.manifest.ManifestCommittable
+import org.apache.paimon.predicate.PredicateBuilder
import org.apache.paimon.spark.PaimonSparkTestBase
-import org.apache.paimon.table.source.RawVectorSearchSplit
+import org.apache.paimon.spark.globalindex.CentroidBitmapFieldAppender
+import org.apache.paimon.table.sink.CommitCallback
+import org.apache.paimon.table.source.{RawVectorSearchSplit,
VectorSearchBuilderImpl}
import org.apache.paimon.vector.index.VectorTrainingModelIO
import org.apache.commons.io.FileUtils
+import org.apache.spark.sql.Row
import java.io.File
import java.nio.ByteBuffer
@@ -36,6 +41,8 @@ import scala.collection.JavaConverters._
/** End-to-end centroid build over nonzero, disjoint source row-ID ranges. */
class CentroidVectorIndexTest extends PaimonSparkTestBase {
+ private def runSql(statement: String): Seq[Row] =
spark.sql(statement).collect().toSeq
+
test("centroid interchange tables omit empty shards and carry canonical
metrics") {
val bitmapTable = "centroid_bitmap"
val metricsTable = "centroid_metrics"
@@ -279,6 +286,224 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase
{
}
}
+ test("add_global_index_fields extends centroid Bitmaps in the selected
partition") {
+ withTable("T") {
+ spark.sql("""CREATE TABLE T (id INT, v ARRAY<FLOAT>, tenant STRING,
priority INT, p INT)
+ |PARTITIONED BY (p) TBLPROPERTIES (
+ |'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true',
+ |'deletion-vectors.enabled'='true',
'vector-index.search-mode'='fast',
+
|'vector-index.post-filter.candidates-factor'='1')""".stripMargin)
+ spark.sql("INSERT INTO T VALUES (1, array(0.0f, 0.0f), 'bulk', 0, 0)")
+ spark.sql("""INSERT INTO T VALUES
+ |(10, array(0.0f, 0.0f), 'bulk', 0, 1),
+ |(11, array(101.0f, 0.0f), 'legacy', 7, 1),
+ |(12, array(20.0f, 0.0f), NULL, 0, 1),
+ |(13, NULL, 'legacy', 7, 1),
+ |(14, array(1.0f, 0.0f), 'bulk', 0, 1),
+ |(15, array(200.0f, 0.0f), 'bulk', 0, 1)""".stripMargin)
+ spark.sql("INSERT INTO T VALUES (2, array(1.0f, 0.0f), 'bulk', 0, 0)")
+ spark.sql("INSERT INTO T VALUES (16, NULL, 'legacy', 7, 1)")
+ runSql(
+ """CALL sys.create_global_index(table=>'test.T', index_column=>'v',
+ |index_type=>'ivf-flat',
extra_fields=>'{"tenant":"bitmap","priority":"bitmap"}',
+
|options=>'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.metric=l2,ivf-flat.centroid.nlist=2,ivf-flat.nlist=1,ivf-flat.train.sample-ratio=1')""".stripMargin)
+ spark.sql("ALTER TABLE T ADD COLUMNS (region STRING, tier INT)")
+ spark.sql("UPDATE T SET region = 'apac' WHERE id IN (12, 13,
14)").collect()
+ spark.sql("DELETE FROM T WHERE id = 14").collect()
+
+ def filesByPartition: Map[Int, Set[IndexFileMeta]] = {
+ val table = loadTable("T")
+ table
+ .store()
+ .newIndexFileHandler()
+ .scan(table.snapshotManager().latestSnapshot(), "ivf-flat")
+ .asScala
+ .groupBy(_.partition().getInt(0))
+ .map { case (partition, entries) => partition ->
entries.map(_.indexFile()).toSet }
+ .toMap
+ }
+
+ def addFields(): Unit = {
+ assert(
+ runSql("""CALL sys.add_global_index_fields(table=>'test.T',
index_column=>'v',
+ |index_type=>'ivf-flat',
extra_fields=>'{"region":"bitmap","tier":"bitmap","tenant":"bitmap"}',
+ |partitions=>'p=1')""".stripMargin).head.getBoolean(0))
+ }
+
+ val table = loadTable("T")
+ val beforeSnapshot = table.snapshotManager().latestSnapshot()
+ val before = filesByPartition
+ addFields()
+ val after = filesByPartition
+ assert(after(0) == before(0))
+ val paths = table.store().pathFactory().globalIndexFileFactory()
+ val beforeFiles = before(1).map(f => (paths.toPath(f), f.fileSize()))
+ val afterFiles = after(1).map(f => (paths.toPath(f), f.fileSize()))
+ assert(beforeFiles.subsetOf(afterFiles))
+ assert(before(1).count(CentroidIndexMeta.isScalarIndex) == 2)
+ val fields = Seq("tenant", "priority", "region",
"tier").map(table.rowType().getField(_).id())
+ val newFiles = after(1).filterNot(f =>
beforeFiles.contains((paths.toPath(f), f.fileSize())))
+ assert(newFiles.size == 2)
+ assert(newFiles.forall(CentroidIndexMeta.isScalarIndex))
+ val newFieldIds = newFiles.map(
+ f => CentroidIndexMeta.file(f,
paths).asInstanceOf[CentroidIndexFile].fieldId())
+ assert(newFieldIds == fields.drop(2).toSet)
+ assert(after(1).forall(_.globalIndexMeta().extraFieldIds().toSeq ==
fields))
+
+ val combinedFilter = "(region = 'apac' OR (tenant = 'legacy' AND
priority = 7))"
+ val query =
+ s"""SELECT id FROM vector_search('T','v',array(0.0f,0.0f),1,
+ |map('centroid.nprobe','2','ivf.nprobe','1'))
+ |WHERE p = 1 AND $combinedFilter""".stripMargin
+ assert(runSql(query).map(_.getInt(0)) == Seq(12))
+ assert(
+ runSql(query.replace(combinedFilter, "tenant = 'legacy' AND priority =
7"))
+ .map(_.getInt(0)) == Seq(11))
+ assert(
+ runSql(query.replace(combinedFilter, "region = 'apac' AND tier IS
NULL"))
+ .map(_.getInt(0)) == Seq(12))
+
+ sys.env.get("PAIMON_JAVA_CENTROID_FIXTURE").foreach {
+ directory =>
+ FileUtils.copyDirectory(
+ new File(tempDBDir, s"$dbName0.db/T"),
+ new File(directory, s"$dbName0.db/centroid_appended_bitmap"))
+ }
+
+ val historical = table
+ .newVectorSearchBuilder()
+ .asInstanceOf[VectorSearchBuilderImpl]
+ .withSnapshot(beforeSnapshot)
+ .withVectorColumn("v")
+ .withVector(Array(0.0f, 0.0f))
+ .withOption("centroid.nprobe", "2")
+ .withLimit(1)
+ .withFilter(new PredicateBuilder(table.rowType())
+ .isNull(table.rowType().getFieldIndex("tenant")))
+ assert(
+ historical
+ .newVectorRead()
+ .read(historical.newVectorScan().scan())
+ .results()
+ .getLongCardinality() == 1)
+
+ val addedSnapshot = table.snapshotManager().latestSnapshotId()
+ addFields()
+ assert(table.snapshotManager().latestSnapshotId() == addedSnapshot)
+ assert(filesByPartition == after)
+ intercept[Exception] {
+ runSql("UPDATE T SET region = 'eu' WHERE id = 12")
+ }
+ assert(runSql(query).map(_.getInt(0)) == Seq(12))
+ runSql("ALTER TABLE T SET TBLPROPERTIES
('global-index.column-update-action'='IGNORE')")
+ addFields()
+ assert(table.snapshotManager().latestSnapshotId() == addedSnapshot)
+ assert(filesByPartition == after)
+ }
+ }
+
+ test("add_global_index_fields rejects an existing Bitmap whose field type
changed") {
+ withTable("T") {
+ spark.sql(
+ """CREATE TABLE T (v ARRAY<FLOAT>, flag INT, tag STRING) TBLPROPERTIES
(
+ |'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true')""".stripMargin)
+ spark.sql("INSERT INTO T VALUES (array(0.0f, 0.0f), 7, 'active')")
+ runSql(
+ """CALL sys.create_global_index(table=>'test.T', index_column=>'v',
index_type=>'ivf-flat',
+ |extra_fields=>'{"flag":"bitmap","tag":"bitmap"}',
+
|options=>'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.centroid.nlist=1')""".stripMargin)
+
+ def add(field: String): Boolean = {
+ val call =
+ s"""CALL sys.add_global_index_fields(table=>'test.T',
index_column=>'v',
+ |index_type=>'ivf-flat',
extra_fields=>'{"$field":"bitmap"}')""".stripMargin
+ runSql(call).head.getBoolean(0)
+ }
+
+ assert(add("flag"))
+ runSql("ALTER TABLE T ALTER COLUMN flag TYPE BIGINT")
+ val widenedSnapshot = loadTable("T").snapshotManager().latestSnapshotId()
+ val failure = intercept[Exception](add("flag"))
+ val message = "Bitmap field 'flag' has changed type. Rebuild the
centroid index."
+ assert(
+ Iterator
+ .iterate[Throwable](failure)(_.getCause)
+ .takeWhile(_ != null)
+ .exists(e => Option(e.getMessage).exists(_.contains(message))))
+ assert(add("tag"))
+ assert(loadTable("T").snapshotManager().latestSnapshotId() ==
widenedSnapshot)
+ }
+ }
+
+ test("centroid Bitmap append checks source snapshots and survives callback
failure") {
+ withTable("T") {
+ spark.sql(
+ """CREATE TABLE T (id INT, v ARRAY<FLOAT>, status INT, region STRING)
+ |TBLPROPERTIES (
+ |'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true')""".stripMargin)
+ spark.sql("INSERT INTO T VALUES (1, array(0.0f, 0.0f), 10, 'old')")
+ val create =
+ """CALL sys.create_global_index(table=>'test.T', index_column=>'v',
index_type=>'ivf-flat',
+
|options=>'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.centroid.nlist=1'""".stripMargin
+ runSql(s"$create)")
+ val add =
+ """CALL sys.add_global_index_fields(table=>'test.T', index_column=>'v',
+ |index_type=>'ivf-flat',
extra_fields=>'{"region":"bitmap"}')""".stripMargin
+ val unsupported = intercept[Exception](runSql(add))
+ assert(
+ Iterator
+ .iterate[Throwable](unsupported)(_.getCause)
+ .takeWhile(_ != null)
+ .exists(e => Option(e.getMessage).exists(_.contains("index with
Bitmap fields"))))
+ runSql(s"""$create, extra_fields=>'{"status":"bitmap"}')""")
+
+ val table = loadTable("T")
+ val handler = table.store().newIndexFileHandler()
+ def currentFiles: Set[IndexFileMeta] = handler
+ .scan(table.snapshotManager().latestSnapshot(), "ivf-flat")
+ .asScala
+ .map(_.indexFile())
+ .toSet
+ val before = currentFiles
+ val messages = CentroidBitmapFieldAppender.build(
+ spark,
+ table,
+ "ivf-flat",
+ table.rowType().getField("v"),
+ Seq(table.rowType().getField("region")).asJava,
+ null)
+ val paths = table.store().pathFactory().globalIndexFileFactory()
+ runSql("UPDATE T SET region = 'new' WHERE id = 1")
+ val commit = table.newCommit("stale-bitmap-append")
+ try {
+ val failure = intercept[Exception](commit.commit(messages))
+ assert(
+ Iterator
+ .iterate[Throwable](failure)(_.getCause)
+ .takeWhile(_ != null)
+ .exists(
+ e => Option(e.getMessage).exists(_.contains("Centroid index
source rows changed"))))
+ } finally {
+ commit.close()
+ }
+ assert(currentFiles == before)
+ assert(before.forall(file => table.fileIO().exists(paths.toPath(file))))
+
+ val callback = classOf[FailingCentroidBitmapAppendCallback].getName
+ runSql(s"ALTER TABLE T SET TBLPROPERTIES
('commit.callbacks'='$callback')")
+ val publishedFailure = intercept[Exception](runSql(add))
+ assert(
+ Iterator
+ .iterate[Throwable](publishedFailure)(_.getCause)
+ .takeWhile(_ != null)
+ .exists(e => Option(e.getMessage).contains("Injected Bitmap
post-commit failure")))
+ assert(currentFiles.forall(file =>
table.fileIO().exists(paths.toPath(file))))
+ assert(runSql("""SELECT id FROM vector_search('T','v',array(0.0f,0.0f),1)
+ |WHERE region = 'new'""".stripMargin).map(_.getInt(0))
== Seq(1))
+ assert(runSql(add).head.getBoolean(0))
+ }
+ }
+
test("distributed centroid search applies the shard bitmap before top K") {
withTable("T") {
spark.sql("""CREATE TABLE T (id INT, v ARRAY<FLOAT>, status STRING, p
INT)
@@ -782,3 +1007,16 @@ class CentroidVectorIndexTest extends PaimonSparkTestBase
{
}
}
+
+class FailingCentroidBitmapAppendCallback extends CommitCallback {
+
+ override def call(context: CommitCallback.Context): Unit = {
+ if (context.snapshot.commitUser().startsWith("global-index-add-fields-")) {
+ throw new RuntimeException("Injected Bitmap post-commit failure")
+ }
+ }
+
+ override def retry(committable: ManifestCommittable): Unit = {}
+
+ override def close(): Unit = {}
+}