Quick answer: Build AI-powered search as a pipeline: clean and chunk your content, index it for both keyword and vector search, retrieve with both, rerank the results, and let a language model answer only from the top passages, with citations.
- Split content into chunks of about 300 tokens with about 15% overlap, and attach metadata such as URL, product and visibility.
- Embed each chunk and store the vector next to its text and metadata.
- Retrieve with keyword (BM25) and vector search together, applying permission filters before retrieval.
- Rerank the top candidates with a cross-encoder.
- Generate a short, cited answer from the top passages, and show plain snippets when confidence is low.
- Measure retrieval quality on a set of real user queries before launch.
In this guide
- Before You Start
- How RAG Search Works
- The RAG Architecture Checklist
- Step 1: Prepare and Chunk Your Content
- Step 2: Choose and Version an Embedding Model
- Step 3: Decide Where to Store Vectors and How to Combine Results
- Step 4: Rerank and Generate Cited Answers
- Step 5: Lock Down Access, Privacy and Prompt Injection
- Step 6: Test It Before Launch
- Build vs Buy: Which Route Fits?
- Practical Examples
- Common Problems and Fixes
- Official docs and trusted sources
- Frequently Asked Questions
- Next Steps
Before You Start
- Access to your content sources: docs (Markdown, HTML, PDF), help-centre articles, tickets, wiki pages or a product catalogue, plus a way to know when they change.
- 50–100 real user queries from search logs or support tickets. You need them in the test step, so collect them first.
- Your permission model: which users may see which documents (tenant, role, region). This decides what metadata every chunk must carry.
- An embedding model and a language model, either from a hosted API or running locally.
- Somewhere to store vectors: often the database or search engine you already run (see Step 3).
- Time: a pilot takes roughly a month; see the 30-day plan below.
How RAG Search Works
- Embeddings are lists of numbers that represent the meaning of a piece of text. Texts with similar meaning get similar vectors, so a search for "cancel my plan" can find a page titled "Ending your subscription".
- Lexical search (usually BM25, the standard keyword-ranking formula) matches the exact words. It catches product codes, error messages and rare names that embeddings often miss.
- RAG combines both kinds of retrieval with a language model that drafts an answer grounded in the retrieved passages and cites them.
The result: users ask questions instead of guessing keywords, and they get a concise answer they can check against the source.
The RAG Architecture Checklist
- Ingest: pull from docs (Markdown, HTML, PDF), tickets, CMS, wikis, product catalogues and databases.
- Normalise: strip boilerplate, remove duplicates, fix headings, keep the structure (H2/H3, lists, tables).
- Chunk: split documents into coherent chunks (200–400 tokens) with 10–20% overlap; attach metadata (URL, section, product, version, visibility).
- Embed: convert chunks to vectors with an embedding model.
- Index: store vectors in a vector index; store raw text and metadata alongside them.
- Retrieve: hybrid search, meaning lexical (BM25) plus semantic (approximate nearest neighbour, ANN) retrieval, with filters (tenant, product, language).
- Rerank: re-score the candidates with a cross-encoder for relevance.
- Generate: prompt the model with the top passages and require citations with source URLs.
- Guardrails: apply access filters before retrieval, detect low-confidence answers, and fall back to extractive snippets.
Step 1: Prepare and Chunk Your Content
- Chunk size: start with about 300 tokens and 15% overlap. Use shorter chunks for error messages and FAQs, longer ones for tutorials.
- Follow the structure: split at headings and list boundaries; never split a code block or a table row.
- Metadata: include
url,title, theh2/h3path,doc_type,product,version,languageandvisibility(public, internal, customer). - Skip unchanged content: hash the normalised text and re-embed a chunk only when its hash changes.
- Scans and images: run OCR (text recognition) on PDFs and images, and mark that text with
ocr=trueso you can trace odd results.
Step 2: Choose and Version an Embedding Model
- Pick by results on your content, not by leaderboard rank or dimension count. More dimensions are not automatically better.
- Cost vs quality: start with a cost-efficient model; you can switch later and re-embed everything.
- Multiple languages: choose a multilingual embedding model and store
languagein the metadata so you can filter. - Versioning: store
embedding_modeland its version on every vector. Vectors from different models cannot be compared, so never mix them in one index.
Step 3: Decide Where to Store Vectors and How to Combine Results
Pick the store by what you already run:
- Choose Postgres with pgvector if your content and permissions already live in Postgres: one database, one backup, and filters written in SQL.
- Choose Elastic or OpenSearch with kNN if you already run them: you get BM25, filters, analytics and vector search in one place.
- Choose Meilisearch or Typesense for a simpler developer experience and fast typo-tolerant keyword search; vector support differs by version, so check their docs.
- Choose a dedicated vector database (Pinecone, Weaviate, Qdrant) when vector volume or query load outgrows the options above, or when you want a managed service for scaling.
Whichever you choose:
- Run both searches: BM25 and vector search in parallel, then merge with a weighted rank or let a reranker score the combined list. Lexical search saves you when embeddings miss rare terms or product codes.
- Filter first: apply tenant, product and role filters inside the query, so restricted documents never enter the candidate list.
Step 4: Rerank and Generate Cited Answers
- Rerank: a cross-encoder reads the query and each passage together and scores relevance more accurately than vector similarity. Run it on the top 50–200 candidates only, because it is slower.
- Prompt: pass the top 5–10 passages with source IDs, and tell the model to answer briefly, only from those passages, and cite them. Short, consistent prompt templates are easier to test than long chains.
- Answer shape: users prefer a few cited sentences over an essay. Show citations with titles and section anchors.
- Fallback: if no passage is relevant or confidence is low, show the top passages as snippets instead of generating an answer.
Step 5: Lock Down Access, Privacy and Prompt Injection
- Access control: enforce role- or attribute-based filters at query time, using visibility attributes (tenant_id, role, region) stored on every chunk.
- Tenant isolation: use separate indices per tenant when contracts require strict separation. For the database side of this, see multi-tenant SaaS architecture with Postgres row-level security.
- Personal data: do not embed sensitive free text by default; redact or tokenise it first.
- Audit log: record the query, filters, retrieved source IDs and the sources cited in the answer.
- Data residency: keep data in the required region, and prefer managed services with SOC 2 or ISO 27001 reports where possible.
- Prompt injection: treat retrieved text as untrusted input. An indexed document can contain instructions aimed at the model, so keep passages clearly delimited in the prompt and do not give the answering model tools, credentials or write access.
Step 6: Test It Before Launch
- Take your 50–100 real queries and, for each one, mark which documents or sections are correct answers. This is your judged set.
- Run retrieval only (no generation) and measure Recall@20: the share of queries where at least one correct passage is in the top 20. If it is low, fix chunking, metadata filters or the hybrid merge before touching prompts.
- Measure ranking with MRR@10 (how high the first correct result appears) or NDCG@10 (how well the whole top 10 is ordered).
- Turn on generation and review a sample of answers by hand: is every claim backed by a cited passage?
- Check latency: aim for retrieval plus rerank around one second at P95 as a starting target, and stream the generated answer.
After launch, track click-through on citations, answer acceptance (thumbs up/down), successful resolution and time to answer. Add real queries to the judged set every quarter. Cache results for popular normalised queries and clear the cache when content changes; the pattern is the same as caching API responses with Redis in Node.js. Re-embed changed chunks incrementally, for example nightly.
Build vs Buy: Which Route Fits?
- Build if search quality is core to your product and you have data engineering capacity: you control chunking, filters and evaluation.
- Buy (managed Elastic, OpenSearch, Typesense or Meilisearch with vector features, or a hosted vector database) if you need results quickly and can accept the vendor's defaults.
- Mix: a managed vector store plus your own retrieval, rerank and prompt layer is the common middle ground.
Practical Examples
- Docs portal: filter by product="Billing" AND version="v3" AND visibility=public; answer with three citations at most.
- Internal knowledge base: filter by tenant_id and role; never generate answers from HR documents, show top passages only.
- E-commerce: hybrid search across titles and specs plus semantic attributes; rerank for intent (e.g., "quiet dishwasher under 45 dB").
Common Problems and Fixes
- Searches for product codes or error strings miss obvious pages. You are relying on vector search alone. Add BM25 and merge the results.
- Answers cite the right page but the wrong section. Chunks are too large or cut across headings. Split at headings and shorten chunks for that content type.
- Users see results from documents they should not access. Filters run after retrieval or a chunk lacks visibility metadata. Move filters into the query and reject chunks without visibility.
- Answers are confident but wrong. Retrieval returned weak passages and the model filled the gap. Check Recall@20 for that query, and show snippets instead of generating when no passage scores well.
- Results got worse after changing the embedding model. Old and new vectors are mixed in one index. Re-embed everything into a new index and switch over once it is complete.
Official docs and trusted sources
- OpenAI embeddings & guidance: platform.openai.com/docs/guides/embeddings
- LangChain RAG: python.langchain.com
- LlamaIndex: docs.llamaindex.ai
- Pinecone: docs.pinecone.io
- Weaviate: weaviate.io/developers
- Qdrant: qdrant.tech/documentation
- Elastic kNN: elastic.co
- OpenSearch k-NN: opensearch.org
- Typesense: typesense.org/docs
- Meilisearch: meilisearch.com/docs
- Hugging Face sentence-similarity (embedding) models: huggingface.co
Frequently Asked Questions
How is AI-powered search different from keyword search?
It matches meaning, not just words. Embeddings let it find a page about "ending your subscription" for the query "cancel my plan", and a language model can then write a short answer that cites those pages. Good systems still keep keyword search for exact terms.
Do I need a vector database for RAG?
You need a vector index, not necessarily a separate database. Vector search built into Postgres (pgvector), Elastic or OpenSearch is often enough. A dedicated vector database becomes worth it when vector volume or query load outgrows those, or when you want a managed scaling service.
What chunk size should I use for RAG?
Start around 300 tokens with about 15% overlap, split at headings, then adjust by content type. Short reference content such as error messages works better with smaller chunks. Confirm any change with Recall@k on your judged set of real queries rather than by eye.
Which embedding model is best for search?
There is no single best model; the right one is the one that retrieves your content best. Shortlist a few current, well-documented models, embed a sample of your content with each, and compare Recall@20 and MRR@10 on real queries. Re-test when you consider switching.
How do I stop RAG search from exposing private documents?
Store visibility attributes such as tenant, role and region on every chunk, and apply them as filters inside the retrieval query. That way restricted passages never reach the reranker or the model. For strict contractual isolation, use a separate index per tenant.
Next Steps
Collect your real queries and build the judged set first, then work through Steps 1–6 on one content source before adding more. To prototype the answer step without sending documents to a hosted API, run a local model with Ollama. For agents that use this search as a tool, continue with the complete guide to building AI agents.

