# Better search made my agent 15% cheaper: how to prove it with recall@k

> Replacing keyword search with hybrid search cut an agent's searches, steps and cost. How to combine both searches with RRF and prove the gain with recall@k.

Rodrigo Lucas · 2026-11-11 · https://rodrigolucas.dev/en/blog/hybrid-search-and-recall-at-k-how-to-prove-search-got-better

---
I replaced the keyword search in an AI assistant I built with hybrid search and, without touching the prompt or the model, the cost per test scenario dropped 15%. On the same 24 eval scenarios, the agent went from 1.98 to 1.56 searches per scenario, and searches that came back empty went from 3 to 0. A number for the whole agent does not prove on its own that the search is what got better, though, and for that I measured the search in isolation with **recall@k**. On 10 vague requests, with the right documents written down by hand before measuring, recall@5 went from 38% to 64%. Ten queries is a small sample, and I come back to that further down.

The assistant searches a small curated base of fewer than two hundred documents. The problem that led me to the change shows up in any search that sits in front of a model. The user asks for something vague, keyword search returns nothing or returns noise, and the model starts running search after search trying to guess the right term. Each extra search is one more step, more input tokens and more seconds of waiting, and the answer still comes out worse.

## Keywords and embeddings fail in different places

Lexical search compares words. The classic version is BM25, which gives more weight to rare terms and saturates repetition (Robertson and Zaragoza explain the parameters in the review listed in the references). However well tuned, it depends on the user's word being in the document. When someone asks "how do I stop paying every month?" and the right document is called "canceling the recurring subscription", there is no shared term worth anything.

My first version was even simpler than BM25, because it only counted how many query terms appeared as a substring in the document. This brought a bug that only showed up when I started measuring. A vague query full of common words ("something with a feel of...") matched almost every document because of words like "with" and "of", and the ranking turned into a lottery. I fixed it with a stopword list, and the bug stayed with me as a reminder of why weighting by rarity (the IDF) exists. If your lexical search lives in Postgres, it is worth knowing that `ts_rank` and `ts_rank_cd` don't do that. The documentation says "the ranking functions do not use any global information", so a word that is common in the base weighs the same as a rare one.

Vector search swaps the question "which words match?" for "which texts mean something similar?". Each text becomes an **embedding**, a vector that represents its meaning, and the ranking is the cosine similarity between the query vector and each document's vector (the Gemini embeddings documentation explains the math). In the assistant, I used 256-dimension vectors, precomputed for the whole base in a file and loaded in memory. With a base that size, comparing the query with every document costs microseconds, so I did not need a vector database. The only extra network call is the query embedding, with an in-memory cache for repeated queries.

The embedding solves the case where keywords fail, but it has the opposite flaw. Anthropic describes this when explaining why it combines embeddings with BM25 in Contextual Retrieval. In a search for an error code like "TS-999", the vector brings documents about error codes in general and may leave out the one with the exact string. Proper names, SKUs, version numbers and internal acronyms fall into the same hole. That is why hybrid search keeps the keywords, runs both searches and combines the results.

## Combining by position instead of score

The first idea for combining is adding the scores, and it runs into a scale problem. BM25's score has no ceiling, my term count went from 1 to 5, and the cosine sits between -1 and 1. Adding requires normalizing and choosing weights, and the right weight changes with the base and with the kind of query.

Reciprocal Rank Fusion (RRF), by Cormack, Clarke and Büttcher (SIGIR 2009), avoids that calibration because it ignores the scores and looks only at each document's position in each list. Each document adds `1 / (k + position)` for every ranking it appears in, with `k = 60`, a value the authors fixed in a pilot and did not change afterwards. In the paper, the method equaled or beat the classic fusion methods and almost always landed above the best individual system. The function below does the fusion for any number of lists.

```ts
// Reciprocal Rank Fusion: each ranking is a list of ids, from best to worst.
function fuseRankings(rankings: string[][], k = 60) {
  const points = new Map<string, number>();
  for (const ranking of rankings) {
    ranking.forEach((id, i) => {
      points.set(id, (points.get(id) ?? 0) + 1 / (k + i + 1));
    });
  }
  return [...points.entries()]
    .sort((a, b) => b[1] - a[1])
    .map(([id]) => id);
}
```

A document that shows up in second place in both lists adds up to `2/62` and beats one that shows up first in one list and does not appear in the other (`1/61`). That was what I wanted, with agreement between the two methods worth more than an isolated peak. The price is that RRF throws the score away, and a document that is by far the best in one list gets the same credit as one that is first by a hair. If one of the searches is much more reliable than the other, a well-calibrated weighted sum may do better, as long as you have a way to measure it.

Two decisions around the fusion made a difference. Hard filters stay the same, so if the query asks for a document type or only active ones, the filter runs first, in both searches, and the fusion only reorders what already passed the rules. And when there is no embedding, the search falls back to keywords. If the embeddings API fails, the error goes to the log and the lexical ranking comes back, as before, because a worse search is still better than a broken one. The same config key turns off the semantic part in unit tests (which run without network) and in the eval that compares the two versions.

## The recall@k test

To know whether hybrid search works better on my base, with my queries, I needed a number that looked only at the search, and recall@k fits a search that feeds an agent. Recall is the fraction of relevant documents the search returned, and recall@k cuts that count at the first k results, which is what actually reaches the model. If the right document was not there when the model went to answer, no prompt will fix it.

I wrote 10 vague requests, the kind keyword search gets wrong, describing what the person wanted without naming anything. For each one, I listed by hand every document in the base that would be a good answer, and I wrote in the file itself that the labels were fixed before measuring hybrid search and should not be adjusted after seeing the result. A label adjusted after the result is theater, because it becomes easy to "discover" that the document the search brought back was also acceptable. The test calls only the search function, with no agent and no language model, with the semantic part on and off, and compares the first 5 results with the labels.

The denominator took some work. The classic definition of recall divides by the total number of relevant documents, and most of my requests had more than 10 acceptable documents. With k = 5, recall would never pass 50% in those cases, and the number would say nothing useful. So I divided by the smaller of k and the total relevant, and the question becomes "of the 5 positions at the top, how many were taken by good answers?".

```ts
function recallAtK(returned: string[], relevant: Set<string>, k = 5) {
  const target = Math.min(k, relevant.size);
  const hits = returned
    .slice(0, k)
    .filter((id) => relevant.has(id)).length;
  return hits / target;
}
```

The test costs cents per run (only the embeddings of the 10 queries) and runs in seconds. It also fails if any label points to a document that no longer exists, which catches rotten labels when the base changes.

## What changed in the search and in the agent

In the isolated search, the average recall@5 over the 10 requests went from **38% with keywords only to 64% with hybrid search**. Then I ran the assistant's full eval, with the same 24 scenarios as before the change.

| Metric, on the same 24 scenarios | Keywords only | Hybrid |
|---|---|---|
| Searches per scenario | 1.98 | 1.56 |
| Agent steps | 4.90 | 4.29 |
| Cost per scenario | 100% | 85% |
| Searches that came back empty | 3 | 0 |
| Median response time | 16.7 s | 13.7 s |

With a weak search, the agent compensated by running more searches, rephrasing the query until it found something. With the right document showing up earlier, that loop got shorter, and steps, cost and time dropped with it. That is why it pays to measure both, since recall@k says whether the search improved and the agent eval says whether that turned into less work for the model.

One of the 10 requests stayed at 0% recall@5, with hybrid search bringing defensible documents that were not in the labels, and I left the ruler as it was.

I would not call these numbers a general rule. Ten queries were enough to show a large difference on a small base, but for differences of a few points I would need many more queries and more than one run. The labels come from one person, and someone else would label differently. And recall@k ignores the order within the top k, so a relevant document in fifth place counts the same as one in first. For an agent that reads all 5, that is fine, but for a list a human reads top to bottom, a position-sensitive metric such as DCG says more.

## When the base grows

With few documents, in-memory vectors do the job. With hundreds of thousands, the math changes, and if the application already uses Postgres, you can run both searches and the fusion in the same database. The pgvector documentation suggests using the extension together with Postgres full-text search for hybrid search, combining the results with Reciprocal Rank Fusion or a cross-encoder.

```sql
WITH lexical AS (
  SELECT id, row_number() OVER (ORDER BY ts_rank_cd(search, q) DESC) AS pos
  FROM documents, websearch_to_tsquery('english', $1) q
  WHERE search @@ q
  ORDER BY pos LIMIT 50
),
semantic AS (
  SELECT id, row_number() OVER (ORDER BY embedding <=> $2) AS pos
  FROM documents
  ORDER BY embedding <=> $2 LIMIT 50
)
SELECT id,
       coalesce(1.0 / (60 + l.pos), 0) + coalesce(1.0 / (60 + s.pos), 0) AS rrf
FROM lexical l FULL OUTER JOIN semantic s USING (id)
ORDER BY rrf DESC
LIMIT 5;
```

The `FULL OUTER JOIN` is what lets in a document that only one of the searches found. In this setting recall@k takes on a second role. By default, pgvector performs exact nearest neighbor search, with perfect recall. When you create an HNSW or IVFFlat index, the search becomes approximate and trades recall for speed, and the same test with fixed labels answers whether the new index cost quality before it goes to production.

The embedding also brings maintenance. The vectors need to be regenerated when the documents change, and switching embedding models forces you to regenerate everything, because vectors from different models are not comparable. Each query gains an external dependency on its path, which in my case was acceptable because of the keyword fallback and the cache.

If I were starting a hybrid search today, I would build the set of labeled queries before choosing the embedding model. It is an afternoon of work, and it is what turns "it looks better" into a question with an answer. What I still don't know is how much of this gain survives a larger set and a second labeler, and that is the test left to run.

## References

- Gordon V. Cormack, Charles L. A. Clarke and Stefan Büttcher. [Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf). SIGIR 2009.
- Stephen Robertson and Hugo Zaragoza. [The Probabilistic Relevance Framework: BM25 and Beyond](https://staff.city.ac.uk/~sbrp622/papers/foundations_bm25_review.pdf). Foundations and Trends in Information Retrieval, 2009.
- PostgreSQL. [Controlling Text Search: ranking search results](https://www.postgresql.org/docs/current/textsearch-controls.html).
- pgvector. [README: hybrid search, exact and approximate search, HNSW and IVFFlat](https://github.com/pgvector/pgvector).
- Anthropic. [Introducing Contextual Retrieval](https://www.anthropic.com/news/contextual-retrieval).
- Google. [Gemini API: embeddings and cosine similarity](https://ai.google.dev/gemini-api/docs/embeddings).
- Elastic. [Reciprocal rank fusion](https://www.elastic.co/guide/en/elasticsearch/reference/current/rrf.html).
- Wikipedia. [Evaluation measures (information retrieval)](https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)).
