Skip to main content
After documents are chunked, they must be converted into numerical vectors using an Embedding Model and stored in a Vector Database for similarity retrieval. By the end of this page, you will have a working semantic search engine project.

1. Vector Spaces & Distance Metrics

An embedding model maps text chunks to coordinate vectors in a high-dimensional space. To retrieve the best matches, the vector database calculates distance metrics between the user’s query vector (qq) and the stored document vectors (dd):
  • Cosine Similarity: Measures the cosine of the angle between two vectors. It ranges from -1 to 1 (where 1 means identical direction). Ideal for text retrieval because it is independent of document length.
  • L2 Distance (Euclidean): Measures the straight-line distance between two points. Closer to 0 means higher similarity.
  • Dot Product: Multiplies corresponding coordinates. If vectors are normalized, dot product equals cosine similarity.

2. Ingestion + Vector Search Working Project

Let’s build a working database search project that loads a text document, chunks it, generates embeddings using Gemini, stores them in ChromaDB, and runs semantic query searches.

2.1 Install Dependencies

Run in your terminal:
Ensure your API key is in your environment:

2.2 Complete Code Implementation

Save and run this code:
Output:

3. Practice Exercises

Practice 1: Search Scope (Top-K)

Modify the search query step in the working project to retrieve the top 2 matches (k=2). Run a query searching for "travel refunds and screen security" and print both returned chunks. Instructions:
  1. Call .similarity_search(query, k=2) on the vector_db object.
  2. Iterate through the returned list and print each chunk’s content.