Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.apache.paimon.index.pk.PrimaryKeyIndexSourceFile;
import org.apache.paimon.index.pk.PrimaryKeyIndexSourceMeta;
import org.apache.paimon.options.Options;
import org.apache.paimon.predicate.BatchVectorSearch;
import org.apache.paimon.predicate.VectorSearch;
import org.apache.paimon.types.DataField;
import org.apache.paimon.utils.IOUtils;
Expand Down Expand Up @@ -177,7 +178,7 @@ CompletableFuture<List<PkVectorSearchResult>> searchAsync(
"Vector segment %s has no source metadata.",
segment.fileName());
if (segment.rowCount() == 0) {
return Collections.emptyList();
return CompletableFuture.completedFuture(Collections.emptyList());
}
GlobalIndexer indexer =
GlobalIndexer.create(segment.indexType(), vectorField, indexOptions);
Expand Down Expand Up @@ -231,6 +232,117 @@ CompletableFuture<List<PkVectorSearchResult>> searchAsync(
}
}

public List<List<PkVectorSearchResult>> searchBatch(
IndexFileMeta segment,
PrimaryKeyIndexSourceMeta sourceMeta,
float[][] queries,
int limit,
Map<String, DeletionVector> deletionVectors,
Set<String> activeSourceFiles,
Map<String, List<Range>> rowRangesByFile,
Map<String, String> searchOptions) {
return searchBatchAsync(
segment,
sourceMeta,
queries,
limit,
deletionVectors,
activeSourceFiles,
rowRangesByFile,
searchOptions)
.join();
}

CompletableFuture<List<List<PkVectorSearchResult>>> searchBatchAsync(
IndexFileMeta segment,
PrimaryKeyIndexSourceMeta sourceMeta,
float[][] queries,
int limit,
Map<String, DeletionVector> deletionVectors,
Set<String> activeSourceFiles,
Map<String, List<Range>> rowRangesByFile,
Map<String, String> searchOptions) {
checkArgument(queries != null && queries.length > 0, "Query vectors cannot be empty.");
checkArgument(limit > 0, "Vector search limit must be positive: %s.", limit);
GlobalIndexMeta globalIndexMeta = segment.globalIndexMeta();
checkArgument(
globalIndexMeta != null && globalIndexMeta.sourceMeta() != null,
"Vector segment %s has no source metadata.",
segment.fileName());
if (segment.rowCount() == 0) {
List<List<PkVectorSearchResult>> results = new ArrayList<>(queries.length);
for (int i = 0; i < queries.length; i++) {
results.add(Collections.emptyList());
}
return CompletableFuture.completedFuture(Collections.unmodifiableList(results));
}
GlobalIndexer indexer =
GlobalIndexer.create(segment.indexType(), vectorField, indexOptions);
checkArgument(
indexer instanceof VectorGlobalIndexer,
"Index algorithm %s does not implement VectorGlobalIndexer.",
segment.indexType());
String readerMetric =
VectorSearchMetric.normalize(((VectorGlobalIndexer) indexer).metric());
checkArgument(
metric.equals(readerMetric),
"ANN segment metric %s does not match index reader metric %s.",
metric,
readerMetric);

GlobalIndexIOMeta ioMeta =
new GlobalIndexIOMeta(
annSegmentFile.path(segment),
segment.fileSize(),
globalIndexMeta.indexMeta());
GlobalIndexReader reader =
indexer.createReader(
meta -> fileIO.newInputStream(meta.filePath()),
Collections.singletonList(ioMeta),
executor);
try {
BatchVectorSearch search =
new BatchVectorSearch(queries, limit, vectorField.name(), searchOptions);
RoaringNavigableMap64 liveRows =
liveRowPositions(
sourceMeta.sourceFiles(),
activeSourceFiles,
deletionVectors,
rowRangesByFile);
if (liveRows != null) {
search.withIncludeRowIds(liveRows);
}
return reader.visitBatchVectorSearch(search)
.whenComplete((ignored, error) -> IOUtils.closeQuietly(reader))
.thenApply(
scoredResults -> {
checkArgument(
scoredResults.size() == queries.length,
"ANN segment %s returned %s batch results for %s queries.",
segment.fileName(),
scoredResults.size(),
queries.length);
List<List<PkVectorSearchResult>> results =
new ArrayList<>(queries.length);
for (Optional<ScoredGlobalIndexResult> scoredResult :
scoredResults) {
results.add(
mapResults(
segment,
sourceMeta,
deletionVectors,
activeSourceFiles,
rowRangesByFile,
scoredResult));
}
return Collections.unmodifiableList(results);
});
} catch (RuntimeException | Error t) {
IOUtils.closeQuietly(reader);
throw t;
}
}

private List<PkVectorSearchResult> mapResults(
IndexFileMeta segment,
PrimaryKeyIndexSourceMeta sourceMeta,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,44 +43,79 @@ public static List<PkVectorSearchResult> search(
int limit,
LongPredicate excludedPosition)
throws IOException {
checkArgument(query.length == reader.dimension(), "Query vector dimension does not match.");
return searchBatch(
dataFileName,
reader,
new float[][] {query},
metric,
limit,
excludedPosition)
.get(0);
}

public static List<List<PkVectorSearchResult>> searchBatch(
String dataFileName,
PkVectorReader reader,
float[][] queries,
String metric,
int limit,
LongPredicate excludedPosition)
throws IOException {
checkArgument(queries != null && queries.length > 0, "Query vectors cannot be empty.");
checkArgument(limit > 0, "Vector search limit must be positive.");
checkArgument(
VectorSearchMetric.isSupported(metric),
"Unsupported vector distance metric: %s.",
metric);
metric = VectorSearchMetric.normalize(metric);
for (int i = 0; i < query.length; i++) {
checkArgument(
Float.isFinite(query[i]),
"Query vector element at position %s must be finite.",
i);
}

Comparator<PkVectorSearchResult> bestFirst =
Comparator.comparingDouble(PkVectorSearchResult::distance)
.thenComparingLong(PkVectorSearchResult::rowPosition);
PriorityQueue<PkVectorSearchResult> nearest =
new PriorityQueue<>(limit, bestFirst.reversed());
List<PriorityQueue<PkVectorSearchResult>> nearest = new ArrayList<>(queries.length);
for (float[] query : queries) {
validateQuery(query, reader.dimension());
nearest.add(new PriorityQueue<>(limit, bestFirst.reversed()));
}

float[] vector = new float[reader.dimension()];
for (long position = 0; position < reader.rowCount(); position++) {
if (!reader.readNextVector(vector) || excludedPosition.test(position)) {
continue;
}
PkVectorSearchResult candidate =
new PkVectorSearchResult(
dataFileName,
position,
VectorSearchMetric.computeDistance(query, vector, metric));
if (nearest.size() < limit) {
nearest.add(candidate);
} else if (bestFirst.compare(candidate, nearest.peek()) < 0) {
nearest.poll();
nearest.add(candidate);
for (int i = 0; i < queries.length; i++) {
PkVectorSearchResult candidate =
new PkVectorSearchResult(
dataFileName,
position,
VectorSearchMetric.computeDistance(queries[i], vector, metric));
PriorityQueue<PkVectorSearchResult> queryNearest = nearest.get(i);
if (queryNearest.size() < limit) {
queryNearest.add(candidate);
} else if (bestFirst.compare(candidate, queryNearest.peek()) < 0) {
queryNearest.poll();
queryNearest.add(candidate);
}
}
}
List<PkVectorSearchResult> result = new ArrayList<>(nearest);
Collections.sort(result, bestFirst);
return Collections.unmodifiableList(result);

List<List<PkVectorSearchResult>> results = new ArrayList<>(queries.length);
for (PriorityQueue<PkVectorSearchResult> queryNearest : nearest) {
List<PkVectorSearchResult> result = new ArrayList<>(queryNearest);
Collections.sort(result, bestFirst);
results.add(Collections.unmodifiableList(result));
}
return Collections.unmodifiableList(results);
}

private static void validateQuery(float[] query, int dimension) {
checkArgument(query != null, "Query vector cannot be null.");
checkArgument(query.length == dimension, "Query vector dimension does not match.");
for (int i = 0; i < query.length; i++) {
checkArgument(
Float.isFinite(query[i]),
"Query vector element at position %s must be finite.",
i);
}
}
}
Loading
Loading