Qdrant Tutorial for RAG

Run Qdrant, create collections, upsert points with payloads, and search with filters and hybrid queries.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 6 · Lesson 6 of 13 · Intermediate

Qdrant Tutorial for RAG

Run Qdrant, create collections, upsert points with payloads, and search with filters and hybrid queries.

Qdrant is an open-source vector database written in Rust, popular for RAG because of its fast filtered search, rich payload (metadata) filtering, built-in hybrid search with sparse vectors, and simple deployment. You can run it in Docker, on Kubernetes or as Qdrant Cloud. In this lesson you run Qdrant locally, create a collection, upsert chunks with payloads, index payload fields, and run filtered and hybrid searches for an enterprise RAG pipeline.

What you will learn

  • How to run Qdrant and connect with the Python client
  • How to create collections, upsert points and create payload indexes
  • How to search with query_points and payload filters for permissions and tenants
  • How to combine dense and sparse vectors in one hybrid query with RRF

Prerequisites

Version note

Written against the Qdrant documentation of November 2026, which uses query_points for search (older tutorials use search). The code has not been executed against a live server for this tutorial; check the Qdrant documentation for your client version.

Step 1: Run Qdrant

docker run -d --name qdrant -p 6333:6333 -p 6334:6334 \
  -v qdrant_storage:/qdrant/storage \
  qdrant/qdrant

pip install -U qdrant-client sentence-transformers anthropic python-dotenv

Port 6333 serves the REST API (and a web dashboard at http://localhost:6333/dashboard); 6334 serves gRPC. The named volume keeps data across container restarts. In production, pin an image version and enable API-key authentication and TLS.

Step 2: Create a collection and payload indexes

qdrant_setup.py
from qdrant_client import QdrantClient, models

client = QdrantClient(url="http://localhost:6333")        # add api_key=... for secured servers
COLLECTION = "enterprise_docs"

client.create_collection(
    collection_name=COLLECTION,
    vectors_config={"dense": models.VectorParams(size=384, distance=models.Distance.COSINE)},
    sparse_vectors_config={"sparse": models.SparseVectorParams(modifier=models.Modifier.IDF)},
)
for field in ("tenant_id", "allowed_groups", "department", "doc_id"):
    client.create_payload_index(collection_name=COLLECTION, field_name=field,
                                field_schema=models.PayloadSchemaType.KEYWORD)
print("collection ready")

The collection has two named vectors per point: a dense embedding (384 dimensions for bge-small-en-v1.5) and a sparse keyword vector. With Modifier.IDF, Qdrant computes inverse document frequency on the server, so the sparse vector you send only needs term frequencies, which gives BM25-like keyword scoring.

Create payload indexes before ingesting for every field you filter on. Without them, filtered searches over large collections become slow, and Qdrant cannot plan filtered vector search efficiently. To re-run the script, delete the collection first with client.delete_collection(COLLECTION).

Step 3: Upsert chunks with payloads

Each point has an id, its vectors and a payload with the chunk text and metadata. Here the sparse vector is built with a simple hashed term-frequency function, so the example needs no extra model:

qdrant_ingest.py
import re
import uuid
import zlib
from collections import Counter

from qdrant_client import QdrantClient, models
from rag_helpers import embed

client = QdrantClient(url="http://localhost:6333")
COLLECTION = "enterprise_docs"

def sparse_vector(text: str) -> models.SparseVector:
    """Term frequencies keyed by a stable hash of each token (IDF is applied by Qdrant)."""
    counts = Counter(zlib.crc32(tok.encode()) for tok in re.findall(r"[a-z0-9]+", text.lower()))
    return models.SparseVector(indices=list(counts), values=[float(v) for v in counts.values()])

CHUNKS = [
    {"doc_id": "hr-leave", "text": "Employees get 18 days of paid leave in their first year.",
     "tenant_id": "acme", "allowed_groups": ["staff"], "department": "hr"},
    {"doc_id": "hr-salary", "text": "Salary band L5 ranges from 90,000 to 120,000 EUR.",
     "tenant_id": "acme", "allowed_groups": ["hr", "leadership"], "department": "hr"},
    {"doc_id": "it-vpn", "text": "Error VPN-403 means your device certificate has expired.",
     "tenant_id": "acme", "allowed_groups": ["staff"], "department": "it"},
]
vectors = embed([c["text"] for c in CHUNKS])
client.upsert(
    collection_name=COLLECTION,
    wait=True,
    points=[models.PointStruct(
        id=str(uuid.uuid5(uuid.NAMESPACE_URL, f"{c['doc_id']}#0")),     # stable id per chunk
        vector={"dense": vectors[i].tolist(), "sparse": sparse_vector(c["text"])},
        payload=c,
    ) for i, c in enumerate(CHUNKS)],
)
print("upserted", len(CHUNKS))

Point ids must be unsigned integers or UUIDs. A UUID derived from the document id and chunk number makes re-ingestion idempotent: upserting the same chunk again replaces it instead of duplicating it.

Step 4: Filtered vector search

Every enterprise search must carry the user's tenant and groups. MatchAny matches points whose allowed_groups list contains any of the given values:

qdrant_search.py
from qdrant_client import QdrantClient, models
from rag_helpers import embed
from qdrant_ingest import sparse_vector

client = QdrantClient(url="http://localhost:6333")
COLLECTION = "enterprise_docs"

def permission_filter(tenant_id: str, groups: list[str], department: str | None = None) -> models.Filter:
    must = [models.FieldCondition(key="tenant_id", match=models.MatchValue(value=tenant_id)),
            models.FieldCondition(key="allowed_groups", match=models.MatchAny(any=groups))]
    if department:
        must.append(models.FieldCondition(key="department", match=models.MatchValue(value=department)))
    return models.Filter(must=must)

def dense_search(question: str, tenant_id: str, groups: list[str], k: int = 5):
    return client.query_points(
        collection_name=COLLECTION,
        query=embed(question, query=True)[0].tolist(),
        using="dense",
        query_filter=permission_filter(tenant_id, groups),
        with_payload=True,
        limit=k,
    ).points

for point in dense_search("What is the salary range for L5?", "acme", ["staff"]):
    print(f"{point.score:.3f}  {point.payload['doc_id']}  {point.payload['text']}")
0.512  hr-leave  Employees get 18 days of paid leave in their first year.
0.371  it-vpn  Error VPN-403 means your device certificate has expired.

A user in the staff group never sees the salary chunk, even though it is the best match: the filter is applied inside the search, not afterwards. With cosine distance, Qdrant's score is a similarity (higher is closer). Your exact scores will differ.

Step 5: Hybrid search with RRF

Exact codes such as VPN-403 are where keyword matching beats embeddings. A hybrid query runs a dense and a sparse search as prefetches and fuses their rankings with Reciprocal Rank Fusion, all in one request:

def hybrid_search(question: str, tenant_id: str, groups: list[str], k: int = 5):
    flt = permission_filter(tenant_id, groups)
    return client.query_points(
        collection_name=COLLECTION,
        prefetch=[
            models.Prefetch(query=embed(question, query=True)[0].tolist(), using="dense",
                            filter=flt, limit=20),
            models.Prefetch(query=sparse_vector(question), using="sparse", filter=flt, limit=20),
        ],
        query=models.RrfQuery(rrf=models.Rrf()),
        with_payload=True,
        limit=k,
    ).points

for point in hybrid_search("what does VPN-403 mean", "acme", ["staff"]):
    print(f"{point.score:.3f}  {point.payload['doc_id']}")

Apply the permission filter in each prefetch, so neither branch can surface restricted points. RRF scores are rank-based, so compare them only within one result list. For a production keyword vector, use a real sparse model (BM25 tokenisation with stemming, or a learned sparse model such as SPLADE) instead of the hashing function above.

Step 6: Update and delete documents

def delete_document(doc_id: str) -> None:
    client.delete(
        collection_name=COLLECTION,
        points_selector=models.FilterSelector(filter=models.Filter(must=[
            models.FieldCondition(key="doc_id", match=models.MatchValue(value=doc_id))])),
    )

delete_document("it-vpn")       # then upsert the new chunks of the updated document

Deleting by doc_id before re-inserting removes chunks that no longer exist in the new version (for example, when a document gets shorter).

Enterprise considerations

  • Multi-tenancy: for many tenants, a single collection with an indexed tenant_id payload is usually better than one collection per tenant; Qdrant's documentation describes tenant-optimised indexing for this pattern.
  • Security: enable API keys and TLS; never expose the port publicly; filter by verified identity only.
  • Memory: use quantization and on-disk storage for large collections (Optimizing Vector Database Performance).
  • Backups: use snapshots and test restores.

Common errors and troubleshooting

  • "Wrong input: Vector dimension error": the vector size does not match the collection's size.
  • Invalid point id: ids must be unsigned integers or UUID strings, not arbitrary strings.
  • Slow filtered search: create payload indexes for filtered fields.
  • No results for named vectors: pass using="dense" (or the sparse name) when the collection has named vectors.
  • AttributeError: search or deprecation warnings in old examples: use query_points.

Key takeaways

  • Qdrant stores points with named dense and sparse vectors and a JSON payload.
  • Create payload indexes for filtered fields before ingesting.
  • query_points handles dense, sparse, filtered and hybrid (prefetch + RRF) searches.
  • Use stable point ids and delete by doc_id for clean updates; filter every query by tenant and groups.

Frequently asked questions

Can Qdrant run without a server?

The Python client also offers a local mode for tests and notebooks; check the client documentation for your version. Use a server for anything shared or persistent.

Qdrant or pgvector?

pgvector is simplest if you already run PostgreSQL and want transactions and joins; Qdrant offers more vector-search features and tuning. See Choosing a Vector Database.

Practice exercises

  1. Compare dense-only and hybrid search on ten questions that contain product codes or error numbers.
  2. Add a valid_until date payload with a range filter so that expired documents are never returned.

Related tutorials