Skip to content

Ranking SQL ​

Search runs two signals, a vector scan and a BM25 scan, and fuses them. You can replace the SELECT of either signal to scope the search to some chunks, or to rank by your own rule. This page lists the tokens, the parameter, the columns in scope and the precedence, with two examples.

How a signal is built ​

Each ranking signal — vector and BM25 — runs a DuckDB SELECT that returns chunk_id best-first; the store collects the ids and fuses them with RRF. Restrict scope or decay by age by injecting your own SELECT — the ranking SQL owns its own WHERE and ORDER BY:

python
scoped = (
    "SELECT chunk_id FROM {table} "
    "WHERE json_extract_string(metadata, '$.kind') = 'faq' "
    "ORDER BY {distance} LIMIT {top_k}"
)
hits = store.query("refund window", vector_sql=scoped, text_sql=scoped)

An injected template uses these substituted tokens: {table}, {distance} (vector signal only), {bm25} (text signal only), and {top_k}. The search text is available as the bound parameter $q, and these columns are in scope: metadata, source, title, stamped_at, text.

Overrides can be set once — shared across queries — via Settings or the DUCKDB_VECTORS_VECTOR_SQL / DUCKDB_VECTORS_TEXT_SQL environment variables, or passed per call as above. Precedence is per-call > settings > default; a custom SELECT owns its own WHERE and supersedes the convenience filter dict for that signal. The next two examples show an audience filter and an age decay.

Two uses of an injected SELECT come back often. The first serves several audiences from one agent: the harness reads "customer" or "staff" from the token that reaches the agent, and injects it in the WHERE, so that only the matching pages are considered. The second decays aging pages, so that fresh content ranks above old content. Here, older chunks sink, and age_days lives in the metadata:

python
decayed = (
    "SELECT chunk_id FROM {table} "
    "ORDER BY {distance} "
    "* (1 + CAST(json_extract_string(metadata, '$.age_days') AS DOUBLE) "
    "/ 365.0) "
    "LIMIT {top_k}"
)
store.query("latest guidance", hybrid=False, vector_sql=decayed)

The injected SELECT is caller-authored SQL that runs against your own database, and the query path only reads it. The query text and the embedding are parameter-bound.

See also ​