This vignette completes the search
side of the textpress pipeline. Where regex and dictionary
search match on form, and BM25 matches on term frequency,
embedding-based search matches on meaning – useful when the query and
the relevant passage share little surface vocabulary. Here they are run
on politics coverage from the weeks after the 2026 midterms, BM25 via
search_index() and semantic via
search_vector(), then combined with reciprocal rank fusion
(RRF). The top-ranked chunks are passed to an LLM for synthesis and
structured extraction, showing the full arc from raw URLs to generated
output.
Load packages.
The corpus comes from two openly reusable sources: the Pew Research
Center politics feed, taken from the bundled rss_politics
catalog, and The Conversation’s US politics feed. Both allow reuse with
attribution (The Conversation publishes under CC BY-ND 4.0; Pew Research
Center under its terms of use), so the article text can be saved with
this vignette. Entries were retrieved in November 2026, in the weeks
after the midterm elections, and only entries about the elections are
kept.
feeds <- c(
textpress::rss_politics |>
filter(source == "Pew Research Center") |>
pull(url),
"https://theconversation.com/us/politics/articles.atom"
)
web_urls <- textpress::fetch_rss(feeds) |>
filter(grepl(
"midterm|election|voter|Congress",
paste(title, description),
ignore.case = TRUE
)) |>
select(-doc_id) |>
distinct(url, .keep_all = TRUE)read_urls() scrapes and parses the article text;
nlp_split_sentences() segments each document into
analysis-ready sentence rows.
Roll each sentence into a chunk with one sentence of context
(before/after) for retrieval. nlp_roll_chunks() with
chunk_size = 1 and context_size = 1 yields a
focal sentence plus surrounding context in
chunk_plus_context.
Embed the chunk text (with context).
util_fetch_embeddings() defaults to a local Ollama server running the small
all-minilm model, so no account or API key is needed:
install Ollama and run ollama pull all-minilm once. Any
OpenAI-compatible endpoint works by changing base_url,
model, and api_key. The result is a numeric
matrix with one row per chunk; use it with search_vector()
for semantic search.
#> [1] 1011 384
#> [1] "1_1_1" "1_2_1" "1_3_1" "1_4_1" "1_4_2" "1_4_3"
Build a BM25 index over the same chunk text for keyword search. Tokenize by chunk, then index.
A single query string is used for both BM25 and semantic search, enabling a direct comparison of the two methods on the same input.
Search the index with the query. BM25 rewards chunks that share its terms.
Embed the same query, then run search_vector(). Semantic
search can rank chunks that answer the question in different words.
Merge the two ranked lists by uid and score each hit with
1 / (k + rank). k is a smoothing constant (here
60); larger k flattens the curve so lower ranks contribute
more. Sum scores per uid, then sort descending. Chunks that
appear in both lists get a higher fused score.
k <- 60
both <- bind_rows(bm25_hits, semantic_hits) |>
group_by(query, method) |>
mutate(rank = row_number()) |>
ungroup()
fused <- both |>
mutate(rrf = 1 / (k + rank)) |>
group_by(uid) |>
summarise(rrf_score = round(100 * sum(rrf), 3), .groups = "drop") |>
arrange(desc(rrf_score))
ff <- fused |>
left_join(chunks) |>
group_by(doc_id, node_id) |>
slice_max(nchar(text), n = 1, with_ties = FALSE) |>
ungroup() |>
slice_max(rrf_score, n = 15)Format the top-ranked chunks as labeled source blocks and concatenate into a single context string for the LLM. Initialize the chat client.
library(ellmer)
meta <- web_text_list$meta |> select(doc_id, date)
ff_meta <- ff |> left_join(meta, by = "doc_id") |>
mutate(
header = if_else(!is.na(date) & nzchar(trimws(date)),
paste0("## Source ", doc_id, " (", date, ")\n\n"),
paste0("## Source ", doc_id, "\n\n")
),
block = paste0(header, text)
)
context <- paste(ff_meta$block, collapse = "\n\n---\n\n")
chat <- ellmer::chat_openai(model = "gpt-4o-mini")Ask the model which explanations the passages give for the results, as structured rows that cite their sources.
explanation_schema <- ellmer::type_object(
"Explanations the passages give for the 2026 midterm results.",
explanations = ellmer::type_array(
ellmer::type_object(
"One explanation.",
factor = ellmer::type_string("Short name, e.g. turnout, economy, candidate quality."),
claim = ellmer::type_string("What the passages say about it, in one or two sentences."),
voters = ellmer::type_string("Voter groups involved, if the passages name any."),
sources = ellmer::type_string("Source numbers that support it, e.g. 3, 7.")
)
)
)
explanations_out <- chat$chat_structured(
glue::glue(
"Based solely on the passages, list the explanations given for the
results of the 2026 US midterm elections. Use one row per distinct
explanation and cite the source numbers that support it.
PASSAGES:\n{context}"
),
type = explanation_schema
)search_vector() and search_index() cover
complementary retrieval modes – meaning vs. term frequency. Combining
them with reciprocal rank fusion consistently outperforms either alone:
chunks that rank well in both lists rise to the top regardless of
surface vocabulary overlap. Passing the fused top chunks to an LLM
closes the loop from raw URLs to structured output.