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 () and the stored document vectors ():- 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:2.2 Complete Code Implementation
Save and run this code: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:
- Call
.similarity_search(query, k=2)on thevector_dbobject. - Iterate through the returned list and print each chunk’s content.
Solution
Solution