# Rerank

> Score and reorder retrieved passages against a query with local cross-encoder models, for sharper RAG results

This page includes setup, release pins, credentials, hosting and verification evidence. [JSON alternative](https://query.farm/products/orchard/api/v1/connectors/rerank.json) contains the same setup facts for structured readers; choose one format.

## Runtime and release

Use DuckDB or Haybarn **2.0.1** with **VGI protocol 3.4**.
Catalog alias: `rerank`. Release: [v0.5.0](https://github.com/Query-farm/vgi-rerank/releases/tag/v0.5.0). Metadata generated: 2026-12-01T18:22:16+00:00.

## Choose where it runs

- On your machine: use an installation method below. No Query Farm account is required for local execution.
- Self-host: follow [the connector deployment instructions](https://github.com/Query-farm/vgi-rerank) and [connection guide](https://query.farm/vgi/connect-to-a-worker/). Use your real endpoint and its authentication settings.
- Query Farm hosted: [create a deployment](https://auth.queryfarm.cloud/console/new?worker=rerank). Hosting has a $10 monthly minimum per organization; usage and license fees may apply. Copy the deployment-specific ATTACH from the console.

## Service credentials and prerequisites

No service credentials are declared by this connector. Individual datasets, input files or deployments may have their own prerequisites.

Secret parameter required flags describe the upstream declaration; they do not override the service-level mode above. Keep secrets in environment variables or the deployment secret store. SQL values in angle brackets are placeholders, not automatic environment lookups. Native DuckDB and Haybarn 2.0.1 do not provide a SQL getenv() function, even when worker-supplied snippets mention it. Read environment variables in your application and pass credential values through client parameter bindings (for example, Python con.execute("CREATE SECRET stripe (TYPE stripe, api_key ?)", [os.environ["STRIPE_API_KEY"]]) after attaching the connector. Omit unused optional parameters and keep real values out of saved SQL and logs.

## Install the extension

In stock DuckDB:

```sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;
```

In Haybarn:

```sql
INSTALL vgi FROM community;
LOAD vgi;
```

## Attach the connector

The local recipes below pin the catalog release for repeatability. A public demo endpoint follows its deployed release.

### uvx

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

```sql
ATTACH 'rerank' AS rerank (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/vgi-rerank@v0.5.0 vgi-rerank-worker'
);
```

### Docker

Attach the signed image

Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.

```sql
ATTACH 'rerank' AS rerank (
  TYPE vgi,
  LOCATION 'oci://ghcr.io/query-farm/vgi-rerank:0.5.0'
);
```

## Rank search passages by relevance

Service credentials required for this example: not declared by this example; check the connector requirements above.

```sql
SELECT doc FROM (VALUES ('Reset your password from the account settings page.'), ('Our office is open from 9am to 5pm.')) AS t(doc) ORDER BY rerank.main.rerank_score('how do I reset my password', doc) DESC;
```

- [rerank.main.rerank_score — scalar_function](https://query.farm/products/orchard/connectors/rerank/objects/scalar_function.bWFpbg.cmVyYW5rX3Njb3Jl.md): exact declaration for this example.

Execution evidence: **captured_result**.

```json
{
  "status": "captured_result",
  "capturedAt": "2026-12-01T06:21:29+00:00",
  "engineVersion": "2.0.1",
  "protocolVersion": "3.4.0",
  "releaseTag": "v0.5.0",
  "sample": {
    "columns": [
      "doc"
    ],
    "types": [
      "VARCHAR"
    ],
    "rows": [
      [
        "Reset your password from the account settings page."
      ],
      [
        "Our office is open from 9am to 5pm."
      ]
    ],
    "more": false
  }
}
```

## Connector reference

### Cross-Encoder Reranking in SQL

![fastembed (Qdrant) logo](https://raw.githubusercontent.com/qdrant/fastembed/main/docs/assets/favicon.png)

**Rerank retrieval results directly in DuckDB with a local cross-encoder reranker (fastembed / ONNX Runtime, no torch) -- the precision second stage that turns a good recall set into a great answer for RAG and semantic search.**

Retrieval-augmented generation and semantic search almost always run in two stages. A fast *recall* stage (DuckDB [VSS](https://duckdb.org) approximate nearest-neighbor search over embeddings, or BM25 full-text search) cheaply pulls a top-K candidate set out of a large corpus, but it ranks each document in isolation, so the truly best passage is often buried at rank 7 instead of rank 1. This worker adds the *precision* second stage: a **cross-encoder** that reads the query and a candidate document *together* in a single transformer forward pass and emits a relevance score that is far more accurate than bi-encoder cosine similarity. It is for anyone building local RAG pipelines, document search, or recommendation ranking who wants higher answer quality without standing up a separate model-serving service -- the reranking happens inside your SQL query.

Scores are computed entirely locally by [fastembed](https://github.com/qdrant/fastembed) (from Qdrant, Apache-2.0), which runs quantized cross-encoder models on [ONNX Runtime](https://onnxruntime.ai/) -- there is **no PyTorch dependency** and no network call at query time. The default model, [`Xenova/ms-marco-MiniLM-L-6-v2`](https://huggingface.co/Xenova/ms-marco-MiniLM-L-6-v2) (~80 MB, Apache-2.0), is fetched once on first use and cached, and the ONNX session is built a single time per worker process and amortized across every row. Because a cross-encoder scores each (query, document) pair at query time and cannot be precomputed or cached the way an embedding can, you should only ever run it over a recall-produced top-K candidate set -- never over a whole corpus.

The catalog exposes a small, focused surface. `rerank_score(query, document)` returns a `DOUBLE` relevance logit (higher = more relevant, meaningful only relative to other documents for the *same* query), so it drops straight into `ORDER BY rerank.rerank_score(:q, chunk) DESC LIMIT k`; a three-argument overload `rerank_score(query, document, model)` lets you pick a specific reranker such as `BAAI/bge-reranker-base`. The `supported_models()` table function (also available as the `supported_models` table) lists every reranker the worker can run together with the license of its weights. A NULL or empty query or document always yields a NULL score, so odd input never crashes a query.

## Getting started

Install and load the `vgi` community extension, then `ATTACH` this worker as a catalog (for example named `rerank`) pointed at `uv run rerank_worker.py`. Once attached, order any recall-produced candidate set by `rerank.main.rerank_score(:query, document) DESC` and keep the top *k* rows. Ready-to-run SQL for every function lives in each object's own examples and in the schema's example queries.

## Learn more

- fastembed source: <https://github.com/qdrant/fastembed>
- fastembed documentation: <https://qdrant.github.io/fastembed/>
- ONNX Runtime: <https://onnxruntime.ai/>

## Find the exact SQL object

[Browse 2 object declarations](https://query.farm/products/orchard/api/v1/connectors/rerank/objects.json) or [search within this connector](https://query.farm/products/orchard/api/v1/search.json?kind=object&connector=rerank&q=rerank).

Follow one format of each needed object for complete argument types, defaults, named flags, return columns and examples. Existing links above can replace another search. For questions about hosting, credentials or supported operations, stop once the documentation answers the question; SQL and unrelated object lookups are unnecessary.

## Verification and interpretation

- Missing, null, or undeclared metadata means unknown; do not invent defaults, credential scope, platform support or endpoint URLs.
- Search is keyword retrieval, not proof of a capability. Read the exact object declaration before generating SQL.
- A table and a table function can have the same name. Preserve parentheses and use the matching overload and schema.
- Service credentials, external data availability and deployment authentication are separate requirements.
- Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL.

```json
{
  "generatedAt": "2026-12-01T18:22:16+00:00",
  "repository": "https://github.com/Query-farm/vgi-rerank",
  "harvest": {
    "status": "ok",
    "method": "subprocess",
    "error": null,
    "vgi_version": "9773130dde"
  },
  "catalogVerification": {
    "verified": true,
    "status": "passed",
    "total": 2,
    "passed": 2,
    "failed": 0,
    "needs_credentials": 0,
    "location": "uvx --from git+https://github.com/Query-farm/vgi-rerank@v0.5.0 vgi-rerank-worker",
    "transport": "subprocess",
    "environment": {
      "vgi_extension_version": "9773130dde",
      "haybarn_version": "2.0.1rc3",
      "engine_version": "v2.0.1",
      "python": "3.12.4",
      "platform": "darwin_arm64",
      "protocol_version": "3.4.0"
    },
    "checked_at": "2026-12-01T06:16:54+00:00"
  },
  "interpretation": "Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL."
}
```
