All writing
qdrant vector-database python rag

Qdrant Python query_points: Filters, Hybrid Search & Tuning

Ayush Kaushik 5 min read
Qdrant Python query_points: Filters, Hybrid Search & Tuning

I switched every production search path to qdrant python query_points six months ago because the legacy search and recommend methods are deprecated and lack hybrid vector support. The new API unifies dense vectors, sparse vectors, and payload filters into a single request object which makes the client code simpler and the query planner smarter. Below is what I wish I had known before rolling it out to traffic.

Understanding the query_points API vs legacy search methods

The query_points method replaces search, recommend, and discover with one consistent interface that accepts a QueryRequest object. You pass a prefetch list for multi-stage retrieval, a query object for the final scoring vector, and a filter for payload conditions all in one round trip.

from qdrant_client import QdrantClient, models
client = QdrantClient(url="http://localhost:6333")
response = client.query_points(
collection_name="docs",
query=models.Document(text="error handling in async python", model="sentence-transformers/all-MiniLM-L6-v2"),
prefetch=[
models.Prefetch(
query=models.SparseVector(
indices=[312, 845, 1024],
values=[0.8, 0.5, 0.3]
),
using="bm25",
limit=50
)
],
limit=10,
with_payload=True
)

The legacy search method still works but it cannot express the prefetch pattern above. If you are on client version 1.7 or newer you should migrate. I wrote about the FastAPI integration pattern in Using the Qdrant Python Client with FastAPI if you need the DI setup.

How do I implement filtered vector search with payload conditions?

You attach a filter parameter to the request using the same Filter DSL the old API used. The difference is the filter now applies to both the prefetch stages and the final scoring stage automatically.

from qdrant_client import models
filter_condition = models.Filter(
must=[
models.FieldCondition(key="tenant_id", match=models.MatchValue(value="acme-corp")),
models.FieldCondition(key="status", match=models.MatchValue(value="published"))
],
should=[
models.FieldCondition(key="tags", match=models.MatchAny(any=["python", "fastapi"]))
]
)
response = client.query_points(
collection_name="docs",
query=models.Document(text="deployment strategies", model="sentence-transformers/all-MiniLM-L6-v2"),
query_filter=filter_condition,
limit=20
)

One gotcha: the query_filter parameter name differs from the old query_filter in search only by position in the signature. Double check the keyword argument because passing it as a positional argument breaks silently when the client adds new parameters.

Optimizing hybrid search using sparse and dense vectors

Hybrid search is the main reason to adopt query_points. You define a sparse vector index named bm25 or splade in the collection config then reference it in prefetch. The dense vector runs on the default named vector unless you specify using.

# Collection creation snippet
client.create_collection(
collection_name="hybrid_docs",
vectors_config={
"dense": models.VectorParams(size=384, distance=models.Distance.COSINE)
},
sparse_vectors_config={
"bm25": models.SparseVectorParams(index=models.SparseIndexParams(on_disk=False))
}
)
# Query time
response = client.query_points(
collection_name="hybrid_docs",
prefetch=[
models.Prefetch(query=sparse_vector, using="bm25", limit=100),
models.Prefetch(query=dense_vector, using="dense", limit=100)
],
query=models.FusionQuery(fusion=models.Fusion.RRF),
limit=10
)

RRF fusion works well out of the box. I have seen DPR fusion degrade when the dense model drifts from the training distribution. Stick with RRF until you have labeled relevance data to tune weights.

What HNSW parameters actually move the needle on latency vs accuracy?

Three parameters matter in production: m, ef_construct, and ef. m controls graph connectivity at build time. ef_construct controls build quality. ef controls search time recall.

client.update_collection(
collection_name="hybrid_docs",
hnsw_config=models.HnswConfigDiff(
m=16,
ef_construct=100,
full_scan_threshold=10000,
on_disk=True
)
)
# Per query override
response = client.query_points(
collection_name="hybrid_docs",
query=dense_vector,
search_params=models.SearchParams(hnsw_ef=128, exact=False),
limit=10
)

My rule of thumb: set m=16 and ef_construct=100 for most 768-dim workloads. Raise ef at query time only for the top 5 percent of traffic that needs higher recall. Keep on_disk=True once the collection exceeds RAM. The full_scan_threshold avoids HNSW overhead for tiny collections.

Pagination patterns for large result sets in production

query_points supports offset and limit but deep pagination on HNSW is expensive because the graph walk restarts every request. Use scroll for exports or infinite scroll UIs where the user paginates sequentially.

# Deep pagination: avoid offset > 1000
# Instead use scroll with a cursor
scroll_result = client.scroll(
collection_name="docs",
scroll_filter=filter_condition,
limit=100,
with_payload=True,
with_vectors=False
)
# scroll_result[1] is the next_page_offset (opaque string)

If you must paginate search results, cache the prefetch stage and only re-run the final fusion step. That requires a custom two-phase client wrapper which I cover in Qdrant Python Search: Filters, Hybrid Vectors & Tuning.

Error handling and retry logic for resilient Qdrant clients

Network blips happen. The client raises UnexpectedResponse for 5xx and ApiException for 4xx. Wrap calls with tenacity and respect the Retry-After header.

from tenacity import retry, stop_after_attempt, wait_exponential_jitter, retry_if_exception_type
from qdrant_client.http.exceptions import UnexpectedResponse, ApiException
@retry(
wait=wait_exponential_jitter(initial=0.1, max=2.0),
stop=stop_after_attempt(3),
retry=retry_if_exception_type((UnexpectedResponse, ConnectionError, TimeoutError))
)
def safe_query_points(client, **kwargs):
return client.query_points(**kwargs)
# Usage
try:
response = safe_query_points(client, collection_name="docs", query=dense_vector, limit=10)
except UnexpectedResponse as e:
if e.status_code == 429:
# Rate limited, back off longer
pass
logger.error("Qdrant query failed", extra={"error": str(e)})
raise

Do not retry 4xx errors except 429. A 400 means your payload filter is malformed and retrying will not fix it. I learned that during a bad deploy where a schema change broke the filter DSL and the retry loop hammered the cluster for five minutes.

FAQ

Does query_points support batch queries? Yes. Pass a list of QueryRequest objects to query_points_batch. It reduces network round trips but increases single request latency. Use it for offline jobs not user facing APIs.

Can I mix named vectors and the default vector in one query_points call? Yes. Each Prefetch and the final query can specify a different using parameter pointing to any named vector or sparse vector configured on the collection.

What is the maximum limit for a single query_points request? The server defaults to 10,000. You can raise it in the collection config hnsw_config.payload_m but large limits increase memory pressure on the query node. Prefer scroll for full scans.

How do I debug why a filter returns zero hits? Run the filter alone with scroll and limit=1 to verify payload values match exactly. Field names are case sensitive and MatchValue requires exact type equality including integer vs float.

Key Takeaways

  • Migrate to query_points now. The legacy methods are frozen and lack hybrid search.
  • Use prefetch with RRF fusion for hybrid sparse-dense retrieval. It outperforms weighted sums without tuning.
  • Set HNSW m=16, ef_construct=100 at build time. Tune ef per query only for high value traffic.
  • Avoid deep offset pagination. Use scroll or cache the prefetch stage.
  • Retry only 5xx and 429 errors. Surface 4xx immediately so bad deployments fail fast.

Working on something similar?

If you're building backend or AI systems and want a second set of senior eyes, let's talk.

Keep reading

Related articles