Skip to content

2.5 Semantic Search. Taking It to Production

Once the index is built and basic search works, the most important stage begins: tuning. A simple search by cosine similarity finds "something similar" to the query, but high-quality answers require finding exactly the relevant fragments.

For this you need to work at several levels at once: optimize the structure of the index, apply filtering sensibly, improve the ranking of results, and monitor quality. Each of these levels adds complexity, but together they significantly increase the accuracy and usefulness of the system (see Fig. 16).

Figure 16. Optimization levels.

Figure 16. Optimization levels.

Choosing the Index Structure

A vector index can be organized in different ways, and the choice depends first of all on the volume of data.

A flat index is the simplest option. All vectors are stored without any additional structure, and for each query the distance to every one of them is computed. This approach gives maximum accuracy but scales poorly in speed. Usually it is sufficient for collections of up to several thousand documents.

HNSW (Hierarchical Navigable Small World) is a more sophisticated algorithm in which the vectors are organized into a graph. This makes search much faster while keeping high accuracy (recall 95%+). The price is additional memory consumption, and such a trade-off is most often justified.

IVF (Inverted File Index) works differently: the space is split into clusters, and the search is performed only within the nearest of them. This makes it faster and more memory-efficient than HNSW, but its accuracy depends directly on the number of clusters that are scanned.

Here is an example of initializing different indexes:

import faiss

dimension = 1536
num_vectors = 100000

flat_index = faiss.IndexFlatIP(dimension)

nlist = 100
quantizer = faiss.IndexFlatIP(dimension)
ivf_index = faiss.IndexIVFFlat(quantizer, dimension, nlist)
ivf_index.train(training_vectors)
ivf_index.nprobe = 10

hnsw_index = faiss.IndexHNSWFlat(dimension, 32)
hnsw_index.hnsw.efConstruction = 200
hnsw_index.hnsw.efSearch = 64

You can start with HNSW for collections of up to a million documents. If memory becomes the bottleneck or further scaling is required, it makes sense to switch to IVF with careful parameter tuning on real data.

Filtering by Metadata

In real systems, semantic search is almost always combined with filtering. For example, a user may be looking for a function, but only in the current version of the documentation, or only among documents of a certain type.

There are two main approaches.

Post-filtering: first the top-k nearest vectors are retrieved, then the ones that do not match the metadata are discarded. This approach is simple to implement, but it can leave you with too few results.

Pre-filtering: first a subset of documents is selected by metadata, and the search is performed only within it. This is a more complex and costly option, but it guarantees that the system finds the required number of results if they exist (see Fig. 17).

Figure 17. Filtering by metadata: post- vs pre-filtering.

Figure 17. Filtering by metadata: post- vs pre-filtering.

An example of using Chroma:

from langchain_community.vectorstores import Chroma

vector_store = Chroma.from_documents(
    documents=chunks,
    embedding=embeddings,
    persist_directory="./chroma_db"
)

results = vector_store.similarity_search(
    query="how to set up authorization",
    k=5,
    filter={"version": "3.0", "type": "guide"}
)

For more complex filters it makes sense to store the metadata separately in a regular database, pre-select the IDs of the documents that match, and then use them to filter the vector search.

Multi-Tenancy Challenges

In SaaS systems, each client uploads its own documentation, and search must work strictly within the data of a specific client. Fine, we add metadata with a client identifier.

But at scale, difficulties arise. If you use a separate index for each client, with ten clients this is still manageable. But with hundreds of clients, managing hundreds of indexes becomes a problem: slow application startup, complex synchronization, uneven load.

Moving to a single index with filtering by tenant_id is simpler to manage, but creates a new problem: if you use post-filtering, clients with small knowledge bases can get too few results. If the nearest vectors by similarity belong to another client, they are cut off by the filter, and fewer results remain than needed.

The solution is a two-stage search. First, all of the client's documents are selected by metadata (without vector search). Then the vector search is performed with the restriction to that set of IDs. This requires support for pre-filtering in the vector database. Not all databases support it: for example, Chroma does not handle it very well, while Pinecone works well.

def search_for_tenant(query, tenant_id, k=5):
    query_embedding = embeddings.embed_query(query)

    results = pinecone_index.query(
        vector=query_embedding,
        top_k=k,
        filter={"tenant_id": {"$eq": tenant_id}},
        include_metadata=True
    )

    return [
        Document(
            page_content=match.metadata["text"],
            metadata=match.metadata
        )
        for match in results.matches
    ]

Tuning Retriever Parameters

The number of returned documents (the parameter k) is one of the key parameters affecting quality. A small k gives precise but potentially incomplete results. A large k increases the chance of finding the needed information, but adds irrelevant context that can confuse the model.

The right choice of k depends on many factors: the size of the context window, the complexity of the questions, and the quality of indexing. The best way is to experiment on real data. Take a test set of 50–100 questions, label the relevant documents for each one, then try different values of k and measure recall.

def find_optimal_k(test_cases, vector_store, k_values=[3, 5, 10, 20]):
    results = {}

    for k in k_values:
        total_recall = 0

        for query, relevant_ids in test_cases:
            retrieved = vector_store.similarity_search(query, k=k)
            retrieved_ids = [doc.metadata["id"] for doc in retrieved]

            hits = len(set(retrieved_ids) & set(relevant_ids))
            recall = hits / len(relevant_ids) if relevant_ids else 0
            total_recall += recall

        results[k] = total_recall / len(test_cases)

    return results

The similarity threshold is another important parameter. It cuts off results below a certain level of relevance. This is useful in situations where it is better to return nothing than to return an irrelevant result.

def search_with_threshold(query, vector_store, k=10, threshold=0.7):
    results_with_scores = vector_store.similarity_search_with_score(
        query=query,
        k=k
    )

    filtered = [
        doc for doc, score in results_with_scores
        if score >= threshold
    ]

    return filtered

Reranking for Better Quality

The first-pass search by embeddings works fast but gives only approximate results. After it, it makes sense to apply a more accurate model for reranking.

Cross-encoder models assess relevance directly, taking a "query–document" pair as input. They are much more accurate but slower, so they are applied only to a limited set of candidates.

from sentence_transformers import CrossEncoder

reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')

def search_with_reranking(query, vector_store, initial_k=20, final_k=5):
    candidates = vector_store.similarity_search(query, k=initial_k)

    pairs = [(query, doc.page_content) for doc in candidates]
    scores = reranker.predict(pairs)

    scored_docs = list(zip(candidates, scores))
    scored_docs.sort(key=lambda x: x[1], reverse=True)

    return [doc for doc, score in scored_docs[:final_k]]

A typical scheme: a fast first-pass search with a large k (for example, 20), then reranking and returning the best ones (for example, 5). Such a two-stage pipeline usually gives a 10–15% quality gain on metrics like NDCG at a moderate increase in latency.

Typical Search Problems and Their Solutions

While working with RAG systems, recurring problems are regularly discovered.

Duplicates in the index. The same content gets indexed several times: from different sources, during re-indexing without cleanup, or when documents are updated. Duplicates take up places in the top-k results and crowd out diverse content.

The solution is deduplication. Keep only unique fragments:

def deduplicate_results(results, similarity_threshold=0.95):
    unique = []
    seen_embeddings = []

    for doc in results:
        doc_embedding = embeddings.embed_query(doc.page_content)

        is_duplicate = False
        for seen_emb in seen_embeddings:
            similarity = cosine_similarity(doc_embedding, seen_emb)
            if similarity > similarity_threshold:
                is_duplicate = True
                break

        if not is_duplicate:
            unique.append(doc)
            seen_embeddings.append(doc_embedding)

    return unique

Overly generic chunks. Tables of contents, introductions, and headings: they contain key terms and often end up in the top-k, but carry no useful information. They are relevant to many queries but do not answer any of them specifically.

def filter_generic_chunks(chunks, max_query_matches=50):
    query_match_counts = defaultdict(int)

    for chunk in chunks:
        query_match_counts[chunk.metadata["id"]] = count_query_matches(chunk)

    filtered = [
        chunk for chunk in chunks
        if query_match_counts[chunk.metadata["id"]] < max_query_matches
    ]

    return filtered

Bias toward long documents. When many chunks are generated from one long document, these chunks often dominate the results. Use MMR (Maximal Marginal Relevance), which balances relevance and diversity:

results = vector_store.max_marginal_relevance_search(
    query=query,
    k=5,
    fetch_k=20,
    lambda_mult=0.7
)

Monitoring Search Quality

It is important to track search quality on real queries. What to look at:

The distribution of similarity scores shows how confidently the system finds relevant content. If the average score of the top-1 result starts to fall, that is a signal of a problem.

The number of results above the threshold shows how often the system finds sufficiently relevant content. If for many queries fewer than k results come back above the set threshold, the index may be short on content, or the threshold may be too high.

class RetrievalMonitor:
    def __init__(self):
        self.metrics = []

    def log_search(self, query, results, scores):
        self.metrics.append({
            "timestamp": datetime.utcnow().isoformat(),
            "query_length": len(query),
            "num_results": len(results),
            "top_score": max(scores) if scores else 0,
            "avg_score": sum(scores) / len(scores) if scores else 0,
            "above_threshold": sum(1 for s in scores if s > 0.7)
        })

    def get_summary(self, hours=24):
        cutoff = datetime.utcnow() - timedelta(hours=hours)
        recent = [m for m in self.metrics if m["timestamp"] > cutoff.isoformat()]

        return {
            "total_searches": len(recent),
            "avg_top_score": sum(m["top_score"] for m in recent) / len(recent),
            "avg_results_above_threshold": sum(m["above_threshold"] for m in recent) / len(recent)
        }

Questions for Reflection and Practice

Theoretical questions

  1. Compare the indexing algorithms for vector search (flat, HNSW, IVF) and their trade-offs between accuracy, speed, and memory.

  2. How does pre-filtering differ from post-filtering in metadata-based search, and what problems can each approach cause?

  3. How do you choose the optimal value of k (the number of returned results), and which factors influence this choice?

  4. What is reranking, and why do cross-encoder models give more accurate relevance estimates than the first-pass search?

  5. Which typical search problems occur in RAG systems, and how do you diagnose them?

  6. How does MMR (Maximal Marginal Relevance) help balance the relevance and diversity of results?

  7. Which metrics should be tracked to monitor search quality in production?

  8. How do you organize multi-tenant search, and which architectural solutions exist for it?

Practical exercises

  1. Create a vector database with an HNSW index and compare the speed and accuracy of search against a flat index on a set of 10,000 vectors.

  2. Implement search with metadata filtering for a scenario with several documentation versions (2.0, 3.0, 4.0).

  3. Build a two-stage pipeline with first-pass search and reranking via a cross-encoder, and compare the results.

  4. Implement search result deduplication based on the similarity of embeddings.

  5. Create a search quality monitoring system with metric aggregation over time periods and alerts.