Vespa nearestNeighbor with filters: pre-filtering, post-filtering and the thresholds that switch between them
A Vespa nearestNeighbor filter is evaluated one of four ways, picked per query from the filter's hit ratio. We ran every path on Vespa 8.796 and show which thresholds decide, why hits go missing and what recall each setting gave.
A Vespa nearestNeighbor filter is pre-filtered by default: Vespa evaluates the filter first, then searches the HNSW graph for neighbours that pass it. Three rank-profile thresholds change that per query, based on the fraction of documents the filter matches. Below approximate-threshold (0.02) Vespa drops the graph and runs an exact search over the filtered documents, below filter-first-threshold (0.2) it checks the filter before computing each distance, and above post-filter-threshold (1.0, so never by default) it searches the graph unfiltered and filters afterwards. Fewer hits than targetHits usually trace back to post-filtering or to the filter-first heuristic at very low hit ratios.
Everything below was run on Vespa 8.796.11 (vespaengine/vespa in Docker, one content node) on 30 November 2026. The corpus is 100,000 synthetic documents: 64-dimension float vectors drawn around 500 random centroids, angular distance, HNSW with max-links-per-node: 16 and neighbors-to-explore-at-insert: 200. Each document has an integer bucket from 0 to 999, assigned independently of its vector, so bucket < 100 matches 10% of the corpus. That independence matters. A filter that correlates with the vectors behaves differently, and the recall numbers here describe this corpus only.
How a Vespa nearestNeighbor filter picks its strategy
The schema reference defines the settings, and the query API reference lists a per-query override for each under ranking.matching. As of December 2026:
| Rank profile setting | Query override | Default | What it decides |
|---|---|---|---|
approximate-threshold | approximateThreshold | 0.02 | Hit ratio below this: exact search with pre-filtering instead of the graph |
post-filter-threshold | postFilterThreshold | 1.0 | Hit ratio above this: post-filtering. 1.0 disables it |
filter-first-threshold | filterFirstThreshold | 0.2 | Hit ratio below this: check the filter before computing a distance |
filter-first-exploration | filterFirstExploration | 0.01 | How far the filter-first heuristic explores. Higher is slower and more accurate |
exploration-slack | explorationSlack | 0.0 | Delays termination of the graph search, with or without a filter |
target-hits-max-adjustment-factor | targetHitsMaxAdjustmentFactor | 20.0 | Cap on how far post-filtering may raise targetHits |
The reference says none of these has any effect in streaming search.
Two caveats on that table. The docs do not say which Vespa release introduced each setting, so we can't give you a minimum version. And Vespa's own blog disagrees with the reference on defaults: the September 2025 post Additions to HNSW in Vespa lists filter-first-threshold at 0.00 (heuristic off) and filter-first-exploration at 0.30, and its companion tuning guide lists approximate-threshold at 0.05. The trace from 8.796.11 printed 0.2, 0.01 and 0.02, matching the reference. If you are on an older release, read the values from your own trace before trusting either source.
The filter-first heuristic is what the docs call "Acorn 1". The blog post describes it: when a node's neighbours fail the filter, the search looks at neighbours of neighbours as well, and Vespa applies this only on the lowest layer of the graph. Elasticsearch has its own ACORN-based filtering, which we covered in filtered kNN and ACORN in Elasticsearch.
flowchart TD
Q["nearestNeighbor on an HNSW field<br/>combined with a filter"] --> E["Estimate the filter hit ratio"]
E --> A{"Below approximate-threshold?<br/>default 0.02"}
A -- yes --> X["Exact search over<br/>the documents that pass the filter"]
A -- no --> P{"Above post-filter-threshold?<br/>default 1.0"}
P -- yes --> PF["Search the graph unfiltered with<br/>adjusted targetHits, then filter"]
P -- no --> F{"Below filter-first-threshold?<br/>default 0.2"}
F -- yes --> FF["Filtered graph search<br/>filter checked before distance"]
F -- no --> PRE["Filtered graph search<br/>distance computed first"]The order of the first two checks is observed, since the reference does not spell it out: with postFilterThreshold=0.0 and a 1% filter, Vespa still ran the exact search.
Schema, rank profile and query
schema product {
document product {
field bucket type int {
indexing: attribute | summary
attribute: fast-search
rank: filter
}
field embedding type tensor<float>(x[64]) {
indexing: attribute | index
attribute {
distance-metric: angular
}
index {
hnsw {
max-links-per-node: 16
neighbors-to-explore-at-insert: 200
}
}
}
}
rank-profile ann {
inputs {
query(q) tensor<float>(x[64])
}
first-phase {
expression: closeness(field, embedding)
}
match-features: distance(field, embedding)
}
rank-profile ann_explore inherits ann {
filter-first-exploration: 0.3
}
}
POST /search/
{
"yql": "select * from product where {targetHits:100}nearestNeighbor(embedding, q) and bucket < 100",
"ranking": "ann",
"input.query(q)": "[ ...64 floats... ]",
"hits": 10,
"trace.level": 1,
"trace.explainLevel": 1
}
With trace.explainLevel: 1 the content node returns its query plan, and the NearestNeighborBlueprint entry tells you which path ran. This is the relevant part of the real response for the query above (other keys removed):
{
"target_hits": 100,
"adjusted_target_hits": 100,
"filter_first_upper_limit": 0.2,
"filter_first_exploration": 0.01,
"exploration_slack": 0.0,
"target_hits_max_adjustment_factor": 20.0,
"algorithm": "index top k using filter",
"filter_first_heuristic_used": true,
"terminated_early": false,
"timeout_hit": false,
"distances_computed": 833,
"nodes_visited": 7348,
"global_filter": {
"lower_limit": 0.02,
"upper_limit": 1.0,
"calculated": true,
"hits": 10000,
"hit_ratio": 0.0999990000099999
}
}
lower_limit and upper_limit are approximate-threshold and post-filter-threshold. The ratio is 10,000 over 100,001, which is why our "20%" filter below lands just under 0.2. Running the same query vector with a tighter and tighter filter, all defaults:
| Filter | Hit ratio | algorithm | Filter-first | totalCount | Distances computed |
|---|---|---|---|---|---|
| none | 1.0 | index top k | n/a | 100 | 477 |
bucket < 500 | 0.50 | index top k using filter | false | 100 | 858 |
bucket < 300 | 0.30 | index top k using filter | false | 100 | 1,742 |
bucket < 200 | 0.199998 | index top k using filter | true | 100 | 1,291 |
bucket < 100 | 0.10 | index top k using filter | true | 100 | 833 |
bucket < 21 | 0.021 | index top k using filter | true | 100 | 358 |
bucket < 20 | 0.0199998 | exact | n/a | 388 | 2,010 |
bucket < 10 | 0.01 | exact | n/a | 321 | 1,010 |
bucket = 7 | 0.001 | exact | n/a | 100 | 110 |
Three things to read off it. Without filter-first, a narrower filter costs more distance computations, because the graph walk keeps scoring nodes it then throws away. Filter-first reverses that slope. And the exact fallback exposes more than targetHits documents to first-phase ranking: the nearest neighbor guide notes that totalCount rises above the target when Vespa falls back, so a totalCount of 388 for targetHits:100 is a sign of exact search, and nothing is wrong.
One detail on the estimate. bucket has attribute: fast-search, and the trace showed "decision": "Skip" for the exact rows: Vespa knew the ratio from the dictionary and never built the filter. We fed the same values into a second attribute without fast-search. There the estimated ratio was 1.0 for every range, Vespa computed the filter, counted the real hits and then reported exact fallback. The outcome was the same in our run. The work to get there was not, so filter fields used with nearestNeighbor should have fast-search.
Why you get fewer hits than targetHits
Post-filtering with a capped adjustment
Post-filtering searches the graph with no filter and removes non-matching neighbours afterwards. To compensate, Vespa raises the target internally. The schema reference gives the formula:
adjustedTargetHits = min(targetHits / estimatedFilterHitRatio,
targetHits * targetHitsMaxAdjustmentFactor)
We forced post-filtering with ranking.matching.postFilterThreshold=0.0 and targetHits:100:
| Filter | Adjustment factor | adjusted_target_hits | totalCount | Distances computed |
|---|---|---|---|---|
bucket < 500 | 20 (default) | 200 | 96 | 765 |
bucket < 100 | 20 | 1,000 | 102 | 4,477 |
bucket < 50 | 20 | 2,000 | 95 | 8,937 |
bucket < 21 | 20 | 2,000 | 42 | 8,937 |
bucket < 21 | 50 | 4,761 | 98 | 18,309 |
bucket < 100 | 5 | 500 | 52 | 2,462 |
bucket < 100 | 1 | 100 | 5 | 477 |
The adjustment aims at the target on average and misses it per query, so 96 and 95 are normal. The 42 is the cap: 100 / 0.021 is 4,762, the default factor of 20 limits it to 2,000, and 2.1% of 2,000 is 42. Across 100 query vectors that row averaged 41.8 hits. With the factor at 1, five documents came back for a query that asked for 100.
This is the mechanism our OpenSearch readers know from k-NN filters returning fewer results. The difference in Vespa is that you opt into it. If someone on your team lowered post-filter-threshold to speed up broad filters, check what the narrowest filter that still clears approximate-threshold does under the cap.
Filter-first at very low hit ratios
This one happens with every default in place. At bucket < 21 (2.1%, just above the exact fallback), 4 of our 100 query vectors got fewer than 100 hits, and 3 of those got zero, from a filter that matches 2,100 documents. The trace for one of them shows distances_computed: 87 and terminated_early: false. The search finished normally and found nothing.
The Vespa blog explains why: with very restrictive filters the filtered subgraph becomes so disconnected that even two-hop neighbours are not enough, and it reports "a significant drop in recall" in that range. The reference says the same of filter-first-threshold in one line: it "improves the response time at low hit ratios but causes a dip in recall".
Lowering approximate-threshold makes this much worse. With approximateThreshold=0.0, so the graph is always used:
| Hit ratio | Queries (of 100) returning fewer than 10 hits | Recall@10 | Avg distances | Exact search distances |
|---|---|---|---|---|
| 0.01 | 34 | 0.394 | 179 | 1,010 |
| 0.005 | 90 | 0.135 | 88 | 510 |
| 0.001 | 100 | 0.026 | 85 | 110 |
Turning filter-first off as well (filterFirstThreshold=0.0) brought recall back to 1.000 on all three rows and cost 32,817, 53,081 and 100,083 distance computations per query. At 0.1% that is every vector in the corpus, to avoid an exact search that needed 110. The tuning guide's advice holds up: "it is important not to completely disable the fallback to an exact search."
The causes the docs name
We did not reproduce these, so they are cited as documented:
geoLocationandpredicateterms. The HNSW guide says these are left out of the pre-filter and evaluated after the neighbours are retrieved, "more like a post-filter", which "might cause the search to expose fewer hits to ranking".distanceThreshold. The annotation removes neighbours beyond a distance, in exact and approximate search alike.- ANN timeout. Since Vespa 8.709.26
ranking.matching.anntimeout.enableis on by default, per the query API reference. An ANN search that runs into it stops and returns what it has, and the response is marked degraded withcoverage.degraded.anntimeout, per the graceful degradation docs.ranking.matching.anntimebudget(since 8.684.9) also stops the search early, and the reference says that case is not reported as degraded.
targetHits vs totalTargetHits vs hits vs rerank-count
| Setting | Where | Default | Counts |
|---|---|---|---|
targetHits | YQL annotation | none, required | Neighbours exposed to first-phase per content node |
totalTargetHits | YQL annotation | none | The same, in total across the content nodes. The YQL reference says to prefer it |
minTargetHits | YQL annotation | 100 | Floor on each node's share of totalTargetHits |
hnsw.exploreAdditionalHits | YQL annotation | 0 | Extra graph nodes explored beyond the target |
second-phase rerank-count | Rank profile | 100 per node | Best first-phase hits rescored |
hits | Query API | 10 | Hits in the response |
One of these is set per node, one per cluster and one per response, and none of them changes another. {targetHits:10} with hits: 50 returned 10 hits. And totalTargetHits has a floor that surprised us: {totalTargetHits:10} gave a totalCount of 100 on our single node, because each node resolves its target as max(minTargetHits, ceil(totalTargetHits × share)). Adding minTargetHits:10 brought it back to 10.
The YQL reference also says not to set totalTargetHits below the profile's total-rerank-count when second-phase is in use. The windows themselves are covered in our phased ranking explainer, and the same sizing question for fusion in RRF in global-phase.
targetHits is also the recall knob people forget they have. Unfiltered, targetHits:10 scored recall@10 of 0.883 against exact search on this corpus. targetHits:100 scored 1.000.
Measuring recall against approximate:false
{approximate:false} forces an exact search, and the HNSW guide recommends exactly this comparison: run both and compute the overlap at k. We ran 100 query vectors with targetHits:100, took the top 10 of each response and compared ids. The guide warns that exact search over many vectors needs a longer timeout than the 500 ms default.
| Hit ratio | Setting | Recall@10 | Avg distances | Queries short of 100 |
|---|---|---|---|---|
| 0.10 | defaults | 1.000 | 759 | 0 |
| 0.10 | filterFirstThreshold=0.0 | 1.000 | 4,451 | 0 |
| 0.05 | defaults | 0.981 | 502 | 0 |
| 0.05 | filter-first-exploration: 0.3 | 0.997 | 1,005 | 0 |
| 0.05 | explorationSlack=0.1 | 0.997 | 1,169 | 0 |
| 0.021 | defaults | 0.758 | 309 | 4 |
| 0.021 | explorationSlack=0.1 | 0.858 | 546 | 4 |
| 0.021 | hnsw.exploreAdditionalHits:100 | 0.835 | 500 | 4 |
| 0.021 | filter-first-exploration: 0.3 | 0.921 | 578 | 2 |
| 0.021 | filter-first exploration 1.0 | 0.995 | 1,157 | 0 |
| 0.021 | filterFirstThreshold=0.0 | 0.999 | 18,156 | 0 |
| 0.021 | approximateThreshold=0.05 (exact) | 1.000 | 2,110 | 0 |
The 0.3 rows used the ann_explore profile; the 1.0 row used query overrides (see the note below). At 10% the defaults are free: filter-first cut the work by a factor of almost six and lost nothing. The trouble is confined to the band just above approximate-threshold. There, exploration-slack and exploreAdditionalHits bought some recall and did nothing for the queries that came back empty, because a search that starts in a disconnected region has nowhere further to go. Only two changes fixed both: more filter-first exploration, or moving the exact threshold up so that band never reaches the graph.
On this corpus the two are close: 2,110 distances for exact search against 1,157 for full filter-first exploration, and only exact search reached 1.000. The Vespa guides add that exact search with a filter can use several threads per query while the graph search is always single-threaded. That will not hold at scale. Exact cost is the number of documents passing the filter, so 5% of 100 million vectors is 5 million distances per query (computed, we did not run it). The tuning guide makes the same point: the more vectors you have, the later you want to fall back.
A query override that did not apply
ranking.matching.filterFirstExploration=0.3 sent on its own left filter_first_exploration at 0.01 in the trace, with identical distance counts. Sent together with ranking.matching.filterFirstThreshold, it applied. And sending filterFirstThreshold alone changed the trace's exploration value to 0.0. The rank-profile setting filter-first-exploration: 0.3 worked as documented. We have not traced this to the source, so treat it as observed on 8.796.11 and check your own trace. It is one more reason to put these in a rank profile.
Symptoms and fixes
| Symptom | Likely cause | What to change |
|---|---|---|
totalCount below targetHits, trace shows adjusted_target_hits at targetHits × 20 | Post-filtering hit the adjustment cap | Raise post-filter-threshold, or raise target-hits-max-adjustment-factor and accept the cost |
Zero or very few hits, filter_first_heuristic_used: true, hit ratio just above 0.02 | Filter-first on a disconnected subgraph | Raise filter-first-exploration, or raise approximate-threshold to cover that band |
Hits missing with a geoLocation or predicate term | Term evaluated after retrieval | Raise targetHits; the HNSW guide documents the behaviour |
totalCount far above targetHits | Exact fallback | Nothing. Lower approximate-threshold only if exact latency is the problem |
totalTargetHits:10 exposes 100 | minTargetHits default of 100 | Set minTargetHits if you want fewer |
| Slow queries with broad filters (above 20%) | Filtered graph search discarding nodes | Raise filter-first-threshold (the tuning guide used 0.4 on its dataset), measure recall |
| Slow queries with narrow filters | Exact search over many documents | Lower approximate-threshold in small steps with filter-first-exploration raised, measure recall and empty results |
coverage.degraded.anntimeout in the response | ANN timeout stopped the search | Raise timeout, or cut the work per query |
| Recall low with no filter at all | targetHits equal to hits | Raise targetHits, or hnsw.exploreAdditionalHits |
What we would ship
Leave post-filter-threshold at 1.0. Post-filtering was never meaningfully cheaper here (681 average distances against 692 for pre-filtering at a 50% filter, 4,465 against 759 at 10%), and it is the only path on which a capped number decides how many hits you get. Keep pre-filtering, set targetHits to 100 or more regardless of hits, and put fast-search on every attribute you filter by.
Then spend the tuning effort on the band between approximate-threshold and roughly twice its value, because that is where the defaults lost a quarter of the top 10 in our run. Replay real queries with real filters, bucket them by hit_ratio from the trace, and compare against approximate:false per bucket. Count empty and short responses separately from recall: an average hides three queries that returned nothing. Vespa also ships an ANN tuning tool that automates the sweep.
Whether to close the band with a higher filter-first-exploration or a higher approximate-threshold depends on corpus size, and we don't think there is a default that is right for both 100,000 and 100 million vectors. For how these controls compare with a segment-based engine, see Elasticsearch vs Vespa.
Where we can help
We tune Vespa filtered vector search against your own queries: thresholds per rank profile, targetHits and rerank windows, with recall and empty-result rates measured per filter selectivity. See our Vespa consulting service.
Abhilash B is an advisor at Query Quotient and an information retrieval and AI expert who holds patents in the field. Abhilash brings that retrieval depth to the search, RAG and agent systems Query Quotient builds for clients.
