Use VectorSearchOperation instead of Document.

See #693
This commit is contained in:
Mark Paluch
2025-05-05 11:00:27 +02:00
parent 1607cc08b7
commit e14503721a

View File

@@ -1,11 +1,11 @@
/*
* Copyright 2024 the original author or authors.
* Copyright 2025 the original author or authors.
*
* Licensed 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
*
* https://www.apache.org/licenses/LICENSE-2.0
* 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,
@@ -17,12 +17,12 @@ package com.example.spi.mongodb.atlas;
import java.util.List;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ResolvableType;
import org.springframework.data.domain.Limit;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.VectorSearchOperation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.RepositoryMethodContext;
import org.springframework.data.repository.core.support.RepositoryMetadataAccess;
@@ -43,8 +43,10 @@ class AtlasRepositoryFragment<T> implements AtlasRepository<T>, RepositoryMetada
Class<?> domainType = resolveDomainType(methodContext.getMetadata());
Document $vectorSearch = createDocument(index, path, vector, Limit.of(10));
Aggregation aggregation = Aggregation.newAggregation(ctx -> $vectorSearch);
VectorSearchOperation $vectorSearch = VectorSearchOperation.search(index).path(path).vector(vector)
.limit(Limit.of(10)).numCandidates(150);
Aggregation aggregation = Aggregation.newAggregation($vectorSearch);
return (List<T>) mongoOperations.aggregate(aggregation, mongoOperations.getCollectionName(domainType), domainType).getMappedResults();
}
@@ -59,16 +61,4 @@ class AtlasRepositoryFragment<T> implements AtlasRepository<T>, RepositoryMetada
.resolve();
}
private static Document createDocument(String indexName, String path, List<Double> vector, Limit limit) {
Document $vectorSearch = new Document();
$vectorSearch.append("index", indexName);
$vectorSearch.append("path", path);
$vectorSearch.append("queryVector", vector);
$vectorSearch.append("limit", limit.max());
$vectorSearch.append("numCandidates", 150);
return new Document("$vectorSearch", $vectorSearch);
}
}