---
title: "Semantic search"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Semantic search}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  message = FALSE,
  warning = FALSE,
  comment = "#>"
)
source("cache-hook.R")
```


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.

```{r message=FALSE, warning=FALSE}
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.

```{r web-urls, cache_rds = c("feeds", "web_urls")}
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.

```{r web-text, cache_rds = c("web_text_list", "web_ss")}
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`.

```{r chunks}
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](https://ollama.com) 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.

```{r embeddings, cache_rds = "embeddings"}
embeddings <- textpress::util_fetch_embeddings(
  chunks,
  by = "uid"
)
```

```{r show-embeddings}
dim(embeddings)
head(rownames(embeddings))
```



## BM25 index

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

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



## Search

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

```{r}
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.

```{r search-bm25, message=FALSE, warning=FALSE}
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.

```{r query-embed, cache_rds = "query_embed"}
query_embed <- textpress::util_fetch_embeddings(query_text)
```

```{r search-semantic}
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.

```{r rrf, message=FALSE, warning=FALSE}
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.

```{r llm-setup, cache_rds = "context"}
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.

```{r llm-explanations, cache_rds = "explanations_out"}
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
)
```

```{r show-explanations}
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.



