steFaiz commented on code in PR #8834:
URL: https://github.com/apache/paimon/pull/8834#discussion_r3643502425


##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/vectorsearch/FlinkDataEvolutionVectorRead.java:
##########
@@ -0,0 +1,596 @@
+/*
+ * 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.flink.vectorsearch;
+
+import org.apache.paimon.flink.utils.StreamExecutionEnvironmentUtils;
+import org.apache.paimon.globalindex.GlobalIndexReadThreadPool;
+import org.apache.paimon.globalindex.GlobalIndexResult;
+import org.apache.paimon.globalindex.GlobalIndexResultSerializer;
+import org.apache.paimon.globalindex.GlobalIndexer;
+import org.apache.paimon.globalindex.ScoredGlobalIndexResult;
+import org.apache.paimon.index.IndexPathFactory;
+import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.predicate.Predicate;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.source.DataEvolutionVectorRead;
+import org.apache.paimon.table.source.IndexVectorSearchSplit;
+import org.apache.paimon.table.source.RawVectorSearchSplit;
+import org.apache.paimon.table.source.VectorScan;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.utils.InstantiationUtil;
+import org.apache.paimon.utils.Range;
+import org.apache.paimon.utils.RoaringNavigableMap64;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.typeinfo.PrimitiveArrayTypeInfo;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.util.CloseableIterator;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+
+import static org.apache.paimon.CoreOptions.GLOBAL_INDEX_THREAD_NUM;
+import static org.apache.paimon.utils.Preconditions.checkNotNull;
+
+/** Flink-aware {@link DataEvolutionVectorRead}. */
+public class FlinkDataEvolutionVectorRead extends DataEvolutionVectorRead {
+
+    private static final long serialVersionUID = 1L;
+    private static final byte INDEX_RESULT = 0;
+    private static final byte RAW_RESULT = 1;
+
+    private final transient StreamExecutionEnvironment env;
+
+    public FlinkDataEvolutionVectorRead(
+            FileStoreTable table,
+            @Nullable PartitionPredicate partitionFilter,
+            @Nullable Predicate filter,
+            int limit,
+            DataField vectorColumn,
+            float[] vector,
+            @Nullable Map<String, String> options,
+            StreamExecutionEnvironment env) {
+        super(table, partitionFilter, filter, limit, vectorColumn, vector, 
options);
+        this.env = checkNotNull(env);
+    }
+
+    @Override
+    public GlobalIndexResult read(VectorScan.Plan plan) {
+        List<IndexVectorSearchSplit> indexSplits = new ArrayList<>();
+        List<RawVectorSearchSplit> rawSplits = new ArrayList<>();
+        splitSearchSplits(plan.splits(), indexSplits, rawSplits);
+        if (indexSplits.isEmpty() && rawSplits.isEmpty()) {
+            return GlobalIndexResult.createEmpty();
+        }
+
+        GlobalIndexer globalIndexer =
+                !indexSplits.isEmpty() && !rawSplits.isEmpty()
+                        ? createGlobalIndexer(indexSplits)
+                        : null;
+        if (!indexSplits.isEmpty() && !rawSplits.isEmpty()) {
+            int parallelism = flinkParallelism();
+            List<Range> rawRowRanges = rawRowRanges(rawSplits);
+            if (indexSplits.size() >= parallelism * 2L

Review Comment:
   Thanks, can u explain why hard-code '2' as the factor of indexSplits size 
and row count num here? Can we make it configurable? Or maybe we can merge some 
small splits of low cardianlity to a single task



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/vectorsearch/FlinkDataEvolutionVectorRead.java:
##########
@@ -0,0 +1,596 @@
+/*
+ * 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.flink.vectorsearch;
+
+import org.apache.paimon.flink.utils.StreamExecutionEnvironmentUtils;
+import org.apache.paimon.globalindex.GlobalIndexReadThreadPool;
+import org.apache.paimon.globalindex.GlobalIndexResult;
+import org.apache.paimon.globalindex.GlobalIndexResultSerializer;
+import org.apache.paimon.globalindex.GlobalIndexer;
+import org.apache.paimon.globalindex.ScoredGlobalIndexResult;
+import org.apache.paimon.index.IndexPathFactory;
+import org.apache.paimon.partition.PartitionPredicate;
+import org.apache.paimon.predicate.Predicate;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.source.DataEvolutionVectorRead;
+import org.apache.paimon.table.source.IndexVectorSearchSplit;
+import org.apache.paimon.table.source.RawVectorSearchSplit;
+import org.apache.paimon.table.source.VectorScan;
+import org.apache.paimon.types.DataField;
+import org.apache.paimon.utils.InstantiationUtil;
+import org.apache.paimon.utils.Range;
+import org.apache.paimon.utils.RoaringNavigableMap64;
+
+import org.apache.flink.api.common.functions.MapFunction;
+import org.apache.flink.api.common.typeinfo.PrimitiveArrayTypeInfo;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.util.CloseableIterator;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+
+import static org.apache.paimon.CoreOptions.GLOBAL_INDEX_THREAD_NUM;
+import static org.apache.paimon.utils.Preconditions.checkNotNull;
+
+/** Flink-aware {@link DataEvolutionVectorRead}. */
+public class FlinkDataEvolutionVectorRead extends DataEvolutionVectorRead {
+
+    private static final long serialVersionUID = 1L;
+    private static final byte INDEX_RESULT = 0;
+    private static final byte RAW_RESULT = 1;
+
+    private final transient StreamExecutionEnvironment env;
+
+    public FlinkDataEvolutionVectorRead(
+            FileStoreTable table,
+            @Nullable PartitionPredicate partitionFilter,
+            @Nullable Predicate filter,
+            int limit,
+            DataField vectorColumn,
+            float[] vector,
+            @Nullable Map<String, String> options,
+            StreamExecutionEnvironment env) {
+        super(table, partitionFilter, filter, limit, vectorColumn, vector, 
options);
+        this.env = checkNotNull(env);
+    }
+
+    @Override
+    public GlobalIndexResult read(VectorScan.Plan plan) {
+        List<IndexVectorSearchSplit> indexSplits = new ArrayList<>();
+        List<RawVectorSearchSplit> rawSplits = new ArrayList<>();
+        splitSearchSplits(plan.splits(), indexSplits, rawSplits);
+        if (indexSplits.isEmpty() && rawSplits.isEmpty()) {
+            return GlobalIndexResult.createEmpty();
+        }
+
+        GlobalIndexer globalIndexer =
+                !indexSplits.isEmpty() && !rawSplits.isEmpty()
+                        ? createGlobalIndexer(indexSplits)
+                        : null;
+        if (!indexSplits.isEmpty() && !rawSplits.isEmpty()) {
+            int parallelism = flinkParallelism();
+            List<Range> rawRowRanges = rawRowRanges(rawSplits);
+            if (indexSplits.size() >= parallelism * 2L
+                    && rawRowCount(rawRowRanges) >= parallelism * 2L) {
+                return readIndexAndRawSplitsInFlink(
+                        indexSplits,
+                        rawSplits,
+                        rawRowRanges,
+                        globalIndexer,
+                        rawPreFilter(rawSplits),
+                        parallelism);
+            }
+        }
+
+        ScoredGlobalIndexResult indexed =
+                indexSplits.isEmpty()
+                        ? ScoredGlobalIndexResult.createEmpty()
+                        : readIndexSplitsInFlink(indexSplits, globalIndexer);
+        ScoredGlobalIndexResult raw =
+                readRawSplitsInFlink(rawSplits, globalIndexer, 
rawPreFilter(rawSplits));
+        return indexed.or(raw).topK(limit);
+    }
+
+    protected ScoredGlobalIndexResult readIndexSplitsInFlink(
+            List<IndexVectorSearchSplit> splits, @Nullable GlobalIndexer 
globalIndexer) {
+        if (splits.isEmpty()) {
+            return ScoredGlobalIndexResult.createEmpty();
+        }
+
+        int parallelism = flinkParallelism();
+        if (splits.size() < parallelism * 2L) {
+            return readIndexed(
+                    splits, globalIndexer == null ? 
createGlobalIndexer(splits) : globalIndexer);
+        }
+
+        List<RoaringNavigableMap64> preFilters = preFilters(splits);
+        String indexType = vectorIndexType(splits);
+        int searchLimit = indexedSearchLimit(indexType);
+        List<List<SerializedSplit>> splitGroups = indexSplitGroups(splits, 
preFilters, parallelism);
+        List<byte[]> remoteResults =
+                executeIndexSearchGroups(splitGroups, searchLimit, 
parallelism);
+        GlobalIndexer rerankGlobalIndexer =
+                globalIndexer == null ? createGlobalIndexer(splits) : 
globalIndexer;
+        return maybeRerankIndexedResult(
+                mergeRemoteResults(remoteResults, searchLimit),
+                indexType,
+                rerankGlobalIndexer,
+                vector);
+    }
+
+    private List<List<SerializedSplit>> indexSplitGroups(
+            List<IndexVectorSearchSplit> splits,
+            List<RoaringNavigableMap64> preFilters,
+            int parallelism) {
+        List<SerializedSplit> serializedSplits = new 
ArrayList<>(splits.size());
+        for (int i = 0; i < splits.size(); i++) {
+            try {
+                IndexVectorSearchSplit split = splits.get(i);
+                RoaringNavigableMap64 preFilter = preFilters.isEmpty() ? null 
: preFilters.get(i);
+                serializedSplits.add(
+                        new SerializedSplit(
+                                InstantiationUtil.serializeObject(split),
+                                preFilter == null
+                                        ? null
+                                        : 
InstantiationUtil.serializeObject(preFilter)));
+            } catch (IOException e) {
+                throw new RuntimeException("Failed to serialize vector-search 
split.", e);
+            }
+        }
+        return splitGroups(serializedSplits, parallelism);
+    }
+
+    protected ScoredGlobalIndexResult readRawSplitsInFlink(
+            List<RawVectorSearchSplit> splits,
+            @Nullable GlobalIndexer globalIndexer,
+            @Nullable RoaringNavigableMap64 preFilter) {
+        List<Range> rawRowRanges = rawRowRanges(splits);
+        if (rawRowRanges.isEmpty()) {
+            return ScoredGlobalIndexResult.createEmpty();
+        }
+
+        int parallelism = flinkParallelism();
+        if (rawRowCount(rawRowRanges) < parallelism * 2L) {
+            return readRawSearch(
+                    rawRowRanges, preFilter, rawSearchIndexer(splits, 
globalIndexer), vector);
+        }
+
+        String metric = rawSearchMetric(rawSearchIndexer(splits, 
globalIndexer));
+        List<List<SerializedSplit>> splitGroups =
+                rawSplitGroups(rawRowRanges, preFilter, parallelism);
+        List<byte[]> remoteResults = executeRawSearchGroups(splitGroups, 
metric, parallelism);
+        return mergeRemoteResults(remoteResults, limit);
+    }
+
+    private List<List<SerializedSplit>> rawSplitGroups(
+            List<Range> rawRowRanges, @Nullable RoaringNavigableMap64 
preFilter, int parallelism) {
+        List<List<Range>> rangeGroups = rangeGroups(rawRowRanges, parallelism);
+        List<SerializedSplit> serializedSplits = new 
ArrayList<>(rangeGroups.size());
+        for (List<Range> rangeGroup : rangeGroups) {
+            try {
+                RoaringNavigableMap64 groupPreFilter = 
groupPreFilter(rangeGroup, preFilter);
+                serializedSplits.add(
+                        new SerializedSplit(
+                                InstantiationUtil.serializeObject(rangeGroup),
+                                groupPreFilter == null
+                                        ? null
+                                        : 
InstantiationUtil.serializeObject(groupPreFilter)));
+            } catch (IOException e) {
+                throw new RuntimeException("Failed to serialize raw vector row 
ranges.", e);
+            }
+        }
+        return splitGroups(serializedSplits, parallelism);
+    }
+
+    @Nullable
+    private RoaringNavigableMap64 groupPreFilter(
+            List<Range> rangeGroup, @Nullable RoaringNavigableMap64 preFilter) 
{
+        if (preFilter == null) {
+            return null;
+        }
+
+        RoaringNavigableMap64 groupRows = new RoaringNavigableMap64();
+        for (Range range : rangeGroup) {
+            groupRows.addRange(range);
+        }
+        groupRows.and(preFilter);
+        if (groupRows.getLongCardinality() == rawRowCount(rangeGroup)) {
+            return null;
+        }
+        groupRows.runOptimize();
+        return groupRows;
+    }
+
+    private ScoredGlobalIndexResult readIndexAndRawSplitsInFlink(
+            List<IndexVectorSearchSplit> indexSplits,
+            List<RawVectorSearchSplit> rawSplits,
+            List<Range> rawRowRanges,
+            GlobalIndexer globalIndexer,
+            @Nullable RoaringNavigableMap64 rawPreFilter,
+            int parallelism) {
+        String indexType = vectorIndexType(indexSplits);
+        int searchLimit = indexedSearchLimit(indexType);
+        List<List<SerializedSplit>> indexGroups =
+                indexSplitGroups(indexSplits, preFilters(indexSplits), 
parallelism);
+
+        String rawMetric = rawSearchMetric(rawSearchIndexer(rawSplits, 
globalIndexer));
+        List<List<SerializedSplit>> rawGroups =
+                rawSplitGroups(rawRowRanges, rawPreFilter, parallelism);
+
+        List<byte[]> taggedResults =
+                executeIndexAndRawSearchGroups(
+                        indexGroups, searchLimit, rawGroups, rawMetric, 
parallelism);
+        List<byte[]> indexedResults = new ArrayList<>();
+        List<byte[]> rawResults = new ArrayList<>();
+        for (byte[] taggedResult : taggedResults) {
+            if (taggedResult.length == 0) {

Review Comment:
   This is a dangerous action. Add one byte to the serialized bytes without any 
code-level specification, then strip the first byte on read. I think we could 
add a new column, or just  
   introduce a format for this field, then deal with the read & write in a 
single format class, to make sure the read/write format is aligned.



##########
paimon-flink/paimon-flink-common/src/main/java/org/apache/paimon/flink/procedure/VectorSearchProcedure.java:
##########
@@ -90,89 +110,418 @@ public String[] call(
             String queryVectorStr,
             Integer topK,
             String projection,
-            String options)
+            String options,
+            String where,
+            String partitions)
             throws Exception {
-        Table table = table(tableId);
+        validateSearch(vectorColumn, queryVectorStr, topK);
 
+        Table table = table(tableId);
         Map<String, String> optionsMap = optionalConfigMap(options);
+        String queryAuthOption = CoreOptions.QUERY_AUTH_ENABLED.key();
+        checkArgument(
+                !optionsMap.containsKey(queryAuthOption),
+                "Option '%s' is not allowed",
+                queryAuthOption);
         if (!optionsMap.isEmpty()) {
             table = table.copy(optionsMap);
         }
+        checkArgument(
+                table instanceof FileStoreTable, "Vector search requires a 
file store table.");
+
+        FileStoreTable fileStoreTable = (FileStoreTable) table;
+        checkArgument(
+                !fileStoreTable.coreOptions().queryAuthEnabled(),
+                "Vector search does not support tables with query auth 
enabled.");
+        RowType tableType = fileStoreTable.rowType();
+        checkArgument(
+                tableType.containsField(vectorColumn),
+                "Vector column '%s' does not exist in table '%s'.",
+                vectorColumn,
+                tableId);
+        checkArgument(
+                tableType.notContainsField(SEARCH_SCORE),
+                "Table column '%s' conflicts with vector-search metadata.",
+                SEARCH_SCORE);
 
         float[] queryVector = parseVector(queryVectorStr);
+        Predicate filter = parseFilter(where, tableType);
+        PartitionPredicate partitionFilter = parsePartitions(partitions, 
fileStoreTable);
+        Projection parsedProjection = Projection.parse(projection, tableType, 
filter);
+        FilterParts filterParts = FilterParts.from(filter, fileStoreTable);
+        validatePrimaryKeyFilter(fileStoreTable, vectorColumn, filterParts);
+
+        fileStoreTable = resolveAndPinSnapshot(fileStoreTable);
+        if (fileStoreTable == null) {
+            return new String[0];
+        }
 
-        GlobalIndexResult result =
-                table.newVectorSearchBuilder()
+        VectorSearchBuilder builder =
+                newVectorSearchBuilder(procedureContext, fileStoreTable)
                         .withVector(queryVector)
                         .withVectorColumn(vectorColumn)
                         .withLimit(topK)
-                        .withOptions(optionsMap)
-                        .executeLocal();
+                        .withOptions(optionsMap);
+        if (filter != null) {
+            builder.withFilter(filter);
+        }
+        if (partitionFilter != null) {
+            builder.withPartitionFilter(partitionFilter);
+        }
+
+        VectorScan.Plan vectorPlan = builder.newVectorScan().scan();
+        GlobalIndexResult result = builder.newVectorRead().read(vectorPlan);
+
+        ReadBuilder readBuilder = fileStoreTable.newReadBuilder();
+        if (filter != null) {
+            readBuilder.withFilter(filter);
+        }
+        PartitionPredicate effectivePartitionFilter =
+                filterParts.mergePartitionFilter(partitionFilter);
+        if (effectivePartitionFilter != null) {
+            readBuilder.withPartitionFilter(effectivePartitionFilter);
+        }
+        if (parsedProjection.readProjection != null) {
+            readBuilder.withProjection(parsedProjection.readProjection);
+        }
+        TableScan.Plan readPlan = 
readBuilder.newScan().withGlobalIndexResult(result).plan();
+        return readRows(readBuilder, readPlan, parsedProjection);
+    }
+
+    private static VectorSearchBuilder newVectorSearchBuilder(
+            ProcedureContext context, FileStoreTable table) {
+        if (!table.coreOptions().vectorSearchDistributeEnabled()) {
+            return table.newVectorSearchBuilder();
+        }
+        return new FlinkVectorSearchBuilderImpl(table, 
context.getExecutionEnvironment());
+    }
 
-        RowType tableRowType = table.rowType();
-        int[] projectionIndices = parseProjection(projection, tableRowType);
+    @Nullable
+    static FileStoreTable resolveAndPinSnapshot(FileStoreTable table) {
+        Snapshot snapshot = TimeTravelUtil.tryTravelOrLatest(table);
+        if (snapshot == null) {
+            return null;
+        }
+
+        Map<String, String> snapshotOptions = new LinkedHashMap<>();
+        snapshotOptions.put(SCAN_VERSION.key(), null);
+        snapshotOptions.put(SCAN_TAG_NAME.key(), null);
+        snapshotOptions.put(SCAN_WATERMARK.key(), null);
+        snapshotOptions.put(SCAN_TIMESTAMP.key(), null);
+        snapshotOptions.put(SCAN_TIMESTAMP_MILLIS.key(), null);
+        snapshotOptions.put(SCAN_MODE.key(), 
CoreOptions.StartupMode.FROM_SNAPSHOT.toString());
+        snapshotOptions.put(SCAN_SNAPSHOT_ID.key(), 
String.valueOf(snapshot.id()));
+        return table.copyWithoutTimeTravel(snapshotOptions);

Review Comment:
   Why we need to do this copy? If we want to pin a snapshot, we could just 
pass the target snapshot id, not clear all other options and copy the table 
again.
   For example, you can check: 
`org.apache.paimon.flink.dataevolution.DataEvolutionPartialWriteOperator#DataEvolutionPartialWriteOperator`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to