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 recent politics coverage about 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.

Sources

The corpus comes from six outlets in the bundled rss_politics catalog: NPR, PBS News, Fox News, the Los Angeles Times, Vox, and The Dispatch. fetch_rss() retrieves their current entries, and ordinary filtering keeps entries about the elections.

outlets <- c("NPR", "PBS News", "Fox News", "Los Angeles Times", "Vox", "The Dispatch")

web_urls <- textpress::rss_politics |>
  filter(source %in% outlets) |>
  pull(url) |>
  textpress::fetch_rss() |>
  filter(grepl(
    "midterm|election|voter|Congress",
    paste(title, description),
    ignore.case = TRUE
  )) |>
  select(-doc_id) |>
  distinct(url, .keep_all = TRUE)

Web text and sentence split

read_urls() scrapes and parses the article text; nlp_split_sentences() segments each document into analysis-ready sentence rows.

web_text_list <- web_urls |>
  textpress::read_urls(cores = 4)

web_ss <- web_text_list$text |>
  textpress::nlp_split_sentences(by = c("doc_id", "node_id"))

Chunks: 1 sentence + 1 sentence context

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.

chunks <- textpress::nlp_roll_chunks(
  web_ss,
  by = c("doc_id", "node_id", "sentence_id"),
  id_col = 'uid',
  chunk_size = 1,
  context_size = 1)

Embeddings for chunks

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.

embeddings <- textpress::util_fetch_embeddings(
  chunks,
  by = "uid"
) |>
  round(4) # plenty for cosine similarity; keeps the saved matrix small
dim(embeddings)
#> [1] 1679  384
head(rownames(embeddings))
#> [1] "1_1_1" "1_2_1" "1_3_1" "1_4_1" "1_5_1" "1_6_1"

BM25 index

Build a BM25 index over the same chunk text for keyword search. Tokenize by chunk, then index.

index <- textpress::nlp_tokenize_text(
  chunks,
  by = c("uid"),
  include_spans = FALSE
  ) |>
  textpress::nlp_index_tokens(stem = T)

A single query string is used for both BM25 and semantic search, enabling a direct comparison of the two methods on the same input.

query_text <- "Why did Democrats gain in the 2026 midterms and which voters shifted?"

BM25

Search the index with the query. BM25 rewards chunks that share its terms.

bm25_hits <- search_index(index,
                          query_text,
                          n = 25,
                          stem = TRUE)

bm25_hits |>
  DT::datatable(
    rownames = FALSE,
    options = list(dom = "lrtip",
                   pageLength = 5))

Semantic

Embed the same query, then run search_vector(). Semantic search can rank chunks that answer the question in different words.

query_embed <- textpress::util_fetch_embeddings(query_text)
semantic_hits <- search_vector(embeddings, query_embed, n = 25)

semantic_hits |>
  DT::datatable(
    rownames = FALSE,
    options = list(dom = "lrtip",
                   pageLength = 5))

Hybrid: reciprocal rank fusion (RRF)

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)

LLM calls over retrieved chunks

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")

Explaining the midterm results

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
)
explanations_out$explanations |> DT::datatable(rownames = F)

Summary

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.