select document.title title, document.description excerpt, document.tags tags, document.url url, document.interestingness from (
select document_id, sum(bm25_term) bm25 from (
with
1.20 as bm25_k1,
0.75 as bm25_b,
(select avg(doc_size) from inverted_index) as avgDocLen,
unhex('{query_hex}') as query,
arrayMap(x -> stem('english', lower(x)), splitByNonAlpha(query)) as query_words
select
document_id,
idf.idf * (ii.count * (bm25_k1 + 1)) / (ii.count + bm25_k1 * (1 - bm25_b + bm25_b * (ii.doc_size / avgDocLen))) bm25_term
from inverted_index ii
left join idf on idf.term = ii.term
where has(query_words, term)
settings allow_experimental_nlp_functions = 1
)
group by document_id
order by bm25 desc
) x
join document on document.id = x.document_id
order by x.bm25 desc
limit 64
settings final = 1
format JSONEachRow
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This SQL-like query is designed to search documents using a full-text relevance scoring algorithm based on BM25, and return the top 64 most relevant documents. Let’s break it down in detail to see what's happening at each stage.
🔍 Overview
You're querying a document database that uses an inverted index and BM25 scoring to rank documents in order of their relevance to a search query.
📌 Key Components Explained
1. 🔢 bm25_k1 and bm25_b
These are BM25 hyperparameters:
bm25_k1 = 1.20: Controls term frequency saturation; higher values give more weight to term frequency.
bm25_b = 0.75: Controls how much document length normalizes term frequency.
2. 📊 Averaging Document Length
sql
(select avg(doc_size) from inverted_index) as `avgDocLen`
Calculates the average number of terms (size) in all documents — needed for the BM25 formula.
3. 🔠 Query Processing
sql
unhex('{query_hex}') as `query`,
arrayMap(x -> stem('english', lower(x)), splitByNonAlpha(query)) as `query_words`
{query_hex}: A hex-encoded query string (probably passed in dynamically).
This part:
Unhexes the query.
Splits the query into words based on non-alphabetic characters.
Converts to lowercase.
Applies English stemming (e.g., "running" → "run").
This gives query_words, a normalized list of search terms.
4. 🔍 Core Search & Scoring
sql
from inverted_index ii
left join idf on idf.term = ii.term
where has(`query_words`, term)
Here, it looks up the inverted_index table:
Each record links a term to documents in which it appears.
Joins with the idf table to get the Inverse Document Frequency for each term.
💡 BM25 Formula:
sql
idf.idf * (ii.`count` * (k1 + 1)) / (ii.`count` + k1 * (1 - b + b * (ii.doc_size / avgDocLen))) AS `bm25_term`
This calculates BM25 score for each term-document pair:
ii.count: Term frequency in the document.
ii.doc_size: Number of terms in the document.
🧮 Returned Output:
document_id
bm25_term — partial BM25 score for this term in this document.
5. 📈 Summing BM25 Terms by Document
sql
select document_id, sum(`bm25_term`) as `bm25`
group by document_id
order by `bm25` desc
Each document may match multiple query terms.
Sums up all BM25 scores for all matched terms per document.
Orders them by descending relevance.
6. 🔄 Joining with document Table
sql
join document on document.id = x.document_id
Now we join the top-ranked document_ids to fetch:
title
description (renamed as excerpt)
tags
url
interestingness
7. 📑 Final Output
sql
limit 64
settings final = 1
format JSONEachRow
Limits output to the top 64 most relevant documents.
Output format is JSONEachRow — each result is a complete JSON document on a single line.
✅ Summary
You're executing a BM25-based full-text document search. The query:
Tokenizes and stems the search query.
Uses an inverted index to find documents that contain the terms.
Calculates the BM25 relevance score between the query and each candidate document.
Ranks the documents by score.
Returns metadata of the top 64 matching documents.
This is likely part of a search engine backend using a SQL-compatible system like ClickHouse, especially given the settings allow_experimental_nlp_functions = 1.
👁️🗨️ Optional Improvements or Notes:
If {query_hex} is dynamically inserted, care should be taken that it’s sanitized.
Ensure stemming and normalization are consistent between indexing and search.
You might cache avgDocLen for efficiency.
Let me know if you'd like this turned into pseudocode or want help modifying the query!