Semantic search

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.

library(textpress)
library(dplyr)

Sources

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)

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"
)
dim(embeddings)
#> [1] 1011  384
head(rownames(embeddings))
#> [1] "1_1_1" "1_2_1" "1_3_1" "1_4_1" "1_4_2" "1_4_3"

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)

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.