How to Use Deep Query Filtering in Vector Search for Structured + Unstructured Data
From the publisher’s feed, collected in the ZeroLabs newsroom.
Why pure semantic search is not enough — and how I composed meaning + rules in a single Qdrant query.I was building a venue discovery feature. The idea was simple: a user describes what they are looking for in natural language, and the app surfaces the best matches from a catalogue of thousands of places.The semantic search part worked beautifully. I embedded descriptions, ran an ANN search, and the results felt impressively relevant. Then I added real-world constraints. Price filters. Location radius. Open now. No tourist traps. And the entire thing fell apart.My first instinct was to add more context to the embeddings. I rewrote the descriptions to include price tiers, neighbourhoods, and opening hours. It helped a little, but it was fighting the wrong battle. Embeddings are not meant to encode hard rules. They encode meaning. And no amount of prompt engineering changes the fact that “within 2 km of Plaça de Catalunya” is a geometric constraint, not a semantic one.That is when I moved to Qdrant’s payload filtering system — and it solved the problem completely. Not as a workaround but as the intended architecture.Why I Used Qdrant for This ProjectI have worked with a few vector databases. What sets Qdrant apart for me is not raw performance benchmarks — it is the philosophy behind how it handles the structured side of search.Qdrant does not treat filtering as an afterthought. The filtering system is a first-class citizen: rich condition types, recursive boolean logic, geo support, nested object filtering, and datetime ranges. It handles the full complexity of real product requirements without forcing me to denormalise my data or write post-retrieval cleanup code.On top of that, the Python client is clean and well-documented. The in-memory mode means I can prototype the full filter logic in a Colab notebook with zero infrastructure — no Docker, no cloud account, no API key.The short version: Qdrant lets me express what I actually need, in the layer where it belongs, without compromise.📓 Full runnable notebook: Colab Notebook LinkZero infrastructure. Runs entirely in Google Colab with free local embeddings via FastEmbed. No OpenAI key required.Part 1 — The Concept1.1 What “Deep Query Filtering” Actually MeansWhen I say deep query filtering, I am not talking about deep learning. I am talking about the depth of the Boolean logic I compose alongside my vector search.Standard vector search retrieves by semantic similarity. That is its job. Deep query filtering means layering hard constraints on top of that retrieval — geo proximity, opening hours, price tier, rating threshold, tag exclusions — all pushed into the search itself, not applied afterwards. Ineligible points never enter your result set.This matters enormously at scale. If a collection has a million points and the filters eliminate 90% of them, the effective search space is 100,000 points. The query planner sees this. A well-indexed, highly selective filter does not just give you correct results — it gives you faster results than an unfiltered search over the full collection.1.2 The Mental Model: Unstructured Recall + Structured PrecisionI think of every search as two layers, each doing one job and doing it well.Layer 1 — Vectors (recall): I embed the user’s natural language query and run an ANN search. This layer handles the subjective, fuzzy part: something like a cosy neighbourhood tapas bar with marble counters and house vermouth. No structured field can capture that intent. Only the embedding can.Layer 2 — Payload filters (precision): I apply hard business constraints on the structured JSON fields stored alongside each vector. Within 2 km of Plaça de Catalunya. Price tier at most 2. Open right now. Rating above 4.2. These have a correct answer. They should never be approximated by a similarity score.Qdrant documentation frames it exactly right: setting additional conditions is important when it is impossible to express all the features of the object in the embedding. Price, location, availability, and access rules — these are exactly those features.The moment I internalised this split, I stopped trying to encode business rules in embeddings.Figure 1 - The Two-Layer Search Architecture1.3 The Logic Primitives — Three Clauses That Cover EverythingQdrant’s filter system rests on three logical clauses. Everything I have ever needed to express fits into these three primitives:The key is that these clauses are recursively nestable. An Filter object can sit inside a should list, which can itself sit inside a must list. This allows me to build arbitrary boolean expressions — OR-of-ANDs, AND-of-ORs, any combination — without any post-processing. That is the "deep" part.Figure 2 — The Three Boolean Primitives and Recursive Nesting1.4 What I Store: Payload as Structured TruthEvery Qdrant point has two parts: a vector (the embedding) and a payload (a JSON object of structured fields). The payload is the structured truth — the facts the filters operate on.The design principle is simple: meaning goes in the vector, facts go in the payload. For my Barcelona tapas demo, the split looks like this:Table 1: Barcelona tapas dataset payload schema — every field mapped to the filter type it enables.The unstructured text description — “Classic Catalan tapas bar, marble counters, patatas bravas, beloved by locals” — becomes the vector. Everything else is payload. The vector captures the vibe. The payload captures the facts.1.5 How I Wire This Into an AI WorkflowThe pattern I use in every project that combines semantic search with structured filtering has three steps:Store: every record has both a structured JSON payload (for constraints) and an unstructured text description (embedded as a vector).Parse: every incoming query is run through a Pydantic schema that explicitly separates the semantic intent from the structured constraints before anything touches Qdrant.Query: call Qdrant with the semantic text embedded and the structured fields as a filter object. One request. One result set that satisfies both.The Pydantic parse step is the one I see skipped most often, and it matters most. Without it, developers end up encoding business rules in the embedding — the wrong layer — or filtering in application code after retrieval, which is both expensive and fragile.Here is what the query parser looks like, taken directly from the notebook:from qdrant_client import QdrantClient, modelsfrom pydantic import BaseModelfrom typing import Optional, Listclass TapasSearchQuery(BaseModel): """Typed query object - separates semantic intent from structured constraints.""" # Unstructured: goes into the vector embedding semantic_text: str # Structured: become Qdrant filter conditions max_price_tier: Optional[int] = None min_rating: Optional[float] = None open_now: Optional[bool] = None neighborhoods: Optional[List[str]] = None exclude_tags: Optional[List[str]] = None geo_radius_metres: Optional[float] = None center_lat: Optional[float] = None center_lon: Optional[float] = None def to_qdrant_filter(self) -> Optional[models.Filter]: must_clauses = [] must_not_clauses = [] if self.max_price_tier is not None: must_clauses.append( models.FieldCondition(key="price_tier", range=models.Range(lte=self.max_price_tier)) ) if self.min_rating is not None: must_clauses.append( models.FieldCondition(key="rating", range=models.Range(gte=self.min_rating)) ) if self.open_now is not None: must_clauses.append( models.FieldCondition(key="open_now", match=models.MatchValue(value=self.open_now)) ) if self.neighborhoods: must_clauses.append( models.FieldCondition(key="neighborhood", match=models.MatchAny(any=self.neighborhoods)) ) if self.geo_radius_metres and self.center_lat and self.center_lon: must_clauses.append( models.FieldCondition( key="geo", geo_radius=models.GeoRadius( center=models.GeoPoint(lat=self.center_lat, lon=self.center_lon), radius=self.geo_radius_metres, ), ) ) if self.exclude_tags: for tag in self.exclude_tags: must_not_clauses.append( models.FieldCondition(key="tags", match=models.MatchValue(value=tag)) ) if not must_clauses and not must_not_clauses: return None return models.Filter( must= must_clauses or None, must_not= must_not_clauses or None, )This schema makes the contract explicit and enforced. semantic_text feeds the embedding. Everything else feeds the filter. When requirements change, I add a field to the schema and a clause to to_qdrant_filter. Nowhere else.Part 2 — What Qdrant Enables2.1 The Complete Tapas Search Walkthrough“Find tapas bars like this, near Placa de Catalunya, cheap-ish, highly rated, open now.”This is the hero query. It has a semantic component — the vibe of the place — and five hard constraints that have nothing to do with semantics. Here is how each part maps:Table 2: Hero query decomposition — how each requirement maps to a layer and a Qdrant mechanism.The vector is retrieved by meaning. The filter enforces eligibility. Here is the full query from the notebook — one call, no post-processing:from qdrant_client import QdrantClient, modelsclient = QdrantClient(":memory:")COLLECTION = "barcelona_tapas"PLAZA_LAT = 41.3870PLAZA_LON = 2.1700query_text = ( "Authentic local tapas bar with marble counter, pan con tomate, " "patatas bravas, and a warm neighbourhood atmosphere")hero_filter = models.Filter( must=[ # 1. Geo: within 2 km of Placa de Catalunya models.FieldCondition( key="geo", geo_radius=models.GeoRadius( center=models.GeoPoint(lat=PLAZA_LAT, lon=PLAZA_LON), radius=2000.0, ), ), # 2. Price: budget or mid-range only models.FieldCondition(key="price_tier", range=models.Range(lte=2)), # 3. Rating threshold models.FieldCondition(key="rating", range=models.Range(gte=4.2)), # 4. Open right now models.FieldCondition(key="open_now", match=models.MatchValue(value=True)), ], must_not=[ # 5. Exclude tourist traps models.FieldCondition(key="tags", match=models.MatchValue(value="tourist-trap")), ],)hits = client.query( collection_name=COLLECTION, query_text=query_text, query_filter=hero_filter, limit=5,)for hit in hits: p = hit.metadata print(f"score={hit.score:.4f} {p['name']:26} " f"rating={p['rating']} tier={p['price_tier']} {p['neighborhood']}")Output on the demo dataset:score=0.9372 Bar del Pla rating=4.5 tier=2 Gothic Quarterscore=0.8661 Born Brunch & Tapes rating=4.2 tier=2 El Bornscore=0.8448 Vins i Tapes PG rating=4.4 tier=2 EixampleWhat did the filter quietly remove? The tourist trap near Las Ramblas. The closed gem in El Born. The Michelin venue at tier 3. The fusion bar outside the radius. None of them pollutes the result set. The user gets exactly what they asked for: semantically relevant and operationally eligible.Figure 3 — Hero Query: One Call, Two Layers Working Together2.2 Every Condition Type — Mapped to Real App NeedsHere is every filter condition Qdrant provides, each with the real product requirement it handles. All code is taken directly from the working notebook.must — AND: All conditions must holdMy default clause. Every condition in the list must be true. Use this for anything that is a hard AND requirement.# Eixample AND open now — both must be true simultaneouslyresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.FieldCondition(key="neighborhood", match=models.MatchValue(value="Eixample")), models.FieldCondition(key="open_now", match=models.MatchValue(value=True)), ] ), with_payload=True,)should — OR: Any condition is enoughA point passes if it satisfies at least one condition. Use this for multi-neighbourhood searches, multiple accepted categories, or any either/or requirement.# Gothic Quarter OR El Born — either neighbourhood is fineresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( should=[ models.FieldCondition(key="neighborhood", match=models.MatchValue(value="Gothic Quarter")), models.FieldCondition(key="neighborhood", match=models.MatchValue(value="El Born")), ] ), with_payload=True,)must_not — NOT: None of these may appearExclusion logic. A point passes only if it matches none of the listed conditions. My go-to for blocked labels, banned categories, and content filters.# Exclude all tourist-trap tagged venuesresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must_not=[ models.FieldCondition(key="tags", match=models.MatchValue(value="tourist-trap")), ] ), with_payload=True,)MatchAny — SQL IN (...): match any value from a listFar more concise than multiple should clauses in the same field. Qdrant resolves this as a single index operation.# Cuisine must be catalan OR basque — one condition, handled at index speedresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.FieldCondition( key="cuisines", match=models.MatchAny(any=["catalan", "basque"]), ), ] ), with_payload=True,)MatchExcept — SQL NOT IN (...): exclude a list of valuesThe inverse of MatchAny. Note that it except is a Python reserved word — pass it via ** unpacking.# Exclude fusion and brunch cuisines from resultsresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.FieldCondition( key="cuisines", match=models.MatchExcept(**{"except": ["fusion", "brunch"]}), ), ] ), with_payload=True,)Range — Numeric constraints for price and ratingsSupports gt, gte, lt, lte on integers and floats. Combine bounds in a single Range for a double-sided constraint.# rating >= 4.2 AND price_tier results, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.FieldCondition(key="rating", range=models.Range(gte=4.2)), models.FieldCondition(key="price_tier", range=models.Range(lte=2)), ] ), with_payload=True,)DatetimeRange — Freshness windows and time-bounded accessQdrant accepts RFC 3339 strings directly — no Unix timestamp conversion needed. (DatetimeRange docs)# Venues added after 2024-11-01 — a freshness windowcutoff = "2024-11-01T00:00:00Z"results, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.FieldCondition( key="added_at", range=models.DatetimeRange(gte=cutoff), ), ] ), with_payload=True,)GeoRadius — Proximity circleThis condition finds all points within a radius, measured in metres, of a lat/lon centre point. It is the primary tool for location-based discovery.# Within 2 km of Placa de Catalunyaresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.FieldCondition( key="geo", geo_radius=models.GeoRadius( center=models.GeoPoint(lat=PLAZA_LAT, lon=PLAZA_LON), radius=2000.0, # metres ), ), ] ), with_payload=True,)GeoBoundingBox — Rectangular map viewportThis condition matches all points within a rectangular bounding box defined by a top-left and bottom-right corner. I use it for map-tile UIs where results need to stay inside the visible viewport.# Approximate bounding box for central Barcelonaresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.FieldCondition( key="geo", geo_bounding_box=models.GeoBoundingBox( top_left= models.GeoPoint(lat=41.3960, lon=2.1550), bottom_right=models.GeoPoint(lat=41.3780, lon=2.1870), ), ), ] ), with_payload=True,)MatchText — Full-text keyword search on a payload fieldTokenised word matching on a string payload field. Requires a TEXT payload index. Useful when keyword-level search on a field value is needed alongside vector similarity — for example, when filtering by a word in a venue name.# Venues whose name contains the token "tapes" (case-insensitive)# Requires a TEXT index created with create_payload_indexmodels.FieldCondition( key="name", match=models.MatchText(text="tapes"),)NestedCondition — Filtering arrays of objects correctlyThis one tripped me up the first time, and I have seen it catch out nearly every developer I have worked with.If you store an array of review objects and use a plain FieldCondition on reviews.source and a separate one on reviews.score, Qdrant evaluates each field independently across all array elements. A venue with a low-score Google review and a high-score Yelp review would incorrectly satisfy both conditions.NestedCondition forces all sub-conditions to apply to the same array element. Always use it when filtering on arrays of objects — reviews, opening hours, data sources:# All three conditions must match the SAME review object in the array# Source: https://qdrant.tech/documentation/concepts/filtering/#nested-object-filterresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.NestedCondition( nested=models.Nested( key="reviews", filter=models.Filter( must=[ models.FieldCondition(key="source", match=models.MatchValue(value="google")), models.FieldCondition(key="score", range=models.Range(gte=4.5)), models.FieldCondition(key="verified", match=models.MatchValue(value=True)), ] ), ) ) ] ), with_payload=True,)IsNull and IsEmpty — Two conditions people always confuseIsNull matches where a field exists but is explicitly null. IsEmpty matches where a field is missing entirely or is an empty array []. These are different — knowing which one to use has saved me from subtle bugs more than once.# Field exists but is null (Python None) — venues 2 and 5 in our datasetresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.IsNullCondition( is_null=models.PayloadField(key="featured") ) ] ), with_payload=True,)# Field is entirely absent OR is an empty array []results, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.IsEmptyCondition( is_empty=models.PayloadField(key="featured") ) ] ), with_payload=True,)HasId — ID whitelist combined with any filterRestricts a query to specific point IDs while still applying other filters. I use this for personalisation (show only saved items), multi-tenant scoping (only IDs belonging to this tenant), and A/B testing.# Among saved venue IDs {1, 4, 8}, return only those open nowresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.HasIdCondition(has_id=[1, 4, 8]), models.FieldCondition(key="open_now", match=models.MatchValue(value=True)), ] ), with_payload=True,)2.3 Deep Logic Patterns — The Templates I Reach ForMost real business logic maps to one of these three patterns.Pattern 1 — OR-of-ANDs: Tiered eligibilityThis is the pattern I reach for most when modelling product requirements. “Budget + decent” OR “premium + exceptional” is a classic example. Each tier is a must block. The tiers sit in a should block. Qdrant evaluates them in a single pass.# (price_tier = 4.0) OR (price_tier >= 3 AND rating >= 4.8)results, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( should=[ # Branch A: budget + decent models.Filter( must=[ models.FieldCondition(key="price_tier", range=models.Range(lte=1)), models.FieldCondition(key="rating", range=models.Range(gte=4.0)), ] ), # Branch B: premium + exceptional models.Filter( must=[ models.FieldCondition(key="price_tier", range=models.Range(gte=3)), models.FieldCondition(key="rating", range=models.Range(gte=4.8)), ] ), ] ), with_payload=True,)Add more tiers by adding more Filter objects to the should list. The nesting depth is unlimited.Pattern 2 — Exclusions with must_notWhen I have a list of labels or categories that should never appear in results, must_not is cleaner and more explicit than any workaround.# Open now AND not a tourist trap AND not a chainresults, _ = client.scroll( collection_name=COLLECTION, scroll_filter=models.Filter( must=[ models.FieldCondition(key="open_now", match=models.MatchValue(value=True)), ], must_not=[ models.FieldCondition(key="tags", match=models.MatchValue(value="tourist-trap")), models.FieldCondition(key="tags", match=models.MatchValue(value="chain")), ] ), with_payload=True,)Pattern 3 — NestedCondition for array correctnessI covered the why above. The pattern to remember is this:# Correct — all conditions apply to the SAME array element:# models.NestedCondition(nested=models.Nested(key="...", filter=models.Filter(...)))# Wrong - causes a ValidationError:# models.Nested(...) placed directly in a must list2.4 Performance — Payload Indexes and the Query PlannerPayload Indexing docsWithout indexes: every filter scans all payload records. With indexes: Qdrant’s query planner evaluates the filter’s selectivity and decides whether to run HNSW first then filter, or filter first then search. A tight geo radius that eliminates 95% of points shifts execution to filter-first, meaning almost no vector computation happens at all. That is a meaningful latency difference at scale.Here is the full index setup from the notebook:import warningsfrom qdrant_client import modelsindex_specs = [ # KEYWORD: enables MatchValue, MatchAny, MatchExcept at index speed ("neighborhood", models.PayloadSchemaType.KEYWORD), ("cuisines", models.PayloadSchemaType.KEYWORD), ("tags", models.PayloadSchemaType.KEYWORD), # INTEGER / FLOAT: enables Range conditions ("price_tier", models.PayloadSchemaType.INTEGER), ("rating", models.PayloadSchemaType.FLOAT), # BOOL: enables MatchValue on boolean fields ("open_now", models.PayloadSchemaType.BOOL), # DATETIME: enables DatetimeRange with RFC 3339 strings directly ("added_at", models.PayloadSchemaType.DATETIME), # GEO: enables GeoRadius and GeoBoundingBox ("geo", models.PayloadSchemaType.GEO), # TEXT: enables MatchText - only add to fields needing substring search ("name", models.TextIndexParams( type=models.TextIndexType.TEXT, tokenizer=models.TokenizerType.WORD, min_token_len=2, max_token_len=20, lowercase=True, )),]with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) for field, schema in index_specs: client.create_payload_index( collection_name=COLLECTION, field_name=field, field_schema=schema, ) print(f" index created: {field}")print("All payload indexes ready.")print("Note: indexes accelerate queries on a live Qdrant server, not in :memory: mode.")A few rules I follow:Index fields I filter on constantly — price_tier, rating, neighborhood, open_now, tenant_id. If a field appears in most queries, it should have an index.Do not index everything — every index adds write-time cost. Only index fields that appear in filters.TEXT index only where I need substring search — it is the heaviest index type. Adding it to every string field is a mistake.Think about selectivity when composing filters — a geo radius covering 1% of the collection is far more valuable as a first-pass filter than a boolean covering 50%.Part 3 — Your Key TakeawaysA Reusable Filter-Building Cheat SheetEvery filter I write is one of these patterns or a combination of them:Table 3: Reusable filter-building cheat sheet — every condition pattern with its Qdrant construct.Production Checklist: What to Index and WhyTable 4: Production indexing checklist — what to index, what schema to use, and why it matters.Wrapping UpWhen I moved to composing payload filters alongside semantic search, the venue discovery feature I described at the start went from frustrating to reliable. Not because the embeddings got better. Because I stopped asking embeddings to do a job they were never designed for.Qdrant’s filtering system handles that second job completely. The logic primitives are composable and nestable to any depth. The condition types cover every practical requirement. The performance model is sensible. And the whole thing works in a Colab notebook with zero infrastructure before touching a production cluster.ReferencesQdrant Filtering Concepts — https://qdrant.tech/documentation/concepts/filtering/Qdrant Payload Indexing — https://qdrant.tech/documentation/concepts/indexing/#payload-indexFastEmbed + Qdrant Semantic Search — https://qdrant.tech/documentation/fastembed/fastembed-semantic-search/How to Use Deep Query Filtering in Vector Search for Structured + Unstructured Data was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.