ADescribe · describe.semantic_search
Semantic search (BM25, sentence embeddings, hybrid)
Which texts in this column best answer each of my questions or search phrases?
Ranks the texts of a column for each query you type. BM25 scores shared words, weighting rare words more and long texts less; it needs no download. Dense search compares meaning: each text and query becomes an all-MiniLM-L6-v2 sentence embedding, ranked by cosine similarity, so "football match" finds "the striker scored a late goal". Hybrid search fuses the two rankings by reciprocal rank fusion, which often beats either alone. Python and R compute the same scores; the embedder runs on this computer after a one-time download you approve (about 90 MB). ColBERT can rerank each query's best candidates by late interaction (MaxSim over token vectors; answerai-colbert-small-v1, a one-time download of about 134 MB). To measure how good a ranking is against relevance judgments, use Ranking evaluation.
A real result
Example “Corpus bm25”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
3 queries over 61 texts by words (BM25); best match for query 1: row 1.
- Texts
- 61
- Queries
- 3
- Distinct words (BM25)
- 231
Plots
View data
| BM25 score | Query | Text |
|---|---|---|
| 7.521 | Q1 | d01 |
| 7.521 | Q1 | d12 |
| 2.797 | Q1 | d07 |
| 2.188 | Q1 | d19 |
| 2.055 | Q1 | d03 |
| 6.653 | Q2 | d36 |
| 6.044 | Q2 | d27 |
| 3.856 | Q2 | d28 |
| 3.327 | Q2 | d31 |
| 2.905 | Q2 | d32 |
| 4.028 | Q3 | d50 |
| 3.784 | Q3 | d41 |
| 3.784 | Q3 | d42 |
| 3.784 | Q3 | d46 |
| 3.784 | Q3 | d57 |
Assumptions
- Words or meaning — BM25 matches shared words only; texts that use other words for the same idea score 0.
- English text — The stop list and all-MiniLM-L6-v2 are English.
Best-ranked texts
| Query | Query text | Rank | Row | doc | Text | BM25 score |
|---|---|---|---|---|---|---|
| 1 | late goal in the match | 1 | 1 | d01 | The striker scored a late goal and the team won the match at home | 7.521 |
| 1 | late goal in the match | 2 | 12 | d12 | League rivals met in a tense match that ended with a late goal | 7.521 |
| 1 | late goal in the match | 3 | 7 | d07 | The referee awarded a penalty and the striker scored the winning goal | 2.797 |
| 1 | late goal in the match | 4 | 19 | d19 | Training focused on set pieces before the derby match | 2.188 |
| 1 | late goal in the match | 5 | 3 | d03 | The coach praised the defence after a clean sheet in the league match | 2.055 |
| 2 | bake bread with flour and butter | 1 | 36 | d36 | Slice the bread and serve it warm with butter and soup | 6.653 |
| 2 | bake bread with flour and butter | 2 | 27 | d27 | Bake the bread until the crust is golden and sounds hollow | 6.044 |
| 2 | bake bread with flour and butter | 3 | 28 | d28 | Whisk the eggs with sugar then fold in the flour gently | 3.856 |
| 2 | bake bread with flour and butter | 4 | 31 | d31 | Fry the fish in butter and finish it with lemon and herbs | 3.327 |
| 2 | bake bread with flour and butter | 5 | 32 | d32 | Let the dough rest before you roll it out and bake it | 2.905 |
| 3 | interest rates | 1 | 50 | d50 | The currency weakened after the bank cut interest rates | 4.028 |
| 3 | interest rates | 2 | 41 | d41 | Shares fell as investors worried about rising interest rates | 3.784 |
| 3 | interest rates | 3 | 42 | d42 | The central bank raised interest rates to slow inflation | 3.784 |
| 3 | interest rates | 4 | 46 | d46 | Inflation eased and the bank signalled lower interest rates | 3.784 |
| 3 | interest rates | 5 | 57 | d57 | The fund manager bought bonds as interest rates peaked | 3.784 |
Ties keep row order.
Queries
| Query | Text |
|---|---|
| 1 | late goal in the match |
| 2 | bake bread with flour and butter |
| 3 | interest rates |
- 1 of 62 rows were left out because a value was missing.
- BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.
3 queries over 61 texts by words (BM25); best match for query 1: row 1.
- Texts
- 61
- Queries
- 3
- Distinct words (BM25)
- 231
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Words or meaning — BM25 matches shared words only; texts that use other words for the same idea score 0.
- English text — The stop list and all-MiniLM-L6-v2 are English.
Best-ranked texts
| Query | Query text | Rank | Row | doc | Text | BM25 score |
|---|---|---|---|---|---|---|
| 1 | late goal in the match | 1 | 1 | d01 | The striker scored a late goal and the team won the match at home | 7.521 |
| 1 | late goal in the match | 2 | 12 | d12 | League rivals met in a tense match that ended with a late goal | 7.521 |
| 1 | late goal in the match | 3 | 7 | d07 | The referee awarded a penalty and the striker scored the winning goal | 2.797 |
| 1 | late goal in the match | 4 | 19 | d19 | Training focused on set pieces before the derby match | 2.188 |
| 1 | late goal in the match | 5 | 3 | d03 | The coach praised the defence after a clean sheet in the league match | 2.055 |
| 2 | bake bread with flour and butter | 1 | 36 | d36 | Slice the bread and serve it warm with butter and soup | 6.653 |
| 2 | bake bread with flour and butter | 2 | 27 | d27 | Bake the bread until the crust is golden and sounds hollow | 6.044 |
| 2 | bake bread with flour and butter | 3 | 28 | d28 | Whisk the eggs with sugar then fold in the flour gently | 3.856 |
| 2 | bake bread with flour and butter | 4 | 31 | d31 | Fry the fish in butter and finish it with lemon and herbs | 3.327 |
| 2 | bake bread with flour and butter | 5 | 32 | d32 | Let the dough rest before you roll it out and bake it | 2.905 |
| 3 | interest rates | 1 | 50 | d50 | The currency weakened after the bank cut interest rates | 4.028 |
| 3 | interest rates | 2 | 41 | d41 | Shares fell as investors worried about rising interest rates | 3.784 |
| 3 | interest rates | 3 | 42 | d42 | The central bank raised interest rates to slow inflation | 3.784 |
| 3 | interest rates | 4 | 46 | d46 | Inflation eased and the bank signalled lower interest rates | 3.784 |
| 3 | interest rates | 5 | 57 | d57 | The fund manager bought bonds as interest rates peaked | 3.784 |
Ties keep row order.
Queries
| Query | Text |
|---|---|
| 1 | late goal in the match |
| 2 | bake bread with flour and butter |
| 3 | interest rates |
- 1 of 62 rows were left out because a value was missing.
- BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Corpus bm25ml_corpus · label: doc · text: text
- Corpus denseml_corpus · label: doc · text: text
- Corpus hybridml_corpus · text: text
- Reviews bm25 tuneds5_reviews · label: id · text: review text
- Reviews no match querys5_reviews · text: review text
- Regress bm25 b1 empty texts5_reviews · label: id · text: review text
- Corpus bm25 colbertml_corpus · label: doc · text: text
- Reviews hybrid colberts5_reviews · label: id · text: review text
In the guides
Where it sits in the decision guides
- Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
- LLMs for prediction (zero/few-shot, RAG) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Textcategorical · 1 column
- The column of texts to search; each row is one document.
- Document name (optional)categorical · 0–1 column
- Optional — a column that names each document (an id or title), shown in the results.
Choices you make
model
- Queriesdefault —
What to search for; separate several queries with semicolons. Each query gets its own ranking.
- Search bydefault bm25
Words (BM25) needs no download; meaning (dense) and hybrid use the all-MiniLM-L6-v2 embedder.
- Words (BM25, no download)(default) — Scores texts that share the query's words; rare words count more and long texts less. Misses synonyms.
- Meaning (sentence embeddings) — Cosine similarity of all-MiniLM-L6-v2 embeddings; finds texts that say the same thing in other words.
- Both (reciprocal rank fusion) — Adds 1 / (k + rank) from the BM25 and the dense rankings, so a text ranked well by either rises.
- Results per querydefault 5
How many of the best-ranked texts to list for each query.
- Rerankdefault none
Optionally reorder each query's best candidates with ColBERT, which compares every query word with every text word (a one-time download you approve).
- No reranking(default) — Keep the ranking from the search above.
- ColBERT MaxSim (~134 MB) — answerai-colbert-small-v1 scores each candidate: for each query token, its best match among the text's tokens, summed (Apache-2.0).
options
- Candidates to rerankdefault 20
How many of each query's best-ranked texts ColBERT rescores (never fewer than Results per query).
Advanced
- BM25 k1default 1.2
How fast repeated words stop adding to the score; 1.2 is the usual default (0 = only presence counts).
- BM25 bdefault 0.75
How much long texts are penalized: 0 none, 1 fully in proportion to length; 0.75 is the usual default.
- Fusion constant kdefault 60
Reciprocal rank fusion adds 1 / (k + rank); larger k flattens the advantage of the very top ranks (60 is the usual value).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Words or meaning
BM25 only matches shared words (after lower-casing and leaving out common English words); dense search matches meaning but can miss exact names and codes.
English text
The stop list and all-MiniLM-L6-v2 are English; other languages need another tokenizer and embedder.
What it reports
- n_docs
- How many texts were searched, how many queries were run and how many best-ranked texts are listed for each.
- n_queries
- How many texts were searched, how many queries were run and how many best-ranked texts are listed for each.
- top_k
- How many texts were searched, how many queries were run and how many best-ranked texts are listed for each.
- retriever
- Search that embeds each text and query and ranks texts by cosine similarity, so a match can share meaning without sharing words.
- n_terms
- A text-search score that adds up the query's words found in a text, weighting rare words more and long texts less.
- n_no_match
- A text-search score that adds up the query's words found in a text, weighting rare words more and long texts less.
Per group, level or term: rerank_<setting>, top_row[<query>], top_score[<query>], row[<query>:<rank>], score[<query>:<rank>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses numpy, pandas, codesplash; R uses nanoparquet, stringi, codesplashr.
Default traps between the two languages
- BM25 is the same arithmetic in both engines (P0, summed in query order); tokens are codesplash.ml.text.tokenize ↔ cs_ml_tokenize, where Python's [^\W\d_] counts a few non-letter characters (superscript digits, fractions) as letters and R's \p{L} does not.
- Dense and hybrid scores use the same all-MiniLM-L6-v2 twin in float64 in both engines; matrix products use each engine's BLAS, so similarities agree to about 1e-12 rather than exactly.
- Without the downloaded weights, dense and hybrid search stop with CS_WEIGHTS_MISSING in both engines; BM25 needs no weights.
- ColBERT reranking (1.1.0) runs the same float64 BERT twin and projection in both engines (codesplash.text.colbert ↔ R/text_colbert.R); MaxSim scores agree to about 1e-14. Without its weights the run stops with CS_WEIGHTS_MISSING.
The exact script CodeSplash ran for example “Corpus bm25” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Semantic search (BM25, sentence embeddings, hybrid)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.semantic_search 1.1.0 · spec 611d7166eac896fa
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.text import search as ss # BM25, rankings, rank fusion (twin: codesplashr cs_bm25*, cs_search_*)
# %% Data (rows with a text)
TEXT = "text"
LABEL = "doc"
df = pd.read_parquet("tests/parity/fixtures/ml_corpus.parquet", columns=["text", "doc"])
n_input = len(df)
df = df[df[TEXT].notna()]
warnings = []
if n_input - len(df):
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
rows = (df.index.to_numpy() + 1).astype(np.int64) # 1-based input rows
texts = df[TEXT].astype(str).tolist()
n = len(texts)
names = [None if pd.isna(v) else str(v) for v in df[LABEL].tolist()] if LABEL else [None] * n
unique_names = LABEL is not None and None not in names and len(set(names)) == n
doc_label = [names[i] if unique_names else f"Row {rows[i]}" for i in range(n)]
# %% Queries and settings
QUERIES = ss.split_list("late goal in the match; bake bread with flour and butter; interest rates")
if not QUERIES:
cs.cs_error("CS_E_INVALID_OPTION", option="Queries", allowed="at least one query (separate several with semicolons)", value="(empty)")
if len(QUERIES) > 50:
cs.cs_error("CS_E_INVALID_OPTION", option="Queries", allowed="at most 50 queries", value=f"{len(QUERIES)} queries")
RETRIEVER = "bm25"
TOP_K = min(int(5), n)
m = len(QUERIES)
# %% Scores
bm25 = dense = None
n_terms, no_match = None, []
if RETRIEVER in ("bm25", "hybrid"):
bm = ss.Bm25(texts, k1=1.2, b=0.75)
if bm.avgdl <= 0:
cs.cs_error("CS_E_UNDEFINED", what="BM25 scores", reason="no text has a word of two or more letters outside the common-word list")
n_terms = bm.n_terms
bm25 = np.vstack([bm.scores(q) for q in QUERIES]) # queries × texts
no_match = [j for j in range(m) if not np.any(bm25[j] > 0)]
for j in no_match:
warnings.append(f"Query {j + 1} (“{ss.snippet(QUERIES[j], 40)}”) shares no word with any text, so its BM25 ranking is just row order.")
if RETRIEVER in ("dense", "hybrid"):
from codesplash.text import minilm # all-MiniLM-L6-v2 in numpy (twin: cs_minilm_embed)
if not minilm.available():
cs.cs_error("CS_WEIGHTS_MISSING", model=f"{minilm.NAME} (download it from Discover → Topics in text → Pretrained embeddings)")
model = minilm.Model()
dense = ss.cosine(minilm.embed(QUERIES, model), minilm.embed(texts, model)) # queries × texts
if RETRIEVER == "bm25":
final = bm25
elif RETRIEVER == "dense":
final = dense
else:
final = np.vstack([ss.rrf(ss.ranks(bm25[j]), ss.ranks(dense[j]), k=60) for j in range(m)])
# %% Rankings
result_rows = []
values = {"n_docs": n, "n_queries": m, "top_k": TOP_K,
"retriever": {"bm25": "words (BM25)", "dense": "meaning (sentence embeddings)", "hybrid": "words and meaning (reciprocal rank fusion)"}[RETRIEVER],
"n_terms": n_terms, "n_no_match": len(no_match) if bm25 is not None else None}
for j, q in enumerate(QUERIES):
order = ss.ranking(final[j])[:TOP_K]
key = f"q{j + 1}"
values[f"top_row[{key}]"] = int(rows[order[0]])
values[f"top_score[{key}]"] = float(final[j][order[0]])
for r, i in enumerate(order, start=1):
values[f"row[{key}:{r}]"] = int(rows[i])
values[f"score[{key}:{r}]"] = float(final[j][i])
row = {"query": j + 1, "query_text": ss.snippet(q, 60), "rank": r, "row": int(rows[i]), "document": doc_label[i],
"text": ss.snippet(texts[i]), "score": float(final[j][i])}
if RETRIEVER == "hybrid":
row["bm25"] = float(bm25[j][i])
row["similarity"] = float(dense[j][i])
result_rows.append(row)
score_label = {"bm25": "BM25 score", "dense": "Cosine similarity", "hybrid": "Fusion score"}[RETRIEVER]
cols = [{"key": "query", "label": "Query", "type": "integer"}, {"key": "query_text", "label": "Query text", "type": "string"},
{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"}]
if LABEL:
cols.append({"key": "document", "label": LABEL if unique_names else "Document", "type": "string"})
cols += [{"key": "text", "label": "Text", "type": "string"}, {"key": "score", "label": score_label, "type": "number"}]
if RETRIEVER == "hybrid":
cols += [{"key": "bm25", "label": "BM25 score", "type": "number"}, {"key": "similarity", "label": "Cosine similarity", "type": "number"}]
tables = [
{"key": "results", "title": "Best-ranked texts", "columns": cols, "rows": result_rows,
"note": "Ties keep row order." + (" Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings." if RETRIEVER == "hybrid" else "")},
{"key": "queries", "title": "Queries", "columns": [{"key": "query", "label": "Query", "type": "integer"}, {"key": "text", "label": "Text", "type": "string"}],
"rows": [{"query": j + 1, "text": q} for j, q in enumerate(QUERIES)]},
]
charts = []
if m <= 9: # the chart draws at most 9 panels; the table has every query
qlevels = [f"Q{j + 1}" for j in range(m)]
terms, scores, groups = [], [], []
for res in result_rows:
terms.append(res["document"])
scores.append(res["score"])
groups.append(f"Q{res['query']}")
charts.append(cs.chart("results", "ngram-bars", f"Best-ranked texts per query ({score_label.lower()})", {
"term": cs.col("Text", terms, kind="categorical"), "count": cs.col(score_label, scores),
"group": cs.col("Query", groups, kind="categorical", levels=qlevels)}, controls={"top": max(3, TOP_K)}))
assumptions = [
{"key": "words_vs_meaning", "label": "Words or meaning", "status": "info",
"detail": {"bm25": "BM25 matches shared words only; texts that use other words for the same idea score 0.",
"dense": "Dense search matches meaning; exact names, numbers and codes can rank lower than with BM25.",
"hybrid": "Hybrid search combines both rankings, so a text matched by words or by meaning can rise."}[RETRIEVER]},
{"key": "language", "label": "English text", "status": "info", "detail": "The stop list and all-MiniLM-L6-v2 are English."},
]
summary = f"{m} quer{'y' if m == 1 else 'ies'} over {n} texts by {values['retriever']}; best match for query 1: row {values['top_row[q1]']}."
cs.publish({
"method": "describe.semantic_search",
"methodVersion": "1.1.0",
"title": "Semantic search",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [{"key": "n_docs", "label": "Texts", "value": n}, {"key": "n_queries", "label": "Queries", "value": m}]
+ ([{"key": "n_terms", "label": "Distinct words (BM25)", "value": n_terms}] if n_terms is not None else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": ["BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out."] if bm25 is not None else [],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Corpus bm25” · R version 4.5.1 (2025-06-13)
# Semantic search (BM25, sentence embeddings, hybrid)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.semantic_search 1.1.0 · spec 611d7166eac896fa
# Dataset: ml_corpus (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_bm25*, cs_search_* (twins of codesplash.text.search) and cs_minilm_embed
# %% Data (rows with a text)
TEXT <- "text"
LABEL <- "doc"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_corpus.parquet", col_select = c("text", "doc")))
n_input <- nrow(df)
keep_rows <- which(!is.na(df[[TEXT]]))
df <- df[keep_rows, , drop = FALSE]
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
rows <- as.integer(keep_rows) # 1-based input rows
texts <- as.character(df[[TEXT]])
n <- length(texts)
doc_names <- if (!is.null(LABEL)) as.character(df[[LABEL]]) else rep(NA_character_, n)
unique_names <- !is.null(LABEL) && !anyNA(doc_names) && !anyDuplicated(doc_names)
doc_label <- if (unique_names) doc_names else sprintf("Row %d", rows)
# %% Queries and settings
QUERIES <- cs_search_split_list("late goal in the match; bake bread with flour and butter; interest rates")
if (!length(QUERIES)) cs_error("CS_E_INVALID_OPTION", option = "Queries", allowed = "at least one query (separate several with semicolons)", value = "(empty)")
if (length(QUERIES) > 50) cs_error("CS_E_INVALID_OPTION", option = "Queries", allowed = "at most 50 queries", value = sprintf("%d queries", length(QUERIES)))
RETRIEVER <- "bm25"
TOP_K <- min(as.integer(5), n)
m <- length(QUERIES)
# %% Scores
bm25 <- NULL
dense <- NULL
n_terms <- NA
no_match <- integer(0)
if (RETRIEVER %in% c("bm25", "hybrid")) {
bm <- cs_bm25(texts, k1 = 1.2, b = 0.75)
if (bm$avgdl <= 0) cs_error("CS_E_UNDEFINED", what = "BM25 scores", reason = "no text has a word of two or more letters outside the common-word list")
n_terms <- cs_bm25_n_terms(bm)
bm25 <- do.call(rbind, lapply(QUERIES, function(q) cs_bm25_scores(bm, q))) # queries x texts
no_match <- which(apply(bm25, 1, function(s) !any(s > 0)))
for (j in no_match) {
warnings <- c(warnings, sprintf("Query %d (“%s”) shares no word with any text, so its BM25 ranking is just row order.", j, cs_search_snippet(QUERIES[j], 40)))
}
}
if (RETRIEVER %in% c("dense", "hybrid")) {
if (!cs_minilm_available()) cs_error("CS_WEIGHTS_MISSING", model = "all-MiniLM-L6-v2 (download it from Discover → Topics in text → Pretrained embeddings)")
model <- cs_minilm_load()
dense <- cs_search_cosine(cs_minilm_embed(QUERIES, model), cs_minilm_embed(texts, model)) # queries x texts
}
final <- if (RETRIEVER == "bm25") {
bm25
} else if (RETRIEVER == "dense") {
dense
} else {
do.call(rbind, lapply(seq_len(m), function(j) cs_search_rrf(list(cs_search_ranks(bm25[j, ]), cs_search_ranks(dense[j, ])), k = 60)))
}
final <- matrix(final, nrow = m)
# %% Rankings
retriever_label <- c(bm25 = "words (BM25)", dense = "meaning (sentence embeddings)", hybrid = "words and meaning (reciprocal rank fusion)")[[RETRIEVER]]
values <- list(n_docs = n, n_queries = m, top_k = TOP_K, retriever = retriever_label,
n_terms = n_terms, n_no_match = if (!is.null(bm25)) length(no_match) else NA)
result_rows <- list()
for (j in seq_len(m)) {
order_j <- utils::head(cs_search_ranking(final[j, ]), TOP_K)
key <- sprintf("q%d", j)
values[[sprintf("top_row[%s]", key)]] <- rows[order_j[1]]
values[[sprintf("top_score[%s]", key)]] <- final[j, order_j[1]]
for (r in seq_along(order_j)) {
i <- order_j[r]
values[[sprintf("row[%s:%d]", key, r)]] <- rows[i]
values[[sprintf("score[%s:%d]", key, r)]] <- final[j, i]
row <- list(query = j, query_text = cs_search_snippet(QUERIES[j], 60), rank = r, row = rows[i], document = doc_label[i],
text = cs_search_snippet(texts[i]), score = final[j, i])
if (RETRIEVER == "hybrid") {
row$bm25 <- bm25[j, i]
row$similarity <- dense[j, i]
}
result_rows[[length(result_rows) + 1]] <- row
}
}
score_label <- c(bm25 = "BM25 score", dense = "Cosine similarity", hybrid = "Fusion score")[[RETRIEVER]]
cols <- list(list(key = "query", label = "Query", type = "integer"), list(key = "query_text", label = "Query text", type = "string"),
list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"))
if (!is.null(LABEL)) cols <- c(cols, list(list(key = "document", label = if (unique_names) LABEL else "Document", type = "string")))
cols <- c(cols, list(list(key = "text", label = "Text", type = "string"), list(key = "score", label = score_label, type = "number")))
if (RETRIEVER == "hybrid") cols <- c(cols, list(list(key = "bm25", label = "BM25 score", type = "number"), list(key = "similarity", label = "Cosine similarity", type = "number")))
tables <- list(
list(key = "results", title = "Best-ranked texts", columns = cols, rows = result_rows,
note = paste0("Ties keep row order.", if (RETRIEVER == "hybrid") " Fusion score = Σ 1 / (k + rank) over the BM25 and the dense rankings." else "")),
list(key = "queries", title = "Queries", columns = list(list(key = "query", label = "Query", type = "integer"), list(key = "text", label = "Text", type = "string")),
rows = lapply(seq_len(m), function(j) list(query = j, text = QUERIES[j])))
)
charts <- list()
if (m <= 9) { # the chart draws at most 9 panels; the table has every query
rv <- function(k) vapply(result_rows, function(r) r[[k]], if (k == "score") numeric(1) else if (k == "query") integer(1) else character(1))
charts[[1]] <- cs_chart("results", "ngram-bars", sprintf("Best-ranked texts per query (%s)", tolower(score_label)),
list(term = cs_col("Text", rv("document"), kind = "categorical"), count = cs_col(score_label, rv("score")),
group = cs_col("Query", sprintf("Q%d", rv("query")), kind = "categorical", levels = sprintf("Q%d", seq_len(m)))),
controls = list(top = max(3L, TOP_K)))
}
assumptions <- list(
list(key = "words_vs_meaning", label = "Words or meaning", status = "info",
detail = c(bm25 = "BM25 matches shared words only; texts that use other words for the same idea score 0.",
dense = "Dense search matches meaning; exact names, numbers and codes can rank lower than with BM25.",
hybrid = "Hybrid search combines both rankings, so a text matched by words or by meaning can rise.")[[RETRIEVER]]),
list(key = "language", label = "English text", status = "info", detail = "The stop list and all-MiniLM-L6-v2 are English.")
)
summary <- sprintf("%d quer%s over %d texts by %s; best match for query 1: row %d.", m, if (m == 1) "y" else "ies", n, retriever_label, values[["top_row[q1]"]])
cs_publish(list(
method = "describe.semantic_search",
methodVersion = "1.1.0",
title = "Semantic search",
engine = cs_engine_info("nanoparquet", "stringi"),
n = n,
summary = summary,
statistics = c(list(list(key = "n_docs", label = "Texts", value = n), list(key = "n_queries", label = "Queries", value = m)),
if (!is.na(n_terms)) list(list(key = "n_terms", label = "Distinct words (BM25)", value = n_terms)) else list()),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = if (!is.null(bm25)) list("BM25: Lucene's idf ln(1 + (N − n + 0.5) / (n + 0.5)) with k1 and b; tokens are lower-cased words of two or more letters, common English words left out.") else list(),
charts = charts,
values = values
))
Sources
- Khattab O, Zaharia M (2020). ColBERT: efficient and effective passage search via contextualized late interaction over BERT. SIGIR 2020, 39–48.
- Santhanam K, Khattab O, Saad-Falcon J, Potts C, Zaharia M (2022). ColBERTv2: effective and efficient retrieval via lightweight late interaction. NAACL 2022.
- Clavié B (2024). JaColBERTv2.5: optimising multi-vector retrievers to create state-of-the-art Japanese retrievers with constrained resources. arXiv:2407.20750 (answerai-colbert-small-v1's training recipe).
- Robertson S, Zaragoza H (2009). The probabilistic relevance framework: BM25 and beyond. Foundations and Trends in Information Retrieval 3(4):333–389.
- Cormack GV, Clarke CLA, Büttcher S (2009). Reciprocal rank fusion outperforms Condorcet and individual rank learning methods. SIGIR 2009, 758–759.
- Karpukhin V, Oğuz B, Min S, Lewis P, Wu L, Edunov S, Chen D, Yih W (2020). Dense passage retrieval for open-domain question answering. EMNLP 2020, 6769–6781.
- Reimers N, Gurevych I (2019). Sentence-BERT: sentence embeddings using Siamese BERT-networks. EMNLP-IJCNLP 2019, 3982–3992.
- Manning CD, Raghavan P, Schütze H (2008). Introduction to Information Retrieval, ch. 11. Cambridge University Press.
From the CodeSplash method registry · describe.semantic_search v1.1.0.