Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ DESIGN, SAFETY & SHIPPING
BUILD NOTE 53 / 53

Put the pieces to work.

Build a reusable in-memory search core with deterministic results.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

This capstone turns text documents into a small inverted index. Each lowercase whitespace-separated term maps to a sorted set of document IDs. Inserting the same term twice in one document does not duplicate the posting. Querying returns the stored IDs in sorted order. This deliberately simple tokenizer treats punctuation as part of a term and is not a complete search engine. Make that contract visible, then extend it with multi-term intersections, replacement semantics, and persistence only when tests define the new behavior.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/capstone/src/main.rs
use std::collections::{BTreeMap, BTreeSet};
#[derive(Default)]
struct Index {
    postings: BTreeMap<String, BTreeSet<u32>>,
}
impl Index {
    fn insert(&mut self, id: u32, text: &str) {
        for word in text.split_whitespace() {
            self.postings
                .entry(word.to_lowercase())
                .or_default()
                .insert(id);
        }
    }
    fn query(&self, word: &str) -> Vec<u32> {
        self.postings
            .get(&word.to_lowercase())
            .map(|ids| ids.iter().copied().collect())
            .unwrap_or_default()
    }
}
fn main() {
    let mut index = Index::default();
    index.insert(2, "Rust builds");
    index.insert(1, "rust rust tests");
    println!("{:?}", index.query("RUST"));
    assert!(index.query("missing").is_empty());
}
↳ EXPECTED OUTPUT
[1, 2]
  1. 1

    The outer map owns normalized terms.

  2. 2

    The set deduplicates document IDs and sorts the results.

  3. 3

    Query borrows the index and returns an independent vector.

From the extracted rust-workbench folder
cargo run -p lesson_capstone

03 Mind the boundary

04 Your next build

A SMALL MISSION

Implement a two-term intersection query over sorted ID sets and test missing and repeated terms.

Reveal one possible solution +
solutions/capstone/src/main.rs
use std::collections::{BTreeMap, BTreeSet};
fn both(index: &BTreeMap<&str, BTreeSet<u32>>, a: &str, b: &str) -> Vec<u32> {
    match (index.get(a), index.get(b)) {
        (Some(left), Some(right)) => left.intersection(right).copied().collect(),
        _ => Vec::new(),
    }
}
fn main() {
    let index = BTreeMap::from([
        ("rust", BTreeSet::from([1, 2])),
        ("web", BTreeSet::from([2, 3])),
    ]);
    assert_eq!(both(&index, "rust", "web"), [2]);
    assert_eq!(both(&index, "rust", "rust"), [1, 2]);
    assert!(both(&index, "rust", "none").is_empty());
}
  • □Case-insensitive term lookup returns sorted unique document IDs.
  • □An unknown term returns an empty result.
  • □Two-term intersection handles missing and repeated terms.
  • □The tokenizer and document replacement limitations are documented.

05 Check your reasoning

QUICK SIGNAL CHECK

Why use a set for each posting list?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.