RAG Integration Patterns

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Retrieval-Augmented Generation (RAG) grounds an LLM’s answer in passages retrieved from a corpus rather than relying only on what the model memorized during training. Qdrant plays the retrieval half of that pattern: it stores an embedding for every passage alongside metadata, then returns the passages closest to a query embedding so they can be inserted into the LLM’s prompt as context. For when Qdrant specifically — rather than Pinecone, Weaviate, Milvus, pgvector, or an existing search engine’s vector support — is the right retrieval store for this job, see Choosing the Right Database — Vector Databases.

End-to-end shape of the pattern

A RAG system has two pipelines that share the same collection: an ingestion pipeline that runs once (or incrementally) per source document, and a retrieval pipeline that runs on every user query.

flowchart TD subgraph Ingestion A[Source document] --> B[Chunk into passages] B --> C[Embed each chunk] C --> D[Upsert as points
vector + payload] end subgraph Retrieval Q[User query] --> E[Embed query] E --> F[Search / filter / re-rank] D -.-> F F --> G[Assemble context] G --> L[LLM generates answer] end

The rest of this page walks through each stage of both paths, then shows a runnable example of the whole thing using qdrant-client directly.

Embedding pipeline: chunking

An LLM’s context window and an embedding model’s input limit both force a source document to be split into smaller chunks before it is embedded. The chunking strategy trades off retrieval precision against how much surrounding context survives in each piece:

  • Fixed-size chunking splits on a token or character count (often with a small overlap between consecutive chunks). It is the cheapest to implement and the most predictable in size, but it can cut a sentence or an argument in half at an arbitrary boundary.

  • Sentence-based chunking splits on sentence boundaries and groups a target number of sentences per chunk. It keeps individual sentences intact, at the cost of chunks that vary more in length and token count.

  • Semantic chunking groups sentences by embedding similarity, starting a new chunk where the topic actually shifts rather than where a fixed budget runs out. It produces the most topically coherent chunks, but costs an extra embedding pass over the document just to find the split points.

There is no single correct choice — the Question Answering System tutorial walks through a complete pipeline built on one particular chunking and embedding choice, as one worked example among these trade-offs.

The cost of a naive fixed-size split is easy to see on the handbook paragraph used in the example below. Cutting it every 160 characters with a 30-character overlap produced a second chunk that began with nual leave must be requested: the word "Annual" was split in two, and the embedding of that chunk is built from a fragment. Packing whole sentences into chunks of at most 200 characters, as the example does, keeps every chunk readable and costs nothing but a small variation in chunk length. Whatever the strategy, two rules hold: a chunk should be a unit a human could read on its own as an answer, and a chunk’s size should be well under the embedding model’s input limit, because text beyond the limit is truncated silently by most models.

Chunk size Retrieval behavior Cost

Small (one or two sentences)

Precise matches; the right sentence ranks high. May lack the context needed to answer.

More points, more embedding calls, larger index.

Medium (a paragraph)

A good default; enough context, still focused.

Balanced.

Large (a page or section)

Context is complete but the vector averages many topics, so relevance blurs.

Fewer points; more tokens in every prompt.

A common refinement is to retrieve small chunks but send their parent section to the LLM: store a parent_id or the section text in the payload, search on the small vector, and assemble the prompt from the parent.

Embedding pipeline: choosing a model

The embedding model choice fixes three things a Qdrant collection then has to be configured around:

  • Dimension count — the length of the vector each chunk becomes, which must match the collection’s configured vector size exactly (see Collections & Points for how a collection’s vector parameters are set).

  • Normalization — whether the model already outputs unit-length vectors. A normalized model pairs naturally with cosine distance (equivalent to a dot product on unit vectors); an unnormalized one may call for a different distance metric or an explicit normalization step before upserting.

  • Cost and latency — a larger embedding model produces better retrieval quality but costs more per token and adds latency to both ingestion (once per chunk) and every query (once per request), so the choice is a direct trade-off against how much traffic the system serves.

Storing chunks as points

Each chunk becomes one Qdrant point: its vector is the chunk’s embedding, and its payload carries the metadata needed to trace a retrieved chunk back to its source and to filter candidates before they are ranked — typically the source document id, the chunk’s index within that document, a section or heading title, and any access-control tags that scope which chunks a given caller is allowed to retrieve. Payload design and the indexes that make filtering on these fields fast are covered in Filtering & Payload Indexing, not repeated here.

The payload the example below writes for every chunk, and what each field is for:

Field Purpose

document_id

Groups chunks of one source document; the key for re-ingestion and for deleting a document.

section_title

Shown in citations and part of the replace key, so one section can be refreshed alone.

chunk_index

Position within the section; sorts retrieved chunks back into reading order.

access_tags

A keyword array that the retrieval filter matches against the caller’s entitlements.

text

The chunk itself, returned with the hit so no second lookup is needed to build the prompt.

Storing the text in the payload keeps Qdrant self-sufficient for retrieval. For very large corpora it is also common to store only a pointer (an object-store key) and fetch the text separately, which keeps the collection small.

Point ids are derived rather than generated: the example uses uuid.uuid5 over document_id/section_title#chunk_index, so ingesting the same section twice produces the same ids and the second upsert overwrites the first instead of duplicating it.

Retrieval at query time

At query time the user’s question is embedded with the same model used for ingestion, then the retrieval path runs in up to four stages:

  1. Search — a dense vector search over the query embedding, or a hybrid combination of dense and sparse search; see Hybrid & Sparse Search for how Qdrant runs and fuses that search, not repeated here.

  2. Filter — payload filters narrow the candidate set to the document ids, sections, or access-control tags the query is allowed to see, using the filtering machinery in Filtering & Payload Indexing.

  3. Re-rank (optional) — a smaller, more expensive scoring pass (e.g. a cross-encoder) reorders the top candidates the vector search returned, trading extra latency for better ranking quality than distance alone gives on the first pass.

  4. Assemble context — the surviving chunks' payload text (and their source metadata) are concatenated into the prompt sent to the LLM.

sequenceDiagram participant U as User participant App as RAG application participant E as Embedding model participant Q as Qdrant participant L as LLM U->>App: question App->>E: embed question E-->>App: query vector App->>Q: query_points with vector and access filter Q-->>App: top chunks with payload App->>App: optional re-rank, assemble context App->>L: prompt with context and question L-->>U: grounded answer

Integrating with LangChain and LlamaIndex

Both major RAG frameworks ship a first-class Qdrant vector-store integration so the ingestion and retrieval plumbing above does not have to be hand-written for every project:

  • LangChain — the langchain-qdrant package provides a QdrantVectorStore class that implements LangChain’s standard vector-store interface (add_documents, similarity_search, retriever construction) on top of qdrant-client, including hybrid search and payload-filter pass-through.

  • LlamaIndex — the llama-index-vector-stores-qdrant package provides a QdrantVectorStore class that plugs into LlamaIndex’s index and query-engine abstractions the same way, so a VectorStoreIndex backed by it persists and queries nodes as Qdrant points.

Both integrations still upsert points and run searches through qdrant-client underneath, following the same point-and-payload shape and the same search/filter/re-rank flow described above — they just generate that code from higher-level document and query-engine objects.

The LangChain version of the ingestion and filtered search is short. This was run with langchain-qdrant 0.2.1 and a toy Embeddings subclass (the same hashing trick as below, wrapped in the two methods LangChain requires), against a collection created beforehand with qdrant-client:

from langchain_core.documents import Document
from langchain_qdrant import QdrantVectorStore
from qdrant_client import models

store = QdrantVectorStore(client=client, collection_name="lc_kb", embedding=ToyEmbeddings())
store.add_documents([
    Document(page_content="Employees request time off through the HR portal.",
             metadata={"document_id": "handbook-v2", "access_tags": ["employees"]}),
    Document(page_content="The board approved a revised compensation plan.",
             metadata={"document_id": "board-minutes", "access_tags": ["board"]}),
])

only_employees = models.Filter(must=[
    models.FieldCondition(key="metadata.access_tags", match=models.MatchAny(any=["employees"]))])
hits = store.similarity_search_with_score("How do I request time off?", k=2, filter=only_employees)
retriever = store.as_retriever(search_kwargs={"k": 1, "filter": only_employees})

The search returned a single hit (score 0.433, the handbook sentence) because the board chunk was filtered out. The detail to remember is the payload layout: LangChain stores the text under page_content and the metadata under a nested metadata object, so a filter key is metadata.access_tags, not access_tags. A collection written by hand with the flat layout of the example below cannot be queried through this store unless the payload keys are mapped. The store accepts a Qdrant filter, which is where the access control of the previous section plugs in.

Example: ingestion and retrieval with qdrant-client

The example below uses qdrant-client directly, since it is the layer both LangChain’s and LlamaIndex’s integrations sit on top of. It is complete and runnable: instead of a model download it uses a toy embedding that hashes each word into one of 128 buckets, so retrieval quality is that of a bag of words, but every Qdrant call is exactly what a real pipeline makes. Replace embed_one with a call to an embedding model and set DIM to its output size, and nothing else changes. It creates the collection, indexes the payload fields the filters will use, and ingests a three-section corpus:

import hashlib
import math
import re
import uuid

from qdrant_client import QdrantClient
from qdrant_client.models import (
    Distance, FieldCondition, Filter, FilterSelector, MatchAny, MatchValue,
    PayloadSchemaType, PointStruct, VectorParams,
)

client = QdrantClient(url="http://localhost:6333")
DIM = 128  # must match the embedding model's output dimension
STOP = {"the", "a", "an", "of", "to", "is", "are", "and", "in", "on", "for", "you", "your",
        "must", "do", "how", "i", "can", "with", "it", "be", "by", "at", "or"}


def embed_one(text):
    """Toy embedding: hash every word into one of DIM buckets, then L2-normalise.
    Stands in for a real model (sentence-transformers, an embeddings API, ...)."""
    vec = [0.0] * DIM
    for word in re.findall(r"[a-z]+", text.lower()):
        if word in STOP:
            continue
        word = word.rstrip("s")  # crude stemming: "requests" -> "request"
        vec[int(hashlib.md5(word.encode()).hexdigest(), 16) % DIM] += 1.0
    norm = math.sqrt(sum(v * v for v in vec)) or 1.0
    return [v / norm for v in vec]


def chunk_document(text, max_chars=200):
    """Sentence-based chunking: pack whole sentences into chunks of at most max_chars."""
    sentences = re.split(r"(?<=[.!?])\s+", text.strip())
    chunks, current = [], ""
    for sentence in sentences:
        if current and len(current) + 1 + len(sentence) > max_chars:
            chunks.append(current)
            current = sentence
        else:
            current = f"{current} {sentence}".strip()
    if current:
        chunks.append(current)
    return chunks


def ingest(document_id, section_title, access_tags, text):
    """Replace every chunk of one document section: delete the old ones, upsert the new ones."""
    client.delete(
        "kb_chunks", wait=True,
        points_selector=FilterSelector(filter=Filter(must=[
            FieldCondition(key="document_id", match=MatchValue(value=document_id)),
            FieldCondition(key="section_title", match=MatchValue(value=section_title)),
        ])),
    )
    chunks = chunk_document(text)
    client.upsert("kb_chunks", wait=True, points=[
        PointStruct(
            id=str(uuid.uuid5(uuid.NAMESPACE_URL, f"{document_id}/{section_title}#{i}")),
            vector=embed_one(chunk),
            payload={"document_id": document_id, "chunk_index": i, "section_title": section_title,
                     "access_tags": access_tags, "text": chunk},
        )
        for i, chunk in enumerate(chunks)
    ])
    return len(chunks)


if client.collection_exists("kb_chunks"):
    client.delete_collection("kb_chunks")
client.create_collection("kb_chunks", vectors_config=VectorParams(size=DIM, distance=Distance.COSINE))
for field in ("access_tags", "document_id", "section_title"):
    client.create_payload_index("kb_chunks", field, PayloadSchemaType.KEYWORD)

ingest("handbook-v2", "Time off", ["employees"],
    "Employees request time off through the HR portal. Choose the dates, pick the leave type and submit "
    "the request to your manager. Annual leave must be requested at least two weeks in advance, while sick "
    "leave can be reported on the same day. Approved requests appear in the shared team calendar.")
ingest("handbook-v2", "Expenses", ["employees"],
    "Travel expenses are reimbursed within thirty days. Attach every receipt to the expense report and "
    "submit it from the finance portal. Meals are reimbursed up to a daily limit; alcohol is never reimbursed.")
ingest("board-minutes", "Compensation", ["board"],
    "The board approved a revised compensation plan for executives. Bonus targets for next year were raised, "
    "and the time off policy for executives was left unchanged.")
print("points:", client.count("kb_chunks").count)

Running it produced two chunks for the time-off section, two for expenses and one for the board minutes, and points: 5.

The query-time path embeds the user’s question, searches with and without an access filter, re-ranks, and assembles the retrieved chunks into the LLM’s prompt context:

query = "How do I request time off?"
query_vector = embed_one(query)


def show(label, **kwargs):
    hits = client.query_points("kb_chunks", query=query_vector, limit=4, **kwargs).points
    print(label)
    for h in hits:
        p = h.payload
        print("  %.3f  %-13s #%d  %s" % (h.score, p["document_id"], p["chunk_index"], p["text"][:60]))
    return hits


show("no filter")
only_employees = Filter(must=[FieldCondition(key="access_tags", match=MatchAny(any=["employees"]))])
hits = show("employees only", query_filter=only_employees)

# Optional re-ranking pass: order the candidates by how many query words they contain.
query_words = set(re.findall(r"[a-z]+", query.lower())) - STOP


def overlap(hit):
    return len(query_words & set(re.findall(r"[a-z]+", hit.payload["text"].lower())))


top = sorted(hits, key=overlap, reverse=True)[:2]
context = "\n\n".join(f"[{h.payload['section_title']} #{h.payload['chunk_index']}]\n{h.payload['text']}"
                      for h in top)
prompt = f"Answer the question using only the context below.\n\nContext:\n{context}\n\nQuestion: {query}"

The two show calls printed:

no filter
  0.560  handbook-v2   #0  Employees request time off through the HR portal. Choose the
  0.241  board-minutes #0  The board approved a revised compensation plan for executive
  0.120  handbook-v2   #1  Annual leave must be requested at least two weeks in advance
  0.000  handbook-v2   #0  Travel expenses are reimbursed within thirty days. Attach ev
employees only
  0.560  handbook-v2   #0  Employees request time off through the HR portal. Choose the
  0.120  handbook-v2   #1  Annual leave must be requested at least two weeks in advance
  0.000  handbook-v2   #0  Travel expenses are reimbursed within thirty days. Attach ev
  0.000  handbook-v2   #1  Meals are reimbursed up to a daily limit; alcohol is never r

and the assembled prompt was:

Answer the question using only the context below.

Context:
[Time off #0]
Employees request time off through the HR portal. Choose the dates, pick the leave type and submit the request to your manager.

[Time off #1]
Annual leave must be requested at least two weeks in advance, while sick leave can be reported on the same day. Approved requests appear in the shared team calendar.

Question: How do I request time off?

Access control belongs in the filter

The first listing above is the reason the access_tags payload exists. Without a filter the board minutes (score 0.241) rank second for an ordinary employee’s question about time off, because they mention the same topic. The filter in the second listing removes the board chunk before ranking, so it can never reach the prompt. Two rules follow. The filter must be built on the server side from the authenticated caller’s entitlements, never from a value the client sends. And it should be enforced even where only one tenant is expected today, since retrofitting it after the first leak is much harder. For per-collection or per-tenant isolation that does not depend on every query remembering a filter, use Qdrant’s JWT-scoped access tokens described in Security & Administration.

Keeping the index in sync with the sources

Documents change, and a RAG index that serves stale text is worse than none. The ingest function above is the whole synchronization mechanism: it deletes every chunk of a section by filter and writes the new chunks. The number of chunks may change between versions, which is why replacing by document_id and section_title is safer than upserting by id alone (an upsert would leave orphaned trailing chunks when a section gets shorter). Re-ingesting the time-off section with a shorter text printed 1, and the collection went from five points to four, with the new text, not the old, returned for the same question. Pair this with a stable document_id per source file and a job that re-ingests only the documents whose content hash changed.

Evaluating retrieval

Retrieval quality should be measured, not assumed. The smallest useful evaluation is a list of questions with the section that should answer each, and the hit rate at 1 (how often the top result comes from the expected section). With the toy embedding, three questions produced:

How do I request time off?                 -> Time off
When are travel expenses reimbursed?       -> Expenses
Can I report sick leave on the same day?   -> Expenses     (expected: Time off)
hit rate@1: 0.67

The miss is informative: the question says "report" and the chunk says "reported", the crude stemmer does not unify them, and the expense chunk wins on the words it happens to share. A real embedding model, a hybrid search that adds a sparse vector (see Hybrid & Sparse Search), or a re-ranker would fix this specific miss; the evaluation is what tells you which of those is worth adding. Grow the list from real user questions, and re-run it every time the chunking, the model or the filters change.