Skip to main content

πŸ‘ Add Semantic Search to Your Application

You now know everything you need to add vector search capabilities to your application.

Configuring the environment variables​

In your server/.env file, you'll find a few variables that you can use to configure the application. Add a couple more at the end of the file to configure the embeddings source and the API key.

EMBEDDINGS_SOURCE=serverlessEndpoint
EMBEDDING_KEY=<API Key>
tip

Your instructor will provide you with an API key that you can use for the event you're attending. Set it in the EMBEDDING_KEY variable.

Configuring the vector search query​

Open up the code from the server file 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: 100,
}
}
];
const books = await collections?.books?.aggregate(aggregationPipeline).toArray() as Book[];
return books;
}

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