Back to blog

Supporting LLM-Powered Top-k Queries in Quail

1. Introduction

A useful AI function in data processing is semantic top-k: given a question and a collection of records, return top k records that best match this question. For example, a sales team might ask, “Which calls most clearly show a customer’s commitment to purchase?” A lawyer might want to find passages that best support a legal argument.

There are multiple approaches to find the top k items in a dataset according to some criteria, but which approach works best for typical, business-relevant data processing tasks? Common approaches use embedding-based retrieval or pairwise LLM comparisons. Surprisingly, a small extension of AI.IF to return a score—which we call AI.SCORE—was enough. Scoring and sorting matched or beat pairwise comparison on Precision@25 across our three tasks and was 8.2x faster per task (geometric mean).

In this blog post, we discuss how we explored different approaches to implement semantic top-k task in Quail, our open-source SQL engine that supports AI functions.

We’ll go through:

2. Embedding-based Retrieval

One established approach is embedding-based retrieval. It computes the embeddings of questions and records (i.e., documents) separately, then ranks by cosine similarity between them. However, the LOTUS paper (Patel et al. 2025)1 aptly pointed out that embedding-based retrieval performed well on simple relevance-based ranking tasks but poorly on tasks that required reasoning.

A reranker helps move relevant records higher in the ranking. Rerankers run inference with both the question and a record in the prompt to produce a number indicating how well they match, then sort by that number. Each prompt is therefore longer than embedding either input alone — the model must run for every question-record pair instead of reusing stored record embeddings, making the reranker approach more expensive over multiple queries.

3. Pairwise Comparison

Another approach to implement semantic top-k is using pairwise LLM comparisons and a Quickselect top-k algorithm, the approach used in the LOTUS paper. More specifically, the algorithm randomly selects a pivot record, compares it with other records, and repeatedly removes records that cannot be in the top k.

Here is the procedure Quickselect uses to find the two largest values in [4, 1, 6, 5, 3, 2].

  1. Randomly select 3 as the pivot. Since 4, 6, and 5 all rank above 3, the top two must be among those three values. The algorithm removes 1, 3, and 2.
  2. Randomly select 6 from [4, 6, 5]. It beats both 4 and 5, so 6 takes first place.
  3. Randomly select 4 from [4, 5]. Since 5 beats 4, it takes second place. The result is [6, 5].

For semantic top-k, the same procedure compares records by asking the LLM which of the two better meets the ranking criterion.

We wanted to use pairwise comparison for Quail’s semantic top-k because earlier studies found it ranked records more effectively. LOTUS1 reported that its pairwise-based top-k outperformed scoring each record independently on SciFact2 (0.765 vs. 0.457 nDCG@10) and HellaSwag-bench3 (0.919 vs. 0.091). Qin et al.4 also found that pairwise comparison outperforms scoring each record independently by more than 10% on average nDCG@10.

4. Pointwise Scoring

Pointwise scoring evaluates each record independently, then sorts the records by score and returns the top k. We implemented AI.SCORE as a small extension of AI.IF: both evaluate a yes/no question about a record, but AI.SCORE returns a number from 0 to 1 instead of a true/false answer.

For the Qwen3-4B model used here, Quail reads the model’s logits for TRUE and FALSE at the answer position. A logit is the model’s unnormalized value for a possible next token. Writing the TRUE and FALSE logits as t and f, Quail returns σ(t − f), where σ is the sigmoid function, which normalizes the score to between 0 and 1. A higher score means the model favors TRUE more strongly. The model is not necessarily trained to produce calibrated probabilities.

Here’s an example query:

SELECT c.id,
       AI.SCORE(PROMPT(
         'Does the customer commit to buying, such as accepting the terms,
          agreeing to sign, or asking for the contract or paperwork?
          Interest, questions, or another meeting do not count.
          {0}
          Answer TRUE or FALSE.', c.transcript
       )) AS commit_score
FROM sales_calls c
WHERE c.deal_stage = 'Negotiation'
ORDER BY commit_score DESC, c.id
LIMIT 25

AI.SCORE with ORDER BY and LIMIT implements semantic top-k: score the records, sort by score, and return the best k.

5. Pointwise Beats Pairwise

We evaluated each ranking using Precision@25: the fraction of its 25 highest-ranked records that meet the task’s criterion.5

We compared four methods on three business-relevant semantic top-k tasks:

All four methods use models with 4 billion parameters. Pointwise and Pairwise use Qwen3-4B for independent scoring and pairwise comparison, respectively. Reranker uses Qwen3-Reranker-4B to score each record independently, and Retrieval uses Qwen3-Embedding-4B for embedding-based retrieval.

Pointwise scoring costs the least on all three tasks. Its Precision@25 ties pairwise on Sales (44%), and exceeds pairwise on Contract (96% vs. 80%) and Drug Safety (28% vs. 20%).
Figure 1. Precision@25 for four ranking methods versus cost per query. Each color represents a dataset. Within each dataset, the upper left is best: farther left means lower cost, and higher means better Precision@25. Pointwise scoring (highlighted) was the cheapest method on each dataset and tied for the highest Precision@25. Cost per query is based on H100 runtime at $3.95 per hour.

To our surprise, pointwise scoring matched pairwise comparison on Precision@25 for Sales (44%) and scored higher on Contract (96% vs. 80%) and Drug Safety (28% vs. 20%). It was 8.2x faster per task (geometric mean).

The latest Quail release supports pointwise scoring and reranking, both optimized for GPU utilization. Our retrieval and pairwise implementations are experimental and unoptimized. Retrieval could be faster with precomputed embeddings, but we don’t support it because it had lower Precision@25 on all three tasks. We’d still expect pairwise comparison to be slower because comparing records repeatedly requires more floating point operations.

In these experiments, more LLM calls did not improve Precision@25. We are not the only ones to observe this: in another study of semantic top-k, Lenzi et al.9 compared two ranking strategies and found that the one requiring more LLM calls generally incurred higher costs without consistently improving ranking quality.

6. Why?

Pairwise ranking depends on consistent comparisons. If the model picks the weaker record, Quickselect can discard a record that belongs in the top k.

6.1 Comparison Can Be Inconsistent

We observed the following two types of inconsistent comparisons during experiments.

The order of the two records in the prompt changes the answer. Swapping the order of two records in the prompt can change which record the model prefers. We tested eight models of different sizes and types: Qwen3 models from 0.6B to 27B (plus Qwen3.6-35B-A3B, a mixture-of-experts model), LFM2-2.6B, two decision models (d1-2B and Decision-2.0-Kai-0.6B), and the Jev API.

Figure 2 shows how often each model picked the same record after we swapped the order of the pair.10 Across all three tasks, the larger dense Qwen models were more consistent: the 4B model outperformed the 0.6B model, and the 27B model outperformed both. The specialized decision models also appeared more consistent than general-purpose models of similar size. For example, on Contract, Decision-2.0-Kai-0.6B picked the same record in 39% of pairs, compared with 0.6% for Qwen3-0.6B. Even Jev, the most consistent model, changed its choice on 12% of Drug Safety pairs.

For eight models on Sales, Contract, and Drug Safety, the fraction of pairs where the model picks the same record after the order is swapped. Values range from 0% to 95%.
Figure 2. How often each model picks the same record after we swap the order of the two records in the prompt. 100% means the order never changes the answer. Models are ordered by total parameter count. Jev appears last because its size was not reported.

Newer, larger models may have been trained on more data from the domains we care about. A model’s weights may already encode enough domain knowledge to recognize which details make a record a strong or weak match for the ranking criterion. If so, the model may not need to see other records to calibrate its judgment.

The model may need more reasoning before making a decision. Some pairwise comparisons may require reasoning. To reduce latency, Quail scores the first token of the answer without generating the full response. We found that when allowed to generate the full response, Qwen3-4B’s first-token decision differed from the final decision 28.89% of times on Sales (SF=0.1).

6.2 How Can Inconsistent Comparison Affect Top-k Results?

One wrong comparison can eliminate a top-k record. Quickselect repeatedly chooses a pivot record and uses comparisons with the pivot to decide which records to remove from consideration. If the LLM mistakenly places a true top-k record in the group being removed, the algorithm excludes it from the result. Later comparisons cannot recover the record. By contrast, AI.SCORE assigns each record one score. While the scores can be wrong, sorting them at least gives a consistent order.

Pairwise comparisons lose the fine-grained information that scores give. Pointwise gives score, while pairwise only gives win/loss, discarding how strong the model favors one choice over the other.11 As a result, an uncertain comparison can have the same impact as a confident one.

7. Conclusion

All in all, we decided against adding a dedicated semantic top-k operator: pairwise comparison was much slower and did not improve Precision@25 on any of our tasks. Scoring each record with AI.SCORE and sorting the scores worked better.12 But if you have a use case that needs pairwise comparison, reach out to us—we’d like to hear about it and are open to changing our minds!

As models improve, we are curious whether fine-tuning on domain-specific data could widen the advantage of scoring each record independently. Could we improve ranking using per-record labels, without collecting pairwise preferences? In the future, we also plan to explore reasoning-enabled AI operators and how to execute them efficiently.

Acknowledgements

We thank Modal for sponsoring the compute used in this research.

  1. Liana Patel, Siddharth Jha, Melissa Pan, Harshit Gupta, Parth Asawa, Carlos Guestrin, and Matei Zaharia. Semantic Operators and Their Optimization: Enabling LLM-Based Data Processing with Accuracy Guarantees in LOTUS. Proceedings of the VLDB Endowment (PVLDB), 2025. ↩ ↩2

  2. David Wadden et al. Fact or Fiction: Verifying Scientific Claims. In EMNLP, 2020. ↩

  3. Rowan Zellers et al. HellaSwag: Can a Machine Really Finish Your Sentence?. In ACL, 2019. ↩

  4. Zhen Qin et al. Large Language Models are Effective Text Rankers with Pairwise Ranking Prompting. In Findings of the Association for Computational Linguistics: NAACL, 2024. ↩

  5. Why Precision@k? In our tasks, each record has a yes/no label, and we care how many “yes” records make the top 25. Precision@25 counts each one equally. nDCG gives more weight to records near the top. ↩

  6. We use the latest call for each deal. A call is positive if the deal links to an activated contract with a recorded customer signature date in CRMArena-Pro. ↩

  7. A contract is positive if either Non-Compete-Answer or Exclusivity-Answer is “Yes” in CUAD. ↩

  8. An article is positive if its reactions field includes either “Nausea” or “Vomiting” in BioDEX-Reactions. ↩

  9. Emilia Lenzi, Davide Martinenghi, Paolo Papotti, and Marco Riva. SERA: Evaluating LLM-based SEmantic RAnking over Structured Tables. In Proceedings of the ACM International Conference on Information and Knowledge Management (CIKM), 2026. ↩

  10. We used the LOTUS pairwise prompt. On Sales, we compared all 59,685 pairs of the 346 calls. On Contract and Drug Safety, we compared 5,000 random pairs each selected from those that fit the 8,192-token window of Decision-2.0-Kai-0.6B. ↩

  11. A comparison could also report how strongly one record is preferred. Here, as in LOTUS, each comparison returns only a winner. ↩

  12. Changing the wording of the ranking prompt sometimes changed Precision@25. We expect future models to be less sensitive to how the prompt is phrased. ↩