Published

Vector Databases and Semantic Search: Embeddings, Indexing and Hybrid Retrieval

A hands-on guide to semantic search over company data: embeddings, vector indexes like HNSW and IVF, choosing a vector database, hybrid search and reranking.

Written by
Ali ÖzdurmuşFounder, Veni AI
Updated
Reading time
7 min read

Keyword search finds documents that contain your words. Semantic search finds documents that mean what you meant. That difference is what makes internal search, document assistants and RAG systems work on real company data, where the same thing is described in ten different ways.

This guide covers the full stack: embeddings, similarity metrics, index types, vector database options, hybrid search, reranking and running it in production.

Code samples are illustrative Python. client is an initialized SDK client, and EMBEDDING_MODEL / RERANK_MODEL are placeholders for the model IDs you choose.

Keyword search:
Query: "late delivery penalty"
Result: only documents containing those exact words

Semantic search:
Query: "late delivery penalty"
Result: "liquidated damages for delayed shipment", "penalty clause for missed delivery dates",
        and other passages with the same meaning

Core Concepts

Embedding: a numeric vector that represents the meaning of a piece of text (or an image, or audio).

"supplier contract" → [0.12, -0.45, 0.89, ..., 0.34]   (hundreds to thousands of dimensions)

Similarity search: find the stored vectors closest to the query vector.

Distance Metrics

Cosine similarity: direction only, range [-1, 1]. The default for text.

cos(A, B) = (A · B) / (||A|| × ||B||)

Euclidean distance (L2): geometric distance, range [0, ∞). Common for image features and clustering.

d(A, B) = √(Σ(Aᵢ - Bᵢ)²)

Dot product: equivalent to cosine when vectors are normalized, and slightly cheaper to compute.

Choosing an Embedding Model

Current options include:

ModelProviderNotes
Cohere Embed 5CohereHosted API, long inputs (128K context)
Gemini Embedding 2GoogleHosted API
Voyage 4Voyage AIHosted API, 32K context
Qwen3-VL-EmbeddingAlibaba QwenOpen weights, text and images, can run on your own servers

How to choose:

  • Test on your own data. Build 50–100 real questions with known correct documents, in the languages your users actually use, and measure recall.
  • Data residency. If documents cannot leave your infrastructure, an open-weights model you host yourself is the simplest answer.
  • Dimensions vs. cost. Larger vectors cost more memory. Many models let you reduce dimensions with a small quality trade-off.
python
def get_embeddings(texts: list[str]) -> list[list[float]]:
    response = client.embeddings.create(model=EMBEDDING_MODEL, input=texts)
    return [item.embedding for item in response.data]

Never mix vectors from two different embedding models in one index. When you change models, re-embed everything.

Indexing Algorithms

Comparing a query against every vector is exact but slow. Vector databases use Approximate Nearest Neighbor (ANN) indexes instead.

Flat (brute force)

Compares against every vector. 100% recall, O(n × d). Fine up to a few hundred thousand vectors.

IVF (Inverted File Index)

  1. Cluster vectors with k-means into nlist groups.
  2. Assign each vector to its nearest centroid.
  3. At query time, search only the nprobe nearest clusters.

Higher nprobe means higher recall and slower queries.

HNSW (Hierarchical Navigable Small World)

A layered graph and the most widely used index today.

Layer 2:    o-------o-------o              (sparse)
            |       |       |
Layer 1:  o-o-o---o-o-o---o-o-o            (medium)
          | | |   | | |   | | |
Layer 0:  o-o-o-o-o-o-o-o-o-o-o-o          (dense)

Parameters:

  • M: connections per node
  • ef_construction: candidate list size while building
  • ef_search: candidate list size while querying

Typical starting points:

High recall: M=32, ef_search=200
High speed:  M=16, ef_search=50
Balanced:    M=24, ef_search=100

Product Quantization (PQ)

Splits each vector into sub-vectors and stores a centroid ID for each, compressing memory dramatically at some cost to recall.

Original: 1536 dims × 4 bytes = 6 KB
PQ (M=96, K=256): 96 × 1 byte = 96 bytes   (~64× smaller)

Scalar Quantization (SQ)

Stores Float32 values as Int8: about 4× smaller with a small recall loss. A good default when memory becomes the bottleneck.

Vector Database Options

  • PostgreSQL + pgvector: keep vectors next to your relational data. Often the simplest choice for companies that already run Postgres.
  • Qdrant: open source, written in Rust, strong payload filtering, self-hosted or managed.
  • Weaviate: open source, built-in hybrid (vector + keyword) search, self-hosted or managed.
  • Milvus: open source, designed for very large collections, Kubernetes-native.
  • Pinecone: fully managed service, no infrastructure to run.
  • Chroma: lightweight and developer-friendly, good for prototypes.

Selection criteria that matter more than benchmarks: where the data must live (on-premise, a Turkish data center, or a public cloud region), filtering needs, expected collection size, and who will operate it.

python
from pinecone import Pinecone

pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
index = pc.Index("company-docs")

index.upsert(vectors=[
    {"id": "policy-12#3", "values": embedding, "metadata": {"dept": "hr", "lang": "tr"}}
])

results = index.query(vector=query_embedding, top_k=10,
                      filter={"dept": "hr"}, include_metadata=True)

Filtering and Metadata

Pre-filtering: apply metadata filters first, then search inside the filtered set. Fast and the right choice for access control.

Post-filtering: search first, then filter the top K × multiplier. Better recall for loose filters, but slower and unsafe for permissions.

Store at least: source document, section, date, language, department and access level.

Combine keyword (BM25) and vector scores so exact identifiers and natural language both work:

python
import numpy as np
from rank_bm25 import BM25Okapi

class HybridSearch:
    def __init__(self, documents):
        self.documents = documents
        self.bm25 = BM25Okapi([doc["text"].split() for doc in documents])
        self.embeddings = np.array(get_embeddings([doc["text"] for doc in documents]))

    def search(self, query: str, top_k: int = 10, alpha: float = 0.5):
        bm25 = self.bm25.get_scores(query.split())
        bm25 = (bm25 - bm25.min()) / (bm25.max() - bm25.min() + 1e-6)

        q = np.array(get_embeddings([query])[0])
        semantic = self.embeddings @ q / (
            np.linalg.norm(self.embeddings, axis=1) * np.linalg.norm(q)
        )

        scores = alpha * semantic + (1 - alpha) * bm25
        top = np.argsort(scores)[::-1][:top_k]
        return [{"document": self.documents[i], "score": float(scores[i])} for i in top]

Reranking

Retrieve more candidates than you need, then re-order them with a reranker (for example Cohere Rerank 4 or Voyage rerank-3):

python
def search_with_rerank(query: str, top_k: int = 5):
    candidates = vector_search(query, top_k=top_k * 6)
    response = reranker.rerank(
        model=RERANK_MODEL,
        query=query,
        documents=[c["text"] for c in candidates],
        top_n=top_k,
    )
    return [candidates[r.index] for r in response.results]

Query Understanding

Query expansion

Ask a model for a few rephrasings of the query and search with all of them. Useful when users type very short queries.

HyDE (Hypothetical Document Embeddings)

Ask the model to write a short hypothetical answer, embed that answer, and search with it. It often helps when questions are phrased very differently from the documents.

Measuring Retrieval Quality

python
def retrieval_metrics(retrieved: list, relevant: list, k: int):
    top_k = retrieved[:k]
    hits = len(set(top_k) & set(relevant))
    mrr = next((1 / (i + 1) for i, d in enumerate(retrieved) if d in relevant), 0)
    return {"precision@k": hits / k, "recall@k": hits / len(relevant), "mrr": mrr}

Production Notes

Batch ingestion

python
# Slow: one vector per request
for vec in vectors:
    index.upsert([vec])

# Better: batches
for i in range(0, len(vectors), 100):
    index.upsert(vectors[i:i + 100])

Embedding cache

Hash the text and cache its embedding; re-embedding unchanged documents on every sync wastes money.

Monitoring

  • Query latency (p50, p95, p99)
  • Recall on a fixed evaluation set, re-run weekly
  • Queries per second
  • Index size and memory use
yaml
alerts:
  - name: high_latency
    condition: p99_latency > 200ms
    severity: warning
  - name: low_recall
    condition: recall_at_10 < 0.9
    severity: critical

Summary

Semantic search rests on three choices: an embedding model tested on your own data, an index and database that fit where your data must live, and hybrid retrieval with reranking on top. Get those right and every application built on top, from internal search to RAG assistants and agents, gets better.

Veni AI designs search and retrieval layers on top of companies' existing data, including on-premise and Türkiye-hosted setups. See our services or describe your data setup.

Keep reading

Have a process that should run on AI?

Describe one process as it runs today, and we'll show you which repetitive steps an AI application or agent could handle.