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 ee544b74f1 [spark] Add Bitmap filters to centroid vector shards
(#11306)
ee544b74f1 is described below
commit ee544b74f172fcb14274812161e6b411a66a2046
Author: Jingsong Lee <[email protected]>
AuthorDate: Sat Nov 21 11:24:02 2026 +0800
[spark] Add Bitmap filters to centroid vector shards (#11306)
---
docs/docs/multimodal-table/global-index/vector.mdx | 30 ++
.../paimon/globalindex/CentroidIndexFile.java | 23 +-
.../globalindex/CentroidShardFilterReader.java | 28 ++
.../globalindex/bitmap/CentroidBitmapIndex.java | 264 ++++++++++++++++
.../bitmap/LazyFilteredBitmapIndexReaderTest.java | 75 +++++
.../paimon/globalindex/CentroidIndexMeta.java | 62 +++-
.../globalindex/GlobalIndexBuilderUtils.java | 4 +-
.../paimon/manifest/IndexManifestFileHandler.java | 12 +-
.../paimon/operation/FileStoreCommitImpl.java | 4 +
.../paimon/operation/commit/ConflictDetection.java | 7 +
.../commit/DataEvolutionConflictDetection.java | 65 +++-
.../source/AbstractDataEvolutionVectorRead.java | 63 +++-
.../paimon/table/source/CentroidBitmapFilter.java | 185 ++++++++++++
.../table/source/DataEvolutionVectorScan.java | 29 +-
.../paimon/globalindex/CentroidIndexMetaTest.java | 25 ++
.../operation/commit/ConflictDetectionTest.java | 18 +-
.../flink/procedure/DropGlobalIndexProcedure.java | 8 +-
.../CentroidGlobalIndexTopoBuilder.java | 332 +++++++++++++++++----
.../procedure/CreateGlobalIndexProcedure.java | 60 +++-
.../spark/procedure/DropGlobalIndexProcedure.java | 8 +-
.../paimon/spark/sql/CentroidKryoBuildTest.scala | 18 +-
.../paimon/spark/sql/CentroidVectorIndexTest.scala | 145 +++++++++
.../index/NativeCentroidRoutedIndexReader.java | 88 ++++--
.../index/CentroidVectorGlobalIndexTest.java | 29 ++
24 files changed, 1433 insertions(+), 149 deletions(-)
diff --git a/docs/docs/multimodal-table/global-index/vector.mdx
b/docs/docs/multimodal-table/global-index/vector.mdx
index 90cd3edfff..bce1756458 100644
--- a/docs/docs/multimodal-table/global-index/vector.mdx
+++ b/docs/docs/multimodal-table/global-index/vector.mdx
@@ -654,6 +654,36 @@ for the current 8-bit PQ codes, `pq.m=64` uses twice the
code bytes of
not recall guarantees. Record the resolved build options, total index size,
query file reads, and achieved recall when comparing configurations.
+### Scalar Bitmap Filters in Centroid Shards
+
+In Spark, pass the vector column in `index_column` and a JSON object mapping
scalar column names
+to index types in `extra_fields`. The supported scalar index type is `bitmap`.
+
+```sql
+CALL sys.create_global_index(
+ table => 'db.model_embeddings',
+ index_column => 'embedding',
+ index_type => 'ivf-pq',
+ options => 'ivf-pq.sharding=centroid',
+ extra_fields => '{"tenant_id":"bitmap","status":"bitmap"}'
+);
+```
+
+Each populated centroid gets one additional scalar index file. In
`GlobalIndexMeta.indexMeta`, the
+centroid metadata wraps the build schema ID and one entry per `extraFieldIds`
field, in the same
+order. Each entry stores the index type, section length, and original Bitmap
metadata. The file
+stores the Bitmap sections consecutively, so the reader derives offsets from
the section lengths.
+
+A vector search can use these Bitmaps for equality, `IN`, `IS NULL`, `IS NOT
NULL`, and
+conjunctions of these predicates. It applies the exact matches before ranking
and skips opening
+the ANN file when no visible vector matches. Other predicates use 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. Updates to any
+indexed column follow `THROW_ERROR` or `DROP_PARTITION_INDEX`. Drop the group
before using an
+older Java reader that lacks support for centroid Bitmap files.
+
## Per-Field Options
The options above can also be set at the table level (in `TBLPROPERTIES`),
where they are shared
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 7d2dedffda..70e14ed31d 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
@@ -24,11 +24,12 @@ import javax.annotation.Nullable;
import java.util.Objects;
-/** A router or shard with its underlying index metadata unpacked by Paimon. */
+/** A router, vector shard or scalar bitmap file in a centroid index. */
public final class CentroidIndexFile extends GlobalIndexIOMeta {
private final String modelId;
private final boolean routingModel;
+ private final boolean scalarIndex;
private final int countOrId;
public CentroidIndexFile(
@@ -39,9 +40,22 @@ public final class CentroidIndexFile extends
GlobalIndexIOMeta {
String modelId,
boolean routingModel,
int countOrId) {
+ this(path, size, rows, payload, modelId, routingModel, false,
countOrId);
+ }
+
+ public CentroidIndexFile(
+ Path path,
+ long size,
+ long rows,
+ @Nullable byte[] payload,
+ String modelId,
+ boolean routingModel,
+ boolean scalarIndex,
+ int countOrId) {
super(path, size, rows, payload);
this.modelId = modelId;
this.routingModel = routingModel;
+ this.scalarIndex = scalarIndex;
this.countOrId = countOrId;
}
@@ -53,6 +67,10 @@ public final class CentroidIndexFile extends
GlobalIndexIOMeta {
return routingModel;
}
+ public boolean scalarIndex() {
+ return scalarIndex;
+ }
+
/** Number of centroids in this router. */
public int nlist() {
if (!routingModel) {
@@ -76,12 +94,13 @@ public final class CentroidIndexFile extends
GlobalIndexIOMeta {
}
CentroidIndexFile file = (CentroidIndexFile) other;
return routingModel == file.routingModel
+ && scalarIndex == file.scalarIndex
&& countOrId == file.countOrId
&& modelId.equals(file.modelId);
}
@Override
public int hashCode() {
- return Objects.hash(super.hashCode(), modelId, routingModel,
countOrId);
+ return Objects.hash(super.hashCode(), modelId, routingModel,
scalarIndex, countOrId);
}
}
diff --git
a/paimon-common/src/main/java/org/apache/paimon/globalindex/CentroidShardFilterReader.java
b/paimon-common/src/main/java/org/apache/paimon/globalindex/CentroidShardFilterReader.java
new file mode 100644
index 0000000000..b2b7889782
--- /dev/null
+++
b/paimon-common/src/main/java/org/apache/paimon/globalindex/CentroidShardFilterReader.java
@@ -0,0 +1,28 @@
+/*
+ * 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.globalindex;
+
+import org.apache.paimon.utils.IOFunction;
+import org.apache.paimon.utils.RoaringNavigableMap64;
+
+/** Reader that can apply an exact, range-relative row-ID filter before
opening each shard. */
+public interface CentroidShardFilterReader extends GlobalIndexReader {
+
+ void withShardFilter(IOFunction<Integer, RoaringNavigableMap64> filter);
+}
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
new file mode 100644
index 0000000000..20b357a9e7
--- /dev/null
+++
b/paimon-common/src/main/java/org/apache/paimon/globalindex/bitmap/CentroidBitmapIndex.java
@@ -0,0 +1,264 @@
+/*
+ * 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.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.Equal;
+import org.apache.paimon.predicate.IsNotNull;
+import org.apache.paimon.predicate.IsNull;
+import org.apache.paimon.predicate.LeafPredicate;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.RoaringNavigableMap64;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.paimon.utils.Preconditions.checkArgument;
+import static org.apache.paimon.utils.Preconditions.checkState;
+
+/** Bitmap sections in the order of their manifest's extra field IDs. */
+public final class CentroidBitmapIndex {
+
+ private static final int BITMAP = 1;
+ private static final int ENTRY_HEADER_LENGTH = Byte.BYTES + Long.BYTES +
Integer.BYTES;
+
+ private CentroidBitmapIndex() {}
+
+ public static long schemaId(byte[] metadata) {
+ return metadataPayload(metadata).getLong();
+ }
+
+ private static ByteBuffer metadataPayload(byte[] metadata) {
+ checkArgument(
+ metadata != null && metadata.length >= Long.BYTES,
+ "Truncated centroid bitmap metadata.");
+ return ByteBuffer.wrap(metadata);
+ }
+
+ public static RoaringNavigableMap64 match(
+ GlobalIndexFileReader files,
+ GlobalIndexIOMeta bitmap,
+ int[] extraFieldIds,
+ RowType rowType,
+ RowType buildType,
+ List<LeafPredicate> predicates)
+ throws IOException {
+ checkArgument(!predicates.isEmpty(), "Centroid bitmap lookup requires
a predicate.");
+ ByteBuffer metadata = metadataPayload(bitmap.metadata());
+ metadata.getLong(); // build schema ID
+ Map<Integer, Section> sections = readDirectory(metadata,
extraFieldIds, bitmap.fileSize());
+ try (SeekableInputStream input = files.getInputStream(bitmap)) {
+ RoaringNavigableMap64 result = null;
+ for (LeafPredicate predicate : predicates) {
+ int fieldId =
rowType.getField(predicate.fieldRefOptional().get().name()).id();
+ Section section = sections.get(fieldId);
+ checkState(section != null, "Missing field %s in %s.",
fieldId, bitmap.filePath());
+ checkArgument(
+ section.indexType == BITMAP,
+ "Unsupported centroid scalar index type %s for field
%s.",
+ section.indexType,
+ fieldId);
+ KeySerializer serializer =
KeySerializer.create(buildType.getField(fieldId).type());
+ GlobalIndexIOMeta sectionMeta =
+ new GlobalIndexIOMeta(
+ bitmap.filePath(),
+ section.length,
+ bitmap.rowCount(),
+ section.metadata);
+ try (BitmapIndexReader reader =
+ new BitmapIndexReader(
+ serializer, ignored -> section.open(input),
sectionMeta)) {
+ RoaringNavigableMap64 rows;
+ if (Equal.INSTANCE.equals(predicate.function())) {
+ rows =
reader.visitEqual(predicate.literals().get(0)).get().results();
+ } else if (IsNull.INSTANCE.equals(predicate.function())) {
+ rows = reader.visitIsNull().get().results();
+ } else if
(IsNotNull.INSTANCE.equals(predicate.function())) {
+ rows = reader.visitIsNotNull().get().results();
+ } else {
+ rows =
reader.visitIn(predicate.literals()).get().results();
+ }
+ result = result == null ? rows :
RoaringNavigableMap64.and(result, rows);
+ if (result.isEmpty()) {
+ break;
+ }
+ }
+ }
+ return result;
+ }
+ }
+
+ private static Map<Integer, Section> readDirectory(
+ ByteBuffer directory, int[] extraFieldIds, long sectionsLength) {
+ int fieldCount = extraFieldIds.length;
+ checkArgument(
+ fieldCount > 0 && fieldCount <= directory.remaining() /
ENTRY_HEADER_LENGTH,
+ "Invalid centroid bitmap field count.");
+ Map<Integer, Section> sections = new HashMap<>();
+ long offset = 0;
+ for (int i = 0; i < fieldCount; i++) {
+ int fieldId = extraFieldIds[i];
+ int indexType = Byte.toUnsignedInt(directory.get());
+ long length = directory.getLong();
+ int metaLength = directory.getInt();
+ checkArgument(
+ length > 0
+ && length <= sectionsLength - offset
+ && metaLength >= 0
+ && metaLength
+ <= directory.remaining()
+ - (fieldCount - i - 1) *
ENTRY_HEADER_LENGTH,
+ "Invalid centroid bitmap section for field %s.",
+ fieldId);
+ byte[] metadata = new byte[metaLength];
+ directory.get(metadata);
+ checkArgument(
+ sections.put(fieldId, new Section(indexType, offset,
length, metadata)) == null,
+ "Duplicate centroid bitmap field %s.",
+ fieldId);
+ offset += length;
+ }
+ checkArgument(
+ offset == sectionsLength && !directory.hasRemaining(),
+ "Invalid centroid bitmap directory.");
+ return sections;
+ }
+
+ /** Writes one complete Bitmap per column to the same output stream. */
+ public static final class Writer implements AutoCloseable {
+
+ private final String name;
+ private final int fieldCount;
+ private final long rowCount;
+ private final PositionOutputStream output;
+ private final ByteArrayOutputStream directoryBytes = new
ByteArrayOutputStream();
+ private final DataOutputStream directory = new
DataOutputStream(directoryBytes);
+ private int written;
+
+ public Writer(GlobalIndexFileWriter files, long schemaId, int
fieldCount, long rowCount)
+ throws IOException {
+ this.name = files.newFileName("centroid-bitmap");
+ this.fieldCount = fieldCount;
+ this.rowCount = rowCount;
+ directory.writeLong(schemaId);
+ this.output = files.newOutputStream(name);
+ }
+
+ public void writeColumn(DataField field, Options options, ColumnRows
rows)
+ throws IOException {
+ long offset = output.getPos();
+ GlobalIndexFileWriter sectionWriter =
+ new GlobalIndexFileWriter() {
+ @Override
+ public String newFileName(String prefix) {
+ return name;
+ }
+
+ @Override
+ public PositionOutputStream newOutputStream(String
fileName) {
+ return new CloseShieldOutputStream(output) {
+ @Override
+ public long getPos() throws IOException {
+ return super.getPos() - offset;
+ }
+ };
+ }
+ };
+ ResultEntry section;
+ try (BitmapGlobalIndexWriter writer =
+ new BitmapGlobalIndexer(field,
options).createWriter(sectionWriter)) {
+ rows.writeTo(writer);
+ section = writer.finish().get(0);
+ }
+ checkState(
+ section.rowCount() == rowCount,
+ "Centroid bitmap and vector row counts differ.");
+ directory.writeByte(BITMAP);
+ directory.writeLong(output.getPos() - offset);
+ directory.writeInt(section.meta().length);
+ directory.write(section.meta());
+ written++;
+ }
+
+ public ResultEntry finish() {
+ checkState(written == fieldCount, "Incomplete centroid bitmap
file.");
+ return new ResultEntry(name, rowCount,
directoryBytes.toByteArray());
+ }
+
+ @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 int indexType;
+ private final long offset;
+ private final long length;
+ private final byte[] metadata;
+
+ private Section(int indexType, long offset, long length, byte[]
metadata) {
+ this.indexType = indexType;
+ this.offset = offset;
+ this.length = length;
+ this.metadata = metadata;
+ }
+
+ 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/test/java/org/apache/paimon/globalindex/bitmap/LazyFilteredBitmapIndexReaderTest.java
b/paimon-common/src/test/java/org/apache/paimon/globalindex/bitmap/LazyFilteredBitmapIndexReaderTest.java
index 389e1a7d72..faff123e8b 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
@@ -34,8 +34,11 @@ 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.FieldRef;
+import org.apache.paimon.predicate.LeafPredicate;
+import org.apache.paimon.predicate.PredicateBuilder;
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.Pair;
@@ -47,6 +50,7 @@ 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;
@@ -76,6 +80,77 @@ public class LazyFilteredBitmapIndexReaderTest {
@TempDir java.nio.file.Path tempPath;
+ @Test
+ void centroidBitmapSectionsPreserveSparseRowIdsAndNulls() 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);
+ };
+ byte[] originalMeta;
+ try (BitmapGlobalIndexWriter standalone =
globalIndexer.createWriter(fileWriter)) {
+ tags.writeTo(standalone);
+ originalMeta = standalone.finish().get(0).meta();
+ }
+ ResultEntry result;
+ try (CentroidBitmapIndex.Writer writer =
+ new CentroidBitmapIndex.Writer(fileWriter, 9, 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();
+ }
+ assertThat(CentroidBitmapIndex.schemaId(result.meta())).isEqualTo(9L);
+ Path path = new Path(basePath, result.fileName());
+ GlobalIndexIOMeta meta =
+ new GlobalIndexIOMeta(path, fileIO.getFileSize(path), 2,
result.meta());
+ ByteBuffer directory = ByteBuffer.wrap(result.meta());
+ directory.position(Long.BYTES);
+ assertThat(directory.get()).isEqualTo((byte) 1);
+ long stateLength = directory.getLong();
+ int stateMetaLength = directory.getInt();
+ directory.position(directory.position() + stateMetaLength);
+ assertThat(directory.get()).isEqualTo((byte) 1);
+ assertThat(directory.getLong()).isEqualTo(meta.fileSize() -
stateLength);
+ assertThat(directory.getInt()).isEqualTo(originalMeta.length);
+ byte[] storedMeta = new byte[directory.remaining()];
+ directory.get(storedMeta);
+ assertThat(storedMeta).isEqualTo(originalMeta);
+
+ int[] extraFieldIds = {state.id(), dataField.id()};
+ PredicateBuilder builder = new PredicateBuilder(fields);
+ List<LeafPredicate> predicates =
+ Arrays.asList(
+ (LeafPredicate) builder.equal(0,
BinaryString.fromString("red")),
+ (LeafPredicate) builder.isNull(1));
+ assertThat(
+ CentroidBitmapIndex.match(
+ fileReader, meta, extraFieldIds, fields,
fields, predicates))
+ .containsExactly(90_000L);
+ GlobalIndexIOMeta incomplete =
+ new GlobalIndexIOMeta(path, meta.fileSize() - 1, 2,
result.meta());
+ assertThatThrownBy(
+ () ->
+ CentroidBitmapIndex.match(
+ file -> {
+ throw new AssertionError(
+ "Invalid manifest opened a
file.");
+ },
+ incomplete,
+ extraFieldIds,
+ fields,
+ fields,
+ predicates))
+ .hasMessageContaining("Invalid centroid bitmap section");
+ }
+
@BeforeEach
public void setUp() {
fileIO = LocalFileIO.create();
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 e02f72f51e..52e040efe5 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
@@ -19,6 +19,7 @@
package org.apache.paimon.globalindex;
import org.apache.paimon.fs.Path;
+import org.apache.paimon.index.GlobalIndexMeta;
import org.apache.paimon.index.IndexFileMeta;
import org.apache.paimon.index.IndexPathFactory;
@@ -26,6 +27,7 @@ import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
+import java.util.List;
import static org.apache.paimon.utils.Preconditions.checkArgument;
import static org.apache.paimon.utils.Preconditions.checkNotNull;
@@ -34,8 +36,10 @@ import static
org.apache.paimon.utils.Preconditions.checkNotNull;
public final class CentroidIndexMeta {
private static final byte[] MAGIC = {'P', 'A', 'I', 'M', 'C', 'E', 'N',
'T'};
private static final byte VERSION = 1;
+ private static final byte SCALAR_INDEX_VERSION = 2;
private static final byte ROUTER = 1;
private static final byte SHARD = 2;
+ private static final byte SCALAR_INDEX = 3;
private static final int HEADER_SIZE = MAGIC.length + 2 + 3 *
Integer.BYTES;
private CentroidIndexMeta() {}
@@ -60,23 +64,64 @@ public final class CentroidIndexMeta {
return isWrapped(meta) && role(meta) == ROUTER;
}
+ public static boolean hasScalarIndexes(@Nullable byte[] meta) {
+ return isWrapped(meta)
+ && meta.length >= HEADER_SIZE
+ && meta[MAGIC.length] == SCALAR_INDEX_VERSION;
+ }
+
+ public static boolean isScalarIndex(IndexFileMeta file) {
+ byte[] meta = checkNotNull(file.globalIndexMeta()).indexMeta();
+ return isWrapped(meta) && role(meta) == SCALAR_INDEX;
+ }
+
+ /** Scalar sections 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
+ && meta.indexFieldId() == fieldIds.get(0)
+ && hasScalarIndexes(meta.indexMeta()));
+ }
+
private static byte role(byte[] meta) {
checkArgument(meta.length >= HEADER_SIZE, "Truncated centroid
metadata.");
- checkArgument(meta[MAGIC.length] == VERSION, "Unsupported centroid
metadata version.");
+ byte version = meta[MAGIC.length];
+ checkArgument(
+ version == VERSION || version == SCALAR_INDEX_VERSION,
+ "Unsupported centroid metadata version: %s.",
+ version);
byte role = meta[MAGIC.length + 1];
- checkArgument(role == ROUTER || role == SHARD, "Invalid centroid file
role.");
+ checkArgument(
+ role == ROUTER
+ || role == SHARD
+ || (version == SCALAR_INDEX_VERSION && role ==
SCALAR_INDEX),
+ "Invalid centroid file role.");
return role;
}
public static ResultEntry router(ResultEntry file, String modelId, int
nlist) {
- return wrap(file, modelId, ROUTER, nlist);
+ return router(file, modelId, nlist, false);
+ }
+
+ public static ResultEntry router(ResultEntry file, String modelId, int
nlist, boolean bitmap) {
+ return wrap(file, modelId, bitmap ? SCALAR_INDEX_VERSION : VERSION,
ROUTER, nlist);
}
public static ResultEntry shard(ResultEntry file, String modelId, int
centroid) {
- return wrap(file, modelId, SHARD, centroid);
+ return shard(file, modelId, centroid, false);
+ }
+
+ public static ResultEntry shard(
+ ResultEntry file, String modelId, int centroid, boolean bitmap) {
+ return wrap(file, modelId, bitmap ? SCALAR_INDEX_VERSION : VERSION,
SHARD, centroid);
+ }
+
+ public static ResultEntry scalarIndex(ResultEntry file, String modelId,
int centroid) {
+ return wrap(file, modelId, SCALAR_INDEX_VERSION, SCALAR_INDEX,
centroid);
}
- private static ResultEntry wrap(ResultEntry file, String modelId, byte
role, int countOrId) {
+ private static ResultEntry wrap(
+ ResultEntry file, String modelId, byte version, byte role, int
countOrId) {
checkArgument(!modelId.isEmpty() && countOrId >= 0, "Invalid centroid
descriptor.");
byte[] id = modelId.getBytes(StandardCharsets.UTF_8);
byte[] payload = file.meta();
@@ -86,7 +131,7 @@ public final class CentroidIndexMeta {
Math.addExact(HEADER_SIZE, id.length),
payload == null ? 0 : payload.length));
out.put(MAGIC)
- .put(VERSION)
+ .put(version)
.put(role)
.putInt(countOrId)
.putInt(id.length)
@@ -110,7 +155,7 @@ public final class CentroidIndexMeta {
if (!isWrapped(meta)) {
return new GlobalIndexIOMeta(path, size, rows, meta);
}
- boolean routing = role(meta) == ROUTER;
+ byte role = role(meta);
ByteBuffer in = ByteBuffer.wrap(meta);
in.position(MAGIC.length + 2);
int countOrId = in.getInt();
@@ -130,6 +175,7 @@ public final class CentroidIndexMeta {
payload = new byte[payloadLength];
in.get(payload);
}
- return new CentroidIndexFile(path, size, rows, payload, id, routing,
countOrId);
+ return new CentroidIndexFile(
+ path, size, rows, payload, id, role == ROUTER, role ==
SCALAR_INDEX, countOrId);
}
}
diff --git
a/paimon-core/src/main/java/org/apache/paimon/globalindex/GlobalIndexBuilderUtils.java
b/paimon-core/src/main/java/org/apache/paimon/globalindex/GlobalIndexBuilderUtils.java
index 4432d31988..0c956c2137 100644
---
a/paimon-core/src/main/java/org/apache/paimon/globalindex/GlobalIndexBuilderUtils.java
+++
b/paimon-core/src/main/java/org/apache/paimon/globalindex/GlobalIndexBuilderUtils.java
@@ -178,7 +178,9 @@ public class GlobalIndexBuilderUtils {
if (meta.indexFieldId() != indexFieldId) {
continue;
}
- if (!sameExtraFieldIds(meta.extraFieldIds(), extraFieldIds)) {
+ if (!sameExtraFieldIds(meta.extraFieldIds(), extraFieldIds)
+ && !(extraFieldIds == null
+ &&
CentroidIndexMeta.hasScalarIndexes(meta.indexMeta()))) {
continue;
}
entries.add(entry);
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 fd6efaa60e..2f909ddd17 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
@@ -19,6 +19,7 @@
package org.apache.paimon.manifest;
import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.globalindex.CentroidIndexMeta;
import org.apache.paimon.index.DataEvolutionIndexSourceMeta;
import org.apache.paimon.index.DeletionVectorMeta;
import org.apache.paimon.index.GlobalIndexMeta;
@@ -250,6 +251,12 @@ public class IndexManifestFileHandler {
validateOverlaps(retainedIndexFiles, addedIndexFiles, true);
}
+ private List<Integer> overlapFieldIds(GlobalIndexMeta meta) {
+ return CentroidIndexMeta.hasScalarIndexes(meta.indexMeta())
+ ? Collections.singletonList(meta.indexFieldId())
+ : meta.getIndexedFieldIds();
+ }
+
private void validateOverlaps(
Iterable<IndexManifestEntry> retainedIndexFiles,
List<IndexManifestEntry> addedIndexFiles,
@@ -264,8 +271,7 @@ public class IndexManifestFileHandler {
TreeRangeMap<Long, IndexManifestEntry> ranges =
additions
.computeIfAbsent(entry.partition(), p -> new
HashMap<>())
- .computeIfAbsent(
- meta.getIndexedFieldIds(), f ->
TreeRangeMap.create());
+ .computeIfAbsent(overlapFieldIds(meta), f ->
TreeRangeMap.create());
Range<Long> range = Range.closed(meta.rowRangeStart(),
meta.rowRangeEnd());
Map.Entry<Range<Long>, IndexManifestEntry> previous =
ranges.getEntry(meta.rowRangeStart());
@@ -287,7 +293,7 @@ public class IndexManifestFileHandler {
continue;
}
TreeRangeMap<Long, IndexManifestEntry> ranges =
- partition.get(retainedMeta.getIndexedFieldIds());
+ partition.get(overlapFieldIds(retainedMeta));
if (ranges == null) {
continue;
}
diff --git
a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
index 3d996fea92..8e99c9cf01 100644
---
a/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
+++
b/paimon-core/src/main/java/org/apache/paimon/operation/FileStoreCommitImpl.java
@@ -1493,6 +1493,10 @@ public class FileStoreCommitImpl implements
FileStoreCommit {
throw exception.get();
}
}
+ if (latestSnapshot != null) {
+ conflictDetection.checkRetainedGlobalIndexes(
+ latestSnapshot, deltaFiles, indexFiles, commitKind);
+ }
Snapshot newSnapshot;
Pair<String, Long> baseManifestList = null;
diff --git
a/paimon-core/src/main/java/org/apache/paimon/operation/commit/ConflictDetection.java
b/paimon-core/src/main/java/org/apache/paimon/operation/commit/ConflictDetection.java
index 3685d96311..9925a76652 100644
---
a/paimon-core/src/main/java/org/apache/paimon/operation/commit/ConflictDetection.java
+++
b/paimon-core/src/main/java/org/apache/paimon/operation/commit/ConflictDetection.java
@@ -173,6 +173,13 @@ public abstract class ConflictDetection {
return false;
}
+ /** Checks whether the existing global indexes can be retained by this
commit. */
+ public void checkRetainedGlobalIndexes(
+ Snapshot snapshot,
+ List<ManifestEntry> deltaFiles,
+ List<IndexManifestEntry> indexFiles,
+ CommitKind commitKind) {}
+
@Nullable
public RowIdConflictChecker createRowIdConflictChecker(
SchemaManager schemaManager, List<ManifestEntry> deltaFiles,
CommitKind commitKind) {
diff --git
a/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionConflictDetection.java
b/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionConflictDetection.java
index 89ad887882..e89ce7b92a 100644
---
a/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionConflictDetection.java
+++
b/paimon-core/src/main/java/org/apache/paimon/operation/commit/DataEvolutionConflictDetection.java
@@ -279,6 +279,59 @@ public class DataEvolutionConflictDetection extends
ConflictDetection {
return Collections.emptyList();
}
+ @Override
+ public void checkRetainedGlobalIndexes(
+ Snapshot snapshot,
+ List<ManifestEntry> deltaFiles,
+ List<IndexManifestEntry> indexFiles,
+ CommitKind commitKind) {
+ if (commitKind == CommitKind.COMPACT || snapshot.indexManifest() ==
null) {
+ return;
+ }
+ Map<BinaryRow, List<DataFileMeta>> updates = new HashMap<>();
+ for (ManifestEntry change : deltaFiles) {
+ if (change.kind() == FileKind.ADD && change.file().firstRowId() !=
null) {
+ updates.computeIfAbsent(change.partition(), ignored -> new
ArrayList<>())
+ .add(change.file());
+ }
+ }
+ if (updates.isEmpty()) {
+ return;
+ }
+ Set<String> deletedIndexes =
+ indexFiles.stream()
+ .filter(entry -> entry.kind() == FileKind.DELETE)
+ .map(entry -> entry.indexFile().fileName())
+ .collect(Collectors.toSet());
+ Map<Long, TableSchema> schemas = new HashMap<>();
+ for (IndexManifestEntry index :
indexFileHandler.readManifest(snapshot.indexManifest())) {
+ IndexFileMeta file = index.indexFile();
+ GlobalIndexMeta meta = file.globalIndexMeta();
+ List<DataFileMeta> partitionUpdates =
updates.get(index.partition());
+ if (partitionUpdates == null
+ || meta == null
+ || !CentroidIndexMeta.hasScalarIndexes(meta.indexMeta())
+ || !CentroidIndexMeta.isRoutingModel(meta.indexMeta())
+ || deletedIndexes.contains(file.fileName())) {
+ continue;
+ }
+ for (DataFileMeta update : partitionUpdates) {
+ Range changed = update.nonNullRowIdRange();
+ if (changed.to < meta.rowRangeStart() || changed.from >
meta.rowRangeEnd()) {
+ continue;
+ }
+ TableSchema schema =
+ schemas.computeIfAbsent(update.schemaId(),
commitScanner()::schema);
+ if (!Collections.disjoint(
+ meta.getIndexedFieldIds(), fileFieldIds(schema,
update))) {
+ throw new IllegalStateException(
+ "Update affects an active centroid index with
Bitmap fields. "
+ + "Drop the index or use
DROP_PARTITION_INDEX before updating.");
+ }
+ }
+ }
+ }
+
private List<SimpleFileEntry> scanChangedRowRanges(
Snapshot latestSnapshot,
List<BinaryRow> changedPartitions,
@@ -669,11 +722,13 @@ public class DataEvolutionConflictDetection extends
ConflictDetection {
Map<Pair<BinaryRow, Integer>, List<Range>> additions = new
HashMap<>();
for (IndexManifestEntry index : starting) {
GlobalIndexMeta meta = index.indexFile().globalIndexMeta();
- additions
- .computeIfAbsent(
- Pair.of(index.partition(),
meta.indexFieldId()),
- ignored -> new ArrayList<>())
- .add(meta.rowRange());
+ for (int fieldId : meta.getIndexedFieldIds()) {
+ additions
+ .computeIfAbsent(
+ Pair.of(index.partition(), fieldId),
+ ignored -> new ArrayList<>())
+ .add(meta.rowRange());
+ }
}
additions.forEach(
(key, ranges) -> {
diff --git
a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataEvolutionVectorRead.java
b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataEvolutionVectorRead.java
index 8867ea05c2..caf369cef2 100644
---
a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataEvolutionVectorRead.java
+++
b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataEvolutionVectorRead.java
@@ -25,6 +25,7 @@ import org.apache.paimon.data.InternalRow;
import org.apache.paimon.data.InternalVector;
import org.apache.paimon.fs.FileIO;
import org.apache.paimon.globalindex.CentroidIndexMeta;
+import org.apache.paimon.globalindex.CentroidShardFilterReader;
import org.apache.paimon.globalindex.DataEvolutionGlobalIndexScanner;
import org.apache.paimon.globalindex.GlobalIndexEvaluator;
import org.apache.paimon.globalindex.GlobalIndexIOMeta;
@@ -54,6 +55,7 @@ import org.apache.paimon.types.ArrayType;
import org.apache.paimon.types.DataField;
import org.apache.paimon.types.DataTypeRoot;
import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.IOFunction;
import org.apache.paimon.utils.IOUtils;
import org.apache.paimon.utils.Pair;
import org.apache.paimon.utils.Range;
@@ -71,6 +73,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
+import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -112,6 +115,10 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
*/
@Nullable private transient RoaringNavigableMap64 scalarPreFilter;
+ private transient Map<List<IndexFileMeta>, IOFunction<Integer,
RoaringNavigableMap64>>
+ shardFilters;
+ private transient Map<Long, RowType> shardBuildSchemas;
+
static final Comparator<long[]> WEAKEST_SCORE_FIRST =
Comparator.<long[]>comparingDouble(a -> Float.intBitsToFloat((int)
a[1]))
.thenComparing((a, b) -> Long.compare(b[0], a[0]));
@@ -198,7 +205,7 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
}
private GlobalIndexer createGlobalIndexer(String indexType,
GlobalIndexMeta meta) {
- if (meta.extraFieldIds() == null) {
+ if (meta.extraFieldIds() == null ||
CentroidIndexMeta.hasScalarIndexes(meta.indexMeta())) {
return createGlobalIndexer(indexType);
}
return GlobalIndexer.createForRead(
@@ -219,10 +226,25 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
splitSearchSplits(splits, indexSplits, rawSplits);
scalarPreFilter = null;
postFiltering = false;
+ shardFilters = new IdentityHashMap<>();
+ shardBuildSchemas = new HashMap<>();
if (filter == null || indexSplits.isEmpty()) {
return;
}
- RoaringNavigableMap64 matchedRows = scalarMatchedRows(indexSplits);
+ List<IndexVectorSearchSplit> otherSplits = new ArrayList<>();
+ for (IndexVectorSearchSplit split : indexSplits) {
+ IOFunction<Integer, RoaringNavigableMap64> shardFilter =
+ CentroidBitmapFilter.create(
+ table, filter, split.vectorIndexFiles(),
shardBuildSchemas);
+ shardFilters.put(split.vectorIndexFiles(), shardFilter);
+ if (shardFilter == null) {
+ otherSplits.add(split);
+ }
+ }
+ if (otherSplits.isEmpty()) {
+ return;
+ }
+ RoaringNavigableMap64 matchedRows = scalarMatchedRows(otherSplits);
if (matchedRows != null) {
scalarPreFilter = matchedRows;
return;
@@ -230,6 +252,18 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
postFiltering = true;
}
+ @Nullable
+ private IOFunction<Integer, RoaringNavigableMap64>
shardFilter(List<IndexFileMeta> files) {
+ if (shardFilters != null && shardFilters.containsKey(files)) {
+ return shardFilters.get(files);
+ }
+ // Distributed readers receive deserialized splits and recreate file
readers on the worker.
+ if (shardBuildSchemas == null) {
+ shardBuildSchemas = new HashMap<>();
+ }
+ return CentroidBitmapFilter.create(table, filter, files,
shardBuildSchemas);
+ }
+
protected List<RoaringNavigableMap64>
preFilters(List<IndexVectorSearchSplit> splits) {
List<Range> indexedRowRanges = new ArrayList<>(splits.size());
for (IndexVectorSearchSplit split : splits) {
@@ -239,14 +273,15 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
RoaringNavigableMap64 liveRows =
GlobalIndexLiveRowFilter.liveRows(
table, planSnapshot, partitionFilter,
indexedRowRanges);
- RoaringNavigableMap64 matchedRows =
- postFiltering
- ? null
- : scalarPreFilter != null ? scalarPreFilter :
scalarMatchedRows(splits);
+ RoaringNavigableMap64 matchedRows = postFiltering ? null :
scalarPreFilter;
+ if (!postFiltering && matchedRows == null && shardFilters == null) {
+ matchedRows = scalarMatchedRows(splits);
+ }
List<RoaringNavigableMap64> includeRowIds = new
ArrayList<>(splits.size());
boolean hasFilter = false;
- for (Range splitRange : indexedRowRanges) {
+ for (int i = 0; i < indexedRowRanges.size(); i++) {
+ Range splitRange = indexedRowRanges.get(i);
RoaringNavigableMap64 splitRows = bitmapOf(splitRange);
RoaringNavigableMap64 include = new RoaringNavigableMap64();
@@ -254,7 +289,7 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
if (liveRows != null) {
include.and(liveRows);
}
- if (matchedRows != null) {
+ if (matchedRows != null &&
shardFilter(splits.get(i).vectorIndexFiles()) == null) {
include.and(matchedRows);
}
@@ -396,6 +431,7 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
return CompletableFuture.completedFuture(Optional.empty());
}
+ IOFunction<Integer, RoaringNavigableMap64> shardFilter =
shardFilter(vectorIndexFiles);
GlobalIndexReader reader =
createVectorReader(
globalIndexer,
@@ -403,8 +439,9 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
rowRangeStart,
rowRangeEnd,
vectorIndexFiles,
+ shardFilter,
executor);
- if (postFiltering) {
+ if (postFiltering && shardFilter == null) {
CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> batch =
evalPostFilter(
reader,
@@ -444,6 +481,7 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
return
CompletableFuture.completedFuture(emptyOptionalResults(vectors.length));
}
+ IOFunction<Integer, RoaringNavigableMap64> shardFilter =
shardFilter(vectorIndexFiles);
GlobalIndexReader reader =
createVectorReader(
globalIndexer,
@@ -451,8 +489,9 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
rowRangeStart,
rowRangeEnd,
vectorIndexFiles,
+ shardFilter,
executor);
- if (postFiltering) {
+ if (postFiltering && shardFilter == null) {
return evalPostFilter(
reader, rowRangeStart, rowRangeEnd, vectors, searchLimit,
includeRowIds);
}
@@ -469,6 +508,7 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
long rowRangeStart,
long rowRangeEnd,
List<IndexFileMeta> vectorIndexFiles,
+ @Nullable IOFunction<Integer, RoaringNavigableMap64> shardFilter,
ExecutorService executor) {
List<GlobalIndexIOMeta> indexIOMetaList =
buildIOMetaList(indexPathFactory, vectorIndexFiles);
@@ -482,6 +522,9 @@ public abstract class AbstractDataEvolutionVectorRead
implements Serializable {
rowRangeEnd - rowRangeStart + 1,
null,
executor);
+ if (shardFilter != null) {
+ ((CentroidShardFilterReader) reader).withShardFilter(shardFilter);
+ }
return new OffsetGlobalIndexReader(reader, rowRangeStart, rowRangeEnd);
}
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
new file mode 100644
index 0000000000..fe9016b432
--- /dev/null
+++
b/paimon-core/src/main/java/org/apache/paimon/table/source/CentroidBitmapFilter.java
@@ -0,0 +1,185 @@
+/*
+ * 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.table.source;
+
+import org.apache.paimon.globalindex.CentroidIndexFile;
+import org.apache.paimon.globalindex.CentroidIndexMeta;
+import org.apache.paimon.globalindex.bitmap.CentroidBitmapIndex;
+import org.apache.paimon.index.GlobalIndexMeta;
+import org.apache.paimon.index.IndexFileMeta;
+import org.apache.paimon.index.IndexPathFactory;
+import org.apache.paimon.predicate.Equal;
+import org.apache.paimon.predicate.FieldRef;
+import org.apache.paimon.predicate.In;
+import org.apache.paimon.predicate.IsNotNull;
+import org.apache.paimon.predicate.IsNull;
+import org.apache.paimon.predicate.LeafPredicate;
+import org.apache.paimon.predicate.Predicate;
+import org.apache.paimon.predicate.PredicateBuilder;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.utils.IOFunction;
+import org.apache.paimon.utils.RoaringNavigableMap64;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.apache.paimon.utils.Preconditions.checkState;
+
+/** Binds an exact scalar predicate to the bitmap files within a vector split.
*/
+final class CentroidBitmapFilter {
+
+ private CentroidBitmapFilter() {}
+
+ @Nullable
+ static IOFunction<Integer, RoaringNavigableMap64> create(
+ FileStoreTable table,
+ @Nullable Predicate filter,
+ List<IndexFileMeta> files,
+ Map<Long, RowType> buildSchemas) {
+ if (filter == null || files.isEmpty()) {
+ return null;
+ }
+ GlobalIndexMeta meta = files.get(0).globalIndexMeta();
+ int[] extraFieldIds = meta.extraFieldIds();
+ if (!CentroidIndexMeta.hasScalarIndexes(meta.indexMeta()) ||
extraFieldIds == null) {
+ return null;
+ }
+ RowType rowType = table.rowType();
+ List<LeafPredicate> predicates = new ArrayList<>();
+ List<DataField> fields = new ArrayList<>();
+ for (Predicate predicate : PredicateBuilder.splitAnd(filter)) {
+ LeafPredicate leaf = pointLookup(predicate);
+ if (leaf == null) {
+ return null;
+ }
+ Optional<FieldRef> fieldRef = leaf.fieldRefOptional();
+ if (!fieldRef.isPresent()
+ || (!Equal.INSTANCE.equals(leaf.function())
+ && !In.INSTANCE.equals(leaf.function())
+ && !IsNotNull.INSTANCE.equals(leaf.function())
+ && !IsNull.INSTANCE.equals(leaf.function()))
+ || !rowType.containsField(fieldRef.get().name())) {
+ return null;
+ }
+ DataField field = rowType.getField(fieldRef.get().name());
+ if (!field.type().equalsIgnoreNullable(fieldRef.get().type())
+ || Arrays.stream(extraFieldIds).noneMatch(id -> id ==
field.id())) {
+ return null;
+ }
+ predicates.add(leaf);
+ fields.add(field);
+ }
+
+ IndexPathFactory paths =
table.store().pathFactory().globalIndexFileFactory();
+ Map<Integer, CentroidIndexFile> bitmaps = new HashMap<>();
+ Map<Integer, CentroidIndexFile> shards = new HashMap<>();
+ CentroidIndexFile router = null;
+ long schemaId = -1;
+ for (IndexFileMeta file : files) {
+ CentroidIndexFile entry = (CentroidIndexFile)
CentroidIndexMeta.file(file, paths);
+ if (entry.routingModel()) {
+ checkState(router == null, "Multiple centroid routing
models.");
+ router = entry;
+ } 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.");
+ long bitmapSchemaId =
CentroidBitmapIndex.schemaId(entry.metadata());
+ checkState(
+ 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.");
+ }
+ }
+ checkState(router != null, "Missing centroid routing model.");
+ checkState(
+ shards.keySet().equals(bitmaps.keySet()),
+ "Centroid bitmap files do not cover the shard group.");
+ if (bitmaps.isEmpty()) {
+ return null;
+ }
+ for (CentroidIndexFile bitmap : bitmaps.values()) {
+ CentroidIndexFile shard = shards.get(bitmap.centroid());
+ checkState(
+ bitmap.modelId().equals(router.modelId())
+ && shard.modelId().equals(router.modelId())
+ && bitmap.rowCount() == shard.rowCount(),
+ "Centroid bitmap and vector shard belong to different
builds.");
+ }
+
+ RowType buildType =
+ schemaId == table.schema().id()
+ ? rowType
+ : buildSchemas.computeIfAbsent(
+ schemaId, id ->
table.schemaManager().schema(id).logicalRowType());
+ for (DataField field : fields) {
+ if (!buildType.containsField(field.id())
+ ||
!field.type().equalsIgnoreNullable(buildType.getField(field.id()).type())) {
+ return null;
+ }
+ }
+ return centroid ->
+ CentroidBitmapIndex.match(
+ file -> table.fileIO().newInputStream(file.filePath()),
+ bitmaps.get(centroid),
+ extraFieldIds,
+ rowType,
+ buildType,
+ predicates);
+ }
+
+ @Nullable
+ private static LeafPredicate pointLookup(Predicate predicate) {
+ if (predicate instanceof LeafPredicate) {
+ return (LeafPredicate) predicate;
+ }
+ // PredicateBuilder represents short IN lists as an OR of equalities.
+ LeafPredicate first = null;
+ List<Object> values = new ArrayList<>();
+ for (Predicate child : PredicateBuilder.splitOr(predicate)) {
+ if (!(child instanceof LeafPredicate)) {
+ return null;
+ }
+ LeafPredicate leaf = (LeafPredicate) child;
+ if (!Equal.INSTANCE.equals(leaf.function()) ||
!leaf.fieldRefOptional().isPresent()) {
+ return null;
+ }
+ if (first == null) {
+ first = leaf;
+ } else if
(!first.fieldRefOptional().equals(leaf.fieldRefOptional())) {
+ return null;
+ }
+ values.add(leaf.literals().get(0));
+ }
+ return first == null ? null : LeafPredicate.of(first.transform(),
In.INSTANCE, values);
+ }
+}
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 28e0e352e6..a1ac203824 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
@@ -36,6 +36,7 @@ import org.apache.paimon.predicate.Predicate;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.source.snapshot.TimeTravelUtil;
import org.apache.paimon.types.DataField;
+import org.apache.paimon.types.RowType;
import org.apache.paimon.utils.Filter;
import org.apache.paimon.utils.Pair;
import org.apache.paimon.utils.Range;
@@ -128,7 +129,6 @@ public class DataEvolutionVectorScan implements VectorScan {
List<IndexFileMeta> scalarFiles = new ArrayList<>();
// Only the primary field serves this vector search. Each split goes
to its own index type.
Map<Pair<Range, String>, List<IndexFileMeta>> rangeGroups = new
HashMap<>();
- List<IndexFileMeta> vectorIndexFiles = new ArrayList<>();
for (IndexManifestEntry entry : indexEntries) {
IndexFileMeta file = entry.indexFile();
GlobalIndexMeta meta = checkNotNull(file.globalIndexMeta());
@@ -136,7 +136,6 @@ public class DataEvolutionVectorScan implements VectorScan {
scalarFiles.add(file);
}
if (isPrimaryColumn(meta, vectorColumn.id())) {
- vectorIndexFiles.add(file);
rangeGroups
.computeIfAbsent(
Pair.of(meta.rowRange(), file.indexType()), k
-> new ArrayList<>())
@@ -155,9 +154,16 @@ public class DataEvolutionVectorScan implements VectorScan
{
.collect(Collectors.toList()));
List<VectorSearchSplit> splits = new ArrayList<>();
List<Range> indexedRanges = new ArrayList<>();
+ List<Range> vectorCoverage = new ArrayList<>();
+ List<Range> bitmapCoverage = new ArrayList<>();
+ Map<Long, RowType> bitmapBuildSchemas = new HashMap<>();
String scoringIndexType = null;
for (Map.Entry<Pair<Range, String>, List<IndexFileMeta>> entry :
rangeGroups.entrySet()) {
List<IndexFileMeta> files = entry.getValue();
+ GlobalIndexMeta meta =
checkNotNull(files.get(0).globalIndexMeta());
+ if (!hasExtraFields(meta) ||
CentroidIndexMeta.hasScalarIndexes(meta.indexMeta())) {
+ 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)) {
@@ -169,6 +175,11 @@ public class DataEvolutionVectorScan implements VectorScan
{
}
Range range = entry.getKey().getLeft();
indexedRanges.add(range);
+ if (!scalarFiles.isEmpty()
+ && CentroidBitmapFilter.create(table, filter, files,
bitmapBuildSchemas)
+ != null) {
+ bitmapCoverage.add(range);
+ }
splits.add(
new IndexVectorSearchSplit(
range.from,
@@ -183,9 +194,9 @@ public class DataEvolutionVectorScan implements VectorScan {
table,
snapshot,
partitionFilter,
- vectorIndexFiles,
+ Collections.emptyList(),
vectorSearchMode)
- .unindexedRanges(vectorColumn.id());
+ .unindexedRangesFromCoverage(vectorCoverage, null);
if (filter != null) {
List<Range> scalarUnindexedRanges =
scalarUnindexedRanges(
@@ -193,6 +204,13 @@ public class DataEvolutionVectorScan implements VectorScan
{
scalarFiles,
effectiveOptions.scalarIndexSearchMode(),
filterFieldIds);
+ if (!bitmapCoverage.isEmpty()) {
+ List<Range> covered =
Range.sortAndMergeOverlap(bitmapCoverage, true);
+ scalarUnindexedRanges =
+ scalarUnindexedRanges.stream()
+ .flatMap(range ->
range.exclude(covered).stream())
+ .collect(Collectors.toList());
+ }
if (vectorSearchMode == GlobalIndexSearchMode.FAST) {
scalarUnindexedRanges =
Range.and(
@@ -332,7 +350,8 @@ public class DataEvolutionVectorScan implements VectorScan {
}
private boolean canServeScalarFilter(GlobalIndexMeta meta) {
- return !isPrimaryColumn(meta, vectorColumn.id()) ||
hasExtraFields(meta);
+ return !CentroidIndexMeta.hasScalarIndexes(meta.indexMeta())
+ && (!isPrimaryColumn(meta, vectorColumn.id()) ||
hasExtraFields(meta));
}
private static boolean hasExtraFields(GlobalIndexMeta meta) {
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 db362de92c..8b336bbddb 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
@@ -19,10 +19,12 @@
package org.apache.paimon.globalindex;
import org.apache.paimon.fs.Path;
+import org.apache.paimon.index.GlobalIndexMeta;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
+import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -79,4 +81,27 @@ class CentroidIndexMetaTest {
assertThatThrownBy(() -> CentroidIndexMeta.file(path, 10, 1, meta))
.hasMessageContaining("version");
}
+
+ @Test
+ void bitmapRolePairsWithTheVectorGeneration() {
+ ResultEntry bitmap =
+ CentroidIndexMeta.scalarIndex(new ResultEntry("bitmap", 3, new
byte[] {9}), "g", 4);
+ CentroidIndexFile decoded =
+ (CentroidIndexFile)
+ CentroidIndexMeta.file(path, 100, bitmap.rowCount(),
bitmap.meta());
+ assertThat(CentroidIndexMeta.hasScalarIndexes(bitmap.meta())).isTrue();
+ assertThat(decoded.scalarIndex()).isTrue();
+ assertThat(decoded.routingModel()).isFalse();
+ assertThat(decoded.centroid()).isEqualTo(4);
+ assertThat(decoded.modelId()).isEqualTo("g");
+ assertThat(decoded.metadata()).containsExactly(9);
+ GlobalIndexMeta meta = new GlobalIndexMeta(0, 9, 1, new int[] {2},
bitmap.meta());
+ assertThat(CentroidIndexMeta.matchesIndexFields(meta,
Collections.singletonList(1)))
+ .isTrue();
+ assertThat(CentroidIndexMeta.matchesIndexFields(meta,
Collections.singletonList(2)))
+ .isFalse();
+ GlobalIndexMeta composite = new GlobalIndexMeta(0, 9, 1, new int[]
{2}, null);
+ assertThat(CentroidIndexMeta.matchesIndexFields(composite,
Collections.singletonList(1)))
+ .isFalse();
+ }
}
diff --git
a/paimon-core/src/test/java/org/apache/paimon/operation/commit/ConflictDetectionTest.java
b/paimon-core/src/test/java/org/apache/paimon/operation/commit/ConflictDetectionTest.java
index d5e9e5bca1..95baee72ae 100644
---
a/paimon-core/src/test/java/org/apache/paimon/operation/commit/ConflictDetectionTest.java
+++
b/paimon-core/src/test/java/org/apache/paimon/operation/commit/ConflictDetectionTest.java
@@ -1808,6 +1808,20 @@ class ConflictDetectionTest {
null,
Snapshot.CommitKind.APPEND))
.isEmpty();
+ byte[] bitmapMeta =
+ CentroidIndexMeta.router(new ResultEntry("model", 0, null),
"model", 2, true)
+ .meta();
+ IndexManifestEntry bitmapIndex = centroidRouter("first", 10, 19, 1,
bitmapMeta);
+ assertThat(
+ detection.checkConflicts(
+ concurrent,
+ data,
+ Collections.emptyList(),
+ Collections.singletonList(bitmapIndex),
+ null,
+ Snapshot.CommitKind.APPEND))
+ .hasValueSatisfying(
+ error ->
assertThat(error).hasMessageContaining("source rows changed"));
// A second router starts at snapshot 2. The change in its interval in
that
// snapshot is already included in its training data. Both are active
in snapshot 3.
IndexManifestEntry second = centroidRouter("second", 100, 109, 2,
meta);
@@ -1828,7 +1842,7 @@ class ConflictDetectionTest {
null,
Snapshot.CommitKind.APPEND))
.isNotPresent();
- verify(scanner, times(3)).readIncrementalEntries(concurrent,
partitions);
+ verify(scanner, times(4)).readIncrementalEntries(concurrent,
partitions);
verify(scanner).readIncrementalEntries(latest, partitions);
when(scanner.readIncrementalEntries(latest, partitions))
@@ -1859,7 +1873,7 @@ class ConflictDetectionTest {
from,
to,
1,
- null,
+ CentroidIndexMeta.hasScalarIndexes(meta) ? new
int[] {0} : null,
meta,
new
org.apache.paimon.index.DataEvolutionIndexSourceMeta(snapshot)
.serialize()));
diff --git
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/procedure/DropGlobalIndexProcedure.java
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/procedure/DropGlobalIndexProcedure.java
index d74d0d2ad7..ace9bfebad 100644
---
a/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/procedure/DropGlobalIndexProcedure.java
+++
b/paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/procedure/DropGlobalIndexProcedure.java
@@ -20,6 +20,7 @@ package org.apache.paimon.flink.procedure;
import org.apache.paimon.Snapshot;
import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.globalindex.CentroidIndexMeta;
import org.apache.paimon.index.IndexFileMeta;
import org.apache.paimon.io.CompactIncrement;
import org.apache.paimon.io.DataIncrement;
@@ -124,15 +125,12 @@ public class DropGlobalIndexProcedure extends
ProcedureBase {
String.format(
"Table '%s' has no
snapshot.", tableId)));
- // Create filter for index entries to delete — match by primary column
+ full column set
Filter<IndexManifestEntry> filter =
entry ->
entry.indexFile().indexType().equals(indexTypeLower)
&& entry.indexFile().globalIndexMeta() != null
- && entry.indexFile()
- .globalIndexMeta()
- .getIndexedFieldIds()
- .equals(indexFieldIds)
+ && CentroidIndexMeta.matchesIndexFields(
+ entry.indexFile().globalIndexMeta(),
indexFieldIds)
&& (partitionPredicate == null
||
partitionPredicate.test(entry.partition()));
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 4bbe847699..d672e44c4b 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
@@ -18,9 +18,15 @@
package org.apache.paimon.spark.globalindex;
+import org.apache.paimon.CoreOptions;
+import org.apache.paimon.CoreOptions.GlobalIndexColumnUpdateAction;
import org.apache.paimon.Snapshot;
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;
import org.apache.paimon.globalindex.GlobalIndexBuilderUtils;
@@ -28,16 +34,22 @@ import
org.apache.paimon.globalindex.GlobalIndexFileReadWrite;
import org.apache.paimon.globalindex.GlobalIndexSingleColumnWriter;
import org.apache.paimon.globalindex.GlobalIndexer;
import org.apache.paimon.globalindex.IndexedSplit;
+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.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.options.Options;
import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.sort.BinaryExternalSortBuffer;
import org.apache.paimon.table.FileStoreTable;
import org.apache.paimon.table.SpecialFields;
import org.apache.paimon.table.sink.CommitMessage;
@@ -47,6 +59,7 @@ 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.MutableObjectIteratorAdapter;
import org.apache.paimon.utils.Pair;
import org.apache.paimon.utils.Range;
import org.apache.paimon.utils.ThreadPoolUtils;
@@ -102,10 +115,42 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
DataField indexField,
Options options)
throws IOException {
+ return buildIndex(
+ spark,
+ relation,
+ partitionPredicate,
+ table,
+ indexType,
+ readType,
+ indexField,
+ Collections.emptyList(),
+ options);
+ }
+
+ @Override
+ public List<CommitMessage> buildIndex(
+ SparkSession spark,
+ DataSourceV2Relation relation,
+ PartitionPredicate partitionPredicate,
+ FileStoreTable table,
+ String indexType,
+ RowType readType,
+ DataField indexField,
+ List<DataField> extraFields,
+ Options options)
+ throws IOException {
CentroidVectorGlobalIndexer indexer = createIndexer(indexType,
indexField, options);
checkArgument(
table.coreOptions().dataEvolutionEnabled(),
"Centroid sharding requires a Data Evolution table.");
+ checkArgument(
+ extraFields.isEmpty()
+ || table.coreOptions().globalIndexColumnUpdateAction()
+ != GlobalIndexColumnUpdateAction.IGNORE,
+ "Centroid bitmap fields require THROW_ERROR or
DROP_PARTITION_INDEX.");
+ for (DataField extraField : extraFields) {
+ KeySerializer.create(extraField.type());
+ }
Snapshot snapshot = table.snapshotManager().latestSnapshot();
if (snapshot == null) {
return Collections.emptyList();
@@ -138,9 +183,11 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
table,
readType,
indexField,
+ extraFields,
options,
partition.getKey(),
snapshot.id(),
+ table.schema().id(),
group.getKey(),
indexType);
ranges.add(Pair.of(context, group.getValue()));
@@ -204,13 +251,18 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
}
}
Map<BinaryRow, List<IndexFileMeta>> previous =
- GlobalIndexBuilderUtils.currentIndexEntries(
- table,
- snapshot,
- indexType,
- Collections.singletonList(indexField),
- partitionPredicate)
- .stream()
+ table.store().newIndexFileHandler().scan(snapshot,
indexType).stream()
+ .filter(
+ entry ->
+ partitionPredicate == null
+ ||
partitionPredicate.test(entry.partition()))
+ .filter(
+ entry ->
+ entry.indexFile().globalIndexMeta() !=
null
+ && entry.indexFile()
+
.globalIndexMeta()
+ .indexFieldId()
+ == indexField.id())
.collect(
Collectors.groupingBy(
IndexManifestEntry::partition,
@@ -242,11 +294,21 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
serializedSplits.add(InstantiationUtil.serializeObject(split));
}
byte[] contextBytes = InstantiationUtil.serializeObject(context);
- JavaRDD<InternalRow> rows =
- sc.parallelize(serializedSplits, Math.min(splits.size(),
slots))
- .mapPartitions(
- input -> new
VectorRows(BuildContext.restore(contextBytes), input));
- byte[] payload = train(sc, contextBytes, rows, indexer,
context.getter());
+ JavaRDD<byte[]> inputSplits =
+ sc.parallelize(serializedSplits, Math.min(splits.size(),
slots));
+ JavaRDD<InternalRow> trainingRows =
+ inputSplits.mapPartitions(
+ input -> {
+ BuildContext build =
BuildContext.restore(contextBytes);
+ return new VectorRows(build, input,
build.trainingReadType());
+ });
+ byte[] payload =
+ train(
+ sc,
+ contextBytes,
+ trainingRows,
+ indexer,
+ context.getter(context.trainingReadType()));
String modelId = UUID.randomUUID().toString();
if (payload == null) {
// Record coverage so an all-null interval also satisfies index
visibility checks.
@@ -260,8 +322,17 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
Broadcast<byte[]> broadcast = sc.broadcast(payload);
try {
int parallelism = Math.min(nlist, slots);
- JavaPairRDD<Integer, Tuple2<Long, float[]>> assigned =
- rows.mapPartitionsToPair(
+ JavaRDD<InternalRow> routedRows =
+ context.hasBitmaps()
+ ? inputSplits.mapPartitions(
+ input -> {
+ BuildContext build =
BuildContext.restore(contextBytes);
+ return new VectorRows(build, input,
build.readType);
+ })
+ : trainingRows;
+ // Keep the shuffle payload compatible with strict Spark Kryo
registration.
+ JavaPairRDD<Integer, Tuple2<Long, Tuple2<float[], byte[]>>>
assigned =
+ routedRows.mapPartitionsToPair(
input ->
route(
BuildContext.restore(contextBytes),
@@ -308,43 +379,20 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
context.table.store().pathFactory().globalIndexFileFactory(),
context.table.coreOptions(),
context.rowRange,
- Collections.singletonList(context.field),
+ context.indexFields,
context.indexType,
Collections.singletonList(
CentroidIndexMeta.router(
indexer.writeRoutingModel(
io, modelFile,
payload, modelId),
modelId,
- nlist)),
+ nlist,
+ context.hasBitmaps())),
context.sourceMeta())
.get(0);
return context.message(Collections.singletonList(modelMeta));
}
- @Override
- public List<CommitMessage> buildIndex(
- SparkSession spark,
- DataSourceV2Relation relation,
- PartitionPredicate partitionPredicate,
- FileStoreTable table,
- String indexType,
- RowType readType,
- DataField indexField,
- List<DataField> extraFields,
- Options options)
- throws IOException {
- checkArgument(extraFields.isEmpty(), "Centroid sharding supports one
vector column.");
- return buildIndex(
- spark,
- relation,
- partitionPredicate,
- table,
- indexType,
- readType,
- indexField,
- options);
- }
-
@Nullable
private static byte[] train(
JavaSparkContext sc,
@@ -415,19 +463,44 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
}
}
- private static Iterator<Tuple2<Integer, Tuple2<Long, float[]>>> route(
+ private static Iterator<Tuple2<Integer, Tuple2<Long, Tuple2<float[],
byte[]>>>> route(
BuildContext context, Iterator<InternalRow> input, byte[] payload)
{
VectorTrainingModel model =
context.indexer().restoreTrainingModel(payload);
closeOnTaskCompletion(model);
- InternalRow.FieldGetter getter = context.getter();
- int idPosition = context.rowIdPosition();
+ InternalRow.FieldGetter getter = context.getter(context.readType);
+ int idPosition =
context.readType.getFieldIndex(SpecialFields.ROW_ID.name());
+ List<InternalRow.FieldGetter> extraGetters = 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), vector));
+ new Tuple2<>(
+ row.getLong(idPosition) -
context.rowRange.from,
+ new Tuple2<>(vector, keys)));
});
}
@@ -447,14 +520,14 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
private static Iterator<byte[]> writeShards(
BuildContext context,
- Iterator<Tuple2<Integer, Tuple2<Long, float[]>>> rows,
+ Iterator<Tuple2<Integer, Tuple2<Long, Tuple2<float[], byte[]>>>>
rows,
int partition,
int parallelism,
int nlist,
String modelId)
throws Exception {
List<byte[]> commits = new ArrayList<>();
- PeekingIterator<Tuple2<Integer, Tuple2<Long, float[]>>> input =
+ PeekingIterator<Tuple2<Integer, Tuple2<Long, Tuple2<float[],
byte[]>>>> input =
Iterators.peekingIterator(rows);
CentroidVectorGlobalIndexer indexer = context.indexer();
GlobalIndexFileReadWrite io = context.io();
@@ -462,12 +535,28 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
// as well, without a second set of input tasks to shuffle sentinel
records.
for (int centroid = partition; centroid < nlist; centroid +=
parallelism) {
GlobalIndexSingleColumnWriter writer =
indexer.createCentroidWriter(io);
- try {
+ try (BitmapSorters bitmapSorters =
+ context.hasBitmaps() && input.hasNext() &&
input.peek()._1() == centroid
+ ? new BitmapSorters(context)
+ : null) {
while (input.hasNext() && input.peek()._1() == centroid) {
- Tuple2<Long, float[]> row = input.next()._2();
- writer.write(row._2(), row._1() - context.rowRange.from);
+ 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());
+ }
}
- commits.add(context.finish(writer, modelId, centroid));
+ List<ResultEntry> files = new ArrayList<>();
+ for (ResultEntry file : writer.finish()) {
+ files.add(
+ CentroidIndexMeta.shard(file, modelId, centroid,
context.hasBitmaps()));
+ }
+ if (bitmapSorters != null) {
+ files.add(
+ CentroidIndexMeta.scalarIndex(
+ bitmapSorters.finish(context, io),
modelId, centroid));
+ }
+ commits.add(context.finish(files));
} finally {
close(writer);
}
@@ -475,6 +564,101 @@ 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"));
+ 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);
+ }
+ 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, context.schemaId,
fields.size(), count)) {
+ for (int i = 0; i < fields.size(); i++) {
+ DataField field = fields.get(i);
+ BinaryExternalSortBuffer buffer = buffers.get(i);
+ 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();
+ }
+ return writer.finish();
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ try {
+ buffers.forEach(BinaryExternalSortBuffer::clear);
+ } finally {
+ ioManager.close();
+ }
+ }
+ }
+
private static void close(Object resource) throws IOException {
if (resource instanceof Closeable) {
((Closeable) resource).close();
@@ -497,9 +681,11 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
private final FileStoreTable table;
private final RowType readType;
private final DataField field;
+ private final List<DataField> indexFields;
private final Options options;
private final BinaryRow partition;
private final long snapshotId;
+ private final long schemaId;
private final Range rowRange;
private final String indexType;
@@ -507,21 +693,35 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
FileStoreTable table,
RowType readType,
DataField field,
+ List<DataField> extraFields,
Options options,
BinaryRow partition,
long snapshotId,
+ long schemaId,
Range rowRange,
String indexType) {
this.table = table;
this.readType = readType;
this.field = field;
+ this.indexFields = new ArrayList<>(1 + extraFields.size());
+ this.indexFields.add(field);
+ this.indexFields.addAll(extraFields);
this.options = options;
this.partition = partition;
this.snapshotId = snapshotId;
+ this.schemaId = schemaId;
this.rowRange = rowRange;
this.indexType = indexType;
}
+ List<DataField> extraFields() {
+ return indexFields.subList(1, indexFields.size());
+ }
+
+ boolean hasBitmaps() {
+ return indexFields.size() > 1;
+ }
+
static BuildContext restore(byte[] bytes) throws IOException,
ClassNotFoundException {
return InstantiationUtil.deserializeObject(
bytes,
CentroidGlobalIndexTopoBuilder.class.getClassLoader());
@@ -536,13 +736,13 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
table.fileIO(),
table.store().pathFactory().globalIndexFileFactory());
}
- int rowIdPosition() {
- return readType.getFieldIndex(SpecialFields.ROW_ID.name());
+ RowType trainingReadType() {
+ return hasBitmaps() ? RowType.of(field, SpecialFields.ROW_ID) :
readType;
}
- InternalRow.FieldGetter getter() {
+ InternalRow.FieldGetter getter(RowType projection) {
return InternalRow.createFieldGetter(
- field.type(), readType.getFieldIndex(field.name()));
+ field.type(), projection.getFieldIndex(field.name()));
}
boolean contains(IndexedSplit split, long id) {
@@ -554,9 +754,10 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
return false;
}
- CloseableIterator<InternalRow> rows(IndexedSplit split) throws
IOException {
+ CloseableIterator<InternalRow> rows(IndexedSplit split, RowType
projection)
+ throws IOException {
return table.newReadBuilder()
- .withReadType(readType)
+ .withReadType(projection)
.newRead()
.createReader(split)
.toCloseableIterator();
@@ -576,19 +777,16 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
.withCheckFromSnapshot(snapshotId);
}
- byte[] finish(GlobalIndexSingleColumnWriter writer, String modelId,
int centroid)
- throws IOException {
+ byte[] finish(List<ResultEntry> entries) throws IOException {
List<IndexFileMeta> files =
GlobalIndexBuilderUtils.toIndexFileMetas(
table.fileIO(),
table.store().pathFactory().globalIndexFileFactory(),
table.coreOptions(),
rowRange,
- Collections.singletonList(field),
+ indexFields,
indexType,
- writer.finish().stream()
- .map(file -> CentroidIndexMeta.shard(file,
modelId, centroid))
- .collect(Collectors.toList()),
+ entries,
sourceMeta());
return new CommitMessageSerializer().serialize(message(files));
}
@@ -597,6 +795,7 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
private static final class VectorRows implements Iterator<InternalRow>,
Closeable {
private final BuildContext context;
private final Iterator<byte[]> splits;
+ private final RowType projection;
private final int vectorPosition;
private final int idPosition;
private CloseableIterator<InternalRow> rows;
@@ -604,11 +803,12 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
private InternalRow next;
private boolean closed;
- VectorRows(BuildContext context, Iterator<byte[]> splits) {
+ VectorRows(BuildContext context, Iterator<byte[]> splits, RowType
projection) {
this.context = context;
this.splits = splits;
- this.vectorPosition =
context.readType.getFieldIndex(context.field.name());
- this.idPosition = context.rowIdPosition();
+ this.projection = projection;
+ this.vectorPosition =
projection.getFieldIndex(context.field.name());
+ this.idPosition =
projection.getFieldIndex(SpecialFields.ROW_ID.name());
closeOnTaskCompletion(this);
}
@@ -635,7 +835,7 @@ public class CentroidGlobalIndexTopoBuilder implements
GlobalIndexTopologyBuilde
InstantiationUtil.deserializeObject(
splits.next(),
CentroidGlobalIndexTopoBuilder.class.getClassLoader());
- rows = context.rows(split);
+ rows = context.rows(split, projection);
continue;
}
InternalRow row = rows.next();
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 fb67f24cf5..0fbf071378 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
@@ -20,8 +20,10 @@ package org.apache.paimon.spark.procedure;
import org.apache.paimon.globalindex.GlobalIndexBuilderUtils;
import org.apache.paimon.globalindex.GlobalIndexer;
+import org.apache.paimon.globalindex.bitmap.BitmapGlobalIndexerFactory;
import org.apache.paimon.options.Options;
import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.spark.globalindex.CentroidGlobalIndexTopoBuilder;
import org.apache.paimon.spark.globalindex.GlobalIndexTopologyBuilder;
import org.apache.paimon.spark.globalindex.GlobalIndexTopologyBuilderUtils;
import org.apache.paimon.spark.utils.SparkProcedureUtils;
@@ -31,9 +33,13 @@ 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.paimon.utils.JsonSerdeUtil;
import org.apache.paimon.utils.ProcedureUtils;
import org.apache.paimon.utils.StringUtils;
+import
org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.DeserializationFeature;
+import
org.apache.paimon.shade.jackson2.com.fasterxml.jackson.databind.JsonNode;
+
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.connector.catalog.Identifier;
import org.apache.spark.sql.connector.catalog.TableCatalog;
@@ -45,9 +51,12 @@ import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -68,7 +77,8 @@ public class CreateGlobalIndexProcedure extends BaseProcedure
{
ProcedureParameter.required("index_column",
DataTypes.StringType),
ProcedureParameter.required("index_type",
DataTypes.StringType),
ProcedureParameter.optional("partitions", StringType),
- ProcedureParameter.optional("options", DataTypes.StringType)
+ ProcedureParameter.optional("options", DataTypes.StringType),
+ ProcedureParameter.optional("extra_fields", StringType)
};
private static final StructType OUTPUT_TYPE =
@@ -106,6 +116,37 @@ public class CreateGlobalIndexProcedure extends
BaseProcedure {
return new Options(tableOptions, parsedOptions);
}
+ private static List<DataField> parseExtraFields(
+ String json, RowType rowType, DataField vectorField) throws
IOException {
+ JsonNode fields =
+ JsonSerdeUtil.OBJECT_MAPPER_INSTANCE
+ .reader()
+ .with(
+
DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY,
+ DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .readTree(json);
+ checkArgument(
+ fields != null && fields.isObject(),
+ "extra_fields must be a JSON object mapping column names to
index types.");
+ List<DataField> extraFields = new ArrayList<>();
+ Iterator<Map.Entry<String, JsonNode>> entries = fields.fields();
+ while (entries.hasNext()) {
+ Map.Entry<String, JsonNode> entry = entries.next();
+ String name = entry.getKey();
+ checkArgument(
+ rowType.containsField(name) &&
!name.equals(vectorField.name()),
+ "Invalid extra field '%s'. Specify a separate column in
the table.",
+ name);
+ checkArgument(
+
BitmapGlobalIndexerFactory.IDENTIFIER.equals(entry.getValue().textValue()),
+ "Unsupported index type %s for extra field '%s'. Supported
type: bitmap.",
+ entry.getValue(),
+ name);
+ extraFields.add(rowType.getField(name));
+ }
+ return extraFields;
+ }
+
@Override
public InternalRow[] call(InternalRow args) {
Identifier tableIdent = toIdentifier(args.getString(0),
PARAMETERS[0].name());
@@ -116,6 +157,8 @@ public class CreateGlobalIndexProcedure extends
BaseProcedure {
? null
: args.getString(3);
String optionString = args.isNullAt(4) ? null : args.getString(4);
+ String extraFieldsJson =
+ args.numFields() <= 5 || args.isNullAt(5) ? null :
args.getString(5);
LOG.info(
"Starting to build index for table {} with partitions: {}",
tableIdent, partitions);
@@ -167,20 +210,25 @@ public class CreateGlobalIndexProcedure extends
BaseProcedure {
indexColumns.stream()
.map(rowType::getField)
.collect(Collectors.toList());
- RowType projectedRowType =
rowType.project(indexColumns);
- RowType readRowType =
SpecialFields.rowTypeWithRowId(projectedRowType);
-
Options userOptions = createUserOptions(table,
optionString);
-
GlobalIndexBuilderUtils.validateIndexFields(
indexType, indexFields, userOptions);
-
GlobalIndexTopologyBuilder topoBuilder =
GlobalIndexTopologyBuilderUtils.createTopoBuilder(
indexType,
GlobalIndexer.resolveOptions(
indexType, indexFields,
userOptions));
+ if (extraFieldsJson != null) {
+ checkArgument(
+ topoBuilder instanceof
CentroidGlobalIndexTopoBuilder
+ && indexFields.size() == 1,
+ "extra_fields requires centroid sharding
and one vector column in index_column.");
+ indexFields.addAll(
+ parseExtraFields(extraFieldsJson, rowType,
indexFields.get(0)));
+ }
+ RowType projectedRowType = new
RowType(rowType.isNullable(), indexFields);
+ RowType readRowType =
SpecialFields.rowTypeWithRowId(projectedRowType);
List<CommitMessage> indexResults =
topoBuilder.buildIndex(
spark(),
diff --git
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/DropGlobalIndexProcedure.java
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/DropGlobalIndexProcedure.java
index 3aae599186..2c56c2c2bf 100644
---
a/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/DropGlobalIndexProcedure.java
+++
b/paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/DropGlobalIndexProcedure.java
@@ -20,6 +20,7 @@ package org.apache.paimon.spark.procedure;
import org.apache.paimon.Snapshot;
import org.apache.paimon.data.BinaryRow;
+import org.apache.paimon.globalindex.CentroidIndexMeta;
import org.apache.paimon.index.IndexFileMeta;
import org.apache.paimon.io.CompactIncrement;
import org.apache.paimon.io.DataIncrement;
@@ -156,10 +157,9 @@ public class DropGlobalIndexProcedure extends
BaseProcedure {
entry ->
entry.indexFile().indexType().equals(indexType)
&&
entry.indexFile().globalIndexMeta() != null
- && entry.indexFile()
- .globalIndexMeta()
- .getIndexedFieldIds()
- .equals(indexFieldIds)
+ &&
CentroidIndexMeta.matchesIndexFields(
+
entry.indexFile().globalIndexMeta(),
+ indexFieldIds)
&& (partitionPredicate == null
||
partitionPredicate.test(
entry.partition()));
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 29572fb0bb..334690cfb0 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
@@ -19,6 +19,7 @@
package org.apache.paimon.spark.sql
import org.apache.paimon.data.{GenericArray, GenericRow}
+import org.apache.paimon.predicate.PredicateBuilder
import org.apache.paimon.spark.PaimonSparkTestBase
import org.apache.spark.SparkConf
@@ -32,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>) TBLPROPERTIES (
+ spark.sql("""CREATE TABLE T (v ARRAY<FLOAT>, tag INT) TBLPROPERTIES (
|'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true',
|'global-index.row-count-per-shard'='8')""".stripMargin)
val table = loadTable("T")
@@ -41,7 +42,7 @@ class CentroidKryoBuildTest extends PaimonSparkTestBase {
val commit = builder.newCommit()
try {
(0 until 32).foreach(
- i => write.write(GenericRow.of(new GenericArray(Array(i.toFloat,
1f)))))
+ i => write.write(GenericRow.of(new GenericArray(Array(i.toFloat,
1f)), Int.box(i))))
commit.commit(write.prepareCommit())
} finally {
write.close()
@@ -58,6 +59,19 @@ class CentroidKryoBuildTest extends PaimonSparkTestBase {
.withLimit(1)
.executeLocal()
assert(result.results().toArray(1).toSeq == Seq(7L))
+ spark.sql(
+ """CALL sys.create_global_index(table=>'test.T',index_column=>'v',
+ |index_type=>'ivf-flat',
+ |extra_fields=>'{"tag":"bitmap"}',
+
|options=>'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.metric=l2,ivf-flat.centroid.nlist=2')""".stripMargin)
+ val filtered = table
+ .newVectorSearchBuilder()
+ .withVectorColumn("v")
+ .withVector(Array(0f, 1f))
+ .withLimit(1)
+ .withFilter(new PredicateBuilder(table.rowType()).equal(1, Int.box(7)))
+ .executeLocal()
+ assert(filtered.results().toArray(1).toSeq == Seq(7L))
}
}
}
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 306e241623..ac2055229d 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
@@ -22,6 +22,7 @@ import
org.apache.paimon.append.dataevolution.DataEvolutionRowIdReassigner
import org.apache.paimon.globalindex.{CentroidIndexFile, CentroidIndexMeta}
import org.apache.paimon.index.IndexFileMeta
import org.apache.paimon.spark.PaimonSparkTestBase
+import org.apache.paimon.table.source.RawVectorSearchSplit
import org.apache.paimon.vector.index.VectorTrainingModelIO
import scala.collection.JavaConverters._
@@ -29,6 +30,150 @@ import scala.collection.JavaConverters._
/** End-to-end centroid build over nonzero, disjoint source row-ID ranges. */
class CentroidVectorIndexTest extends PaimonSparkTestBase {
+ test("centroid bitmap fields pre-filter top K and follow the vector
definition") {
+ withTable("T") {
+ spark.sql("""CREATE TABLE T (id INT, v ARRAY<FLOAT>, tenant STRING,
status STRING)
+ |TBLPROPERTIES (
+ |'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true',
+ |'global-index.row-count-per-shard'='128',
+ |'vector-index.search-mode'='detail',
+
|'vector-index.post-filter.candidates-factor'='1')""".stripMargin)
+ spark.sql("""INSERT INTO T SELECT cast(id AS INT),
+ |array(cast(IF(id < 32, id, id + 1000) AS FLOAT), 0.0f),
+ |IF(id % 2 = 0, 'red', 'blue'),
+ |CASE WHEN id = 48 THEN NULL ELSE 'busy' END FROM
range(64)""".stripMargin)
+ def build(extraFields: String = "", sharding: String = "centroid"): Unit
= {
+ val extra = if (extraFields.isEmpty) "" else s", extra_fields =>
'$extraFields'"
+ spark
+ .sql(
+ s"""CALL sys.create_global_index(table=>'test.T',index_column=>'v',
+ |index_type=>'ivf-flat',
options=>'ivf-flat.sharding=$sharding,ivf-flat.dimension=2,
+
|ivf-flat.metric=l2,ivf-flat.centroid.nlist=2,ivf-flat.nlist=1'$extra)""".stripMargin
+ .replace("\n", ""))
+ .collect()
+ }
+ def files: Seq[IndexFileMeta] = {
+ val table = loadTable("T")
+ table
+ .store()
+ .newIndexFileHandler()
+ .scan(table.snapshotManager().latestSnapshot(), "ivf-flat")
+ .asScala
+ .map(_.indexFile())
+ .toSeq
+ }
+ def nearest(predicate: String): Seq[Int] =
+ spark
+ .sql(s"""SELECT id FROM vector_search('T','v',array(0.0f,0.0f),1,
+ |map('centroid.nprobe','2','ivf.nprobe','1')) WHERE
$predicate""".stripMargin)
+ .collect()
+ .map(_.getInt(0))
+ .toSeq
+
+ build()
+ assert(nearest("status IS NULL").isEmpty)
+
+ def assertBuildRejected(
+ fields: String,
+ message: String,
+ sharding: String = "centroid"): Unit = {
+ val previousFiles = files.map(_.fileName()).toSet
+ val error = intercept[Exception](build(fields, sharding))
+ assert(
+ Iterator
+ .iterate[Throwable](error)(_.getCause)
+ .takeWhile(_ != null)
+ .exists(e => Option(e.getMessage).exists(_.contains(message))))
+ assert(files.map(_.fileName()).toSet == previousFiles)
+ }
+ assertBuildRejected("""{"status":"btree"}""", "Unsupported index type")
+ assertBuildRejected("""{"status":"bitmap","status":"bitmap"}""",
"Duplicate field")
+ assertBuildRejected("""{"status":"bitmap"}""", "requires centroid
sharding", "range")
+
+ 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")
+ .newVectorSearchBuilder()
+ .withVectorColumn("v")
+ .withVector(Array(0f, 0f))
+ .withLimit(1)
+ .newVectorScan()
+ .scan()
+
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)
+
+ build("""{"status":"bitmap"}""")
+ assert(files.count(CentroidIndexMeta.isRoutingModel) == 1)
+ assert(files.forall(_.globalIndexMeta().extraFieldIds().length == 1))
+ assert(nearest("status IS NULL") == Seq(48))
+ for (inReader <- Seq(false, true)) {
+ spark.sql(
+ s"ALTER TABLE T SET TBLPROPERTIES
('global-index.query-in-reader.enabled'='$inReader')")
+ assert(
+ spark.sql("SELECT id FROM T WHERE status IS
NULL").collect().map(_.getInt(0)).toSeq ==
+ Seq(48))
+ }
+
+ intercept[Exception] {
+ spark.sql("UPDATE T SET status = 'ready' WHERE id = 48").collect()
+ }
+ assert(nearest("status IS NULL") == Seq(48))
+ spark.sql("ALTER TABLE T SET TBLPROPERTIES
('global-index.column-update-action'='IGNORE')")
+ intercept[Exception] {
+ spark.sql("UPDATE T SET status = 'ready' WHERE id = 48").collect()
+ }
+ spark.sql(
+ "ALTER TABLE T SET TBLPROPERTIES
('global-index.column-update-action'='DROP_PARTITION_INDEX')")
+ spark.sql("UPDATE T SET status = 'ready' WHERE id = 48").collect()
+ assert(files.isEmpty)
+
+ build("""{"status":"bitmap"}""")
+ assert(nearest("status = 'ready'") == Seq(48))
+ val centroidFiles = files.map(_.fileName()).toSet
+ spark.sql("INSERT INTO T VALUES (64, array(2000.0f, 0.0f), 'red',
'new')").collect()
+ build(sharding = "range")
+ assert(centroidFiles.subsetOf(files.map(_.fileName()).toSet))
+ assert(files.size == centroidFiles.size + 1)
+ assert(nearest("status = 'ready'") == Seq(48))
+ spark
+ .sql("""CALL sys.drop_global_index(table=>'test.T',index_column=>'v',
+ |index_type=>'ivf-flat')""".stripMargin)
+ .collect()
+ assert(files.isEmpty)
+ }
+ }
+
+ 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)
+ |PARTITIONED BY (p) TBLPROPERTIES (
+ |'bucket'='-1', 'row-tracking.enabled'='true',
'data-evolution.enabled'='true',
+ |'global-index.thread-num'='1',
+
|'vector-index.post-filter.candidates-factor'='1')""".stripMargin)
+ spark.sql(
+ """INSERT INTO T VALUES
+ |(0, array(0.0f, 0.0f), 'near', 0), (1, array(1.0f, 0.0f), NULL, 0),
+ |(2, array(0.0f, 0.0f), 'near', 1), (3, array(2.0f, 0.0f), NULL,
1)""".stripMargin)
+ spark
+ .sql("""CALL sys.create_global_index(
+ |table => 'test.T', index_column => 'v', index_type =>
'ivf-flat',
+ |options =>
'ivf-flat.sharding=centroid,ivf-flat.dimension=2,ivf-flat.metric=l2,ivf-flat.centroid.nlist=1',
+ |extra_fields => '{"status":"bitmap"}')""".stripMargin)
+ .collect()
+ withSparkSQLConf("spark.paimon.vector-search.distribute.enabled" ->
"true") {
+ val ids = spark
+ .sql("""SELECT id FROM vector_search('T','v',array(0.0f,0.0f),1,
+ |map('centroid.nprobe','1','ivf.nprobe','1')) WHERE status IS
NULL""".stripMargin)
+ .collect()
+ .map(_.getInt(0))
+ assert(ids.toSeq == Seq(1))
+ }
+ }
+ }
+
private def build(): Unit = {
spark
.sql(
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 a5bc0a0c93..cd9d5e649b 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
@@ -21,6 +21,7 @@ package org.apache.paimon.vector.index;
import org.apache.paimon.fs.SeekableInputStream;
import org.apache.paimon.globalindex.AbstractVectorGlobalIndexReader;
import org.apache.paimon.globalindex.CentroidIndexFile;
+import org.apache.paimon.globalindex.CentroidShardFilterReader;
import org.apache.paimon.globalindex.GlobalIndexIOMeta;
import org.apache.paimon.globalindex.ScoreGetter;
import org.apache.paimon.globalindex.ScoredGlobalIndexResult;
@@ -56,7 +57,8 @@ 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 {
+final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexReader
+ implements CentroidShardFilterReader {
private static final int JOINT_OUTER_PROBES = 4;
private static final int[] NO_CENTERS = new int[0];
@@ -72,6 +74,7 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
private final long vectorCount;
private final String indexType;
private CentroidRouter model;
+ private IOFunction<Integer, RoaringNavigableMap64> shardFilter;
private volatile boolean closed;
NativeCentroidRoutedIndexReader(
@@ -89,6 +92,9 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
long count = 0;
for (GlobalIndexIOMeta file : entries) {
CentroidIndexFile meta = (CentroidIndexFile) file;
+ if (meta.scalarIndex()) {
+ continue;
+ }
if (meta.routingModel()) {
modelMeta = meta;
checkArgument(routing == null, "Multiple routing models.");
@@ -113,6 +119,11 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
this.vectorCount = count;
}
+ @Override
+ public void withShardFilter(IOFunction<Integer, RoaringNavigableMap64>
filter) {
+ this.shardFilter = filter;
+ }
+
private synchronized CentroidRouter model() {
checkArgument(!closed, "Centroid reader is closed.");
if (model == null) {
@@ -147,13 +158,7 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
GlobalIndexIOMeta shard, IOFunction<NativeVectorGlobalIndexReader,
T> operation) {
return CompletableFuture.supplyAsync(
() -> {
- try (NativeVectorGlobalIndexReader reader =
- new NativeVectorGlobalIndexReader(
- files,
- Collections.singletonList(shard),
- fieldType,
- executor,
- indexType)) {
+ try (NativeVectorGlobalIndexReader reader =
openShard(shard)) {
return operation.apply(reader);
} catch (IOException e) {
throw new UncheckedIOException(e);
@@ -162,6 +167,11 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
executor);
}
+ private NativeVectorGlobalIndexReader openShard(GlobalIndexIOMeta shard) {
+ return new NativeVectorGlobalIndexReader(
+ files, Collections.singletonList(shard), fieldType, executor,
indexType);
+ }
+
private synchronized String metric() {
if (metric == null) {
model();
@@ -267,7 +277,8 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
VectorSearch query = batch.forIndex(0);
SearchScope scope = SearchScope.of(batch.includeRowIds(),
batch.limit());
boolean considerJoint =
- centers.get(0).length == 8
+ shardFilter == null
+ && centers.get(0).length == 8
&& metadata.nlist() == 64
&& query.limit() >= 10
&& query.limit() <= 100
@@ -495,31 +506,48 @@ final class NativeCentroidRoutedIndexReader extends
AbstractVectorGlobalIndexRea
groups.forEach(
(file, policies) ->
pending.add(
- readShard(
- file,
- reader -> {
- // A mixed batch may select this
shard with both probe
- // policies.
- for (Map.Entry<Boolean,
List<Integer>> policy :
- policies.entrySet()) {
- List<Integer> indices =
policy.getValue();
- searchSubset(
- reader,
- batch,
- scope,
- indices,
- policy.getKey(),
- (index, result) ->
-
plans.get(index)
-
.matches
-
.add(result));
- }
- return null;
- })));
+ CompletableFuture.runAsync(
+ () -> searchShard(file, policies,
batch, plans, scope),
+ executor)));
return CompletableFuture.allOf(pending.toArray(new
CompletableFuture[0]))
.thenComposeAsync(done -> finishRound(batch, plans, scope));
}
+ private void searchShard(
+ GlobalIndexIOMeta file,
+ Map<Boolean, List<Integer>> policies,
+ BatchVectorSearch batch,
+ List<Route> plans,
+ SearchScope scope) {
+ try {
+ if (shardFilter != null) {
+ RoaringNavigableMap64 rows =
+ shardFilter.apply(((CentroidIndexFile)
file).centroid());
+ if (batch.includeRowIds() != null) {
+ rows.and(batch.includeRowIds());
+ }
+ if (rows.isEmpty()) {
+ return;
+ }
+ scope = SearchScope.of(rows, batch.limit());
+ }
+ try (NativeVectorGlobalIndexReader reader = openShard(file)) {
+ // A mixed batch may select this shard with both probe
policies.
+ for (Map.Entry<Boolean, List<Integer>> policy :
policies.entrySet()) {
+ searchSubset(
+ reader,
+ batch,
+ scope,
+ policy.getValue(),
+ policy.getKey(),
+ (index, result) ->
plans.get(index).matches.add(result));
+ }
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
private Map<GlobalIndexIOMeta, Map<Boolean, List<Integer>>>
shardsForRound(List<Route> plans) {
Map<GlobalIndexIOMeta, Map<Boolean, List<Integer>>> groups = new
LinkedHashMap<>();
if (plans.stream()
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 118d361e9e..4314beeea9 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
@@ -26,6 +26,7 @@ import org.apache.paimon.fs.SeekableInputStreamWrapper;
import org.apache.paimon.fs.local.LocalFileIO;
import org.apache.paimon.globalindex.CentroidIndexFile;
import org.apache.paimon.globalindex.CentroidIndexMeta;
+import org.apache.paimon.globalindex.CentroidShardFilterReader;
import org.apache.paimon.globalindex.CentroidVectorGlobalIndexer.TrainingBatch;
import org.apache.paimon.globalindex.GlobalIndexIOMeta;
import org.apache.paimon.globalindex.GlobalIndexReader;
@@ -515,6 +516,34 @@ class CentroidVectorGlobalIndexTest {
.hasRootCauseInstanceOf(IllegalArgumentException.class);
}
+ try (GlobalIndexReader pruning =
+ indexer.createReader(fileReader, metas, rowCount, null,
executor)) {
+ int expectedCentroid = centroidByRow[200];
+ ((CentroidShardFilterReader) pruning)
+ .withShardFilter(
+ centroid -> {
+ RoaringNavigableMap64 matches = new
RoaringNavigableMap64();
+ if (centroid == expectedCentroid) {
+ matches.add(101L * 200);
+ }
+ return matches;
+ });
+ opened.clear();
+ BatchVectorSearch query =
+ new BatchVectorSearch(
+ queries, 1, "v",
Collections.singletonMap("centroid.nprobe", "4"));
+ assertThat(pruning.visitBatchVectorSearch(query).get(30,
TimeUnit.SECONDS))
+ .allSatisfy(
+ result ->
+ assertThat(result.get().results())
+ .containsExactly(101L * 200));
+ assertThat(opened).hasSize(2);
+ for (GlobalIndexIOMeta file : metas.subList(1, metas.size())) {
+ assertThat(opened.containsKey(file.filePath()))
+ .isEqualTo(((CentroidIndexFile) file).centroid()
== expectedCentroid);
+ }
+ }
+
RoaringNavigableMap64 include = new RoaringNavigableMap64();
include.add(BASE - 1);
include.add(BASE + 101L * 200);