π Add Semantic Search to Your Application
You now know everything you need to add vector search capabilities to your application.
- π NodeJS/Express
- βοΈ Java Spring Boot
Open up the BookController
in server/src/controllers/books.ts once more, and edit the searchBooks
method to query your data for semantic search.
tip
Use the getEmbeddings
function to convert the query into a vector.
Answer
public async searchBooks(query: string): Promise<Book[]> {
const vector = await getEmbeddings(query);
const aggregationPipeline = [
{
$vectorSearch: {
queryVector: vector,
path: 'embeddings',
numCandidates: 100,
index: 'vectorsearch',
limit: 10,
}
}
];
const books = await collections?.books?.aggregate(aggregationPipeline).toArray() as Book[];
return books;
}
Open the BookService
class in /domain/service/BookService.java, locate the searchBooks(String theTerm)
method, and update it to use Vector Search for semantic queries.
tip
Use the embeddingProvider.getEmbeddings
method to convert the query into a vector.
Answer
src/main/java/com/mongodb/devrel/library/domain/service/BookService.java
public List<Book> searchBooks(String theTerm) {
List<Double> vector = embeddingProvider.getEmbeddings(theTerm);
AggregationOperation searchStage = context ->
new Document("$vectorSearch",
new Document("index", "vectorsearch")
.append("path", "embeddings")
.append("queryVector", vector)
.append("numCandidates", 100)
.append("limit", 10)
);
Aggregation aggregation = Aggregation.newAggregation(searchStage);
return mongoTemplate.aggregate(aggregation, "books", Book.class).getMappedResults();
}
Testing the semantic searchβ
To test the semantic search in the app, try to search for some books but use different words that have a similar meaning or are related to the book's cover.
You can use the following queries:
- Canines doing stuff
- Fluffy animals
- European history