Skip to content

About

A real mini full-text search engine: inverted index, TF-IDF ranking, and a boolean AND/OR/NOT query parser. Zero-dependency Rust.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

rs-invertedindex

A real, small, zero-dependency full-text search engine for Rust: an inverted index, TF-IDF relevance ranking, and a boolean AND/OR/NOT query parser with parenthesized grouping — the same core mechanism that underpins search systems like Elasticsearch and Apache Lucene, distilled to something you can read end-to-end in a few minutes.

Why this is genuinely useful: almost every "search this text" feature — searching support tickets, log lines, product descriptions, notes, documentation — needs two things underneath: a fast way to find which documents contain a term (instead of scanning every document on every query), and a way to rank the matches by relevance. That's exactly what an inverted index plus TF-IDF gives you. This crate implements both from scratch, in safe Rust, with no dependencies, so it's easy to audit, embed, or learn from.

Usage

use rs_invertedindex::Index;

fn main() {
    let mut index = Index::new();
    index.add_document("Rust is a systems language with a focus on safety and performance"); // doc 0
    index.add_document("Python is a popular language for data science and web development"); // doc 1
    index.add_document("This storage engine is written in Rust for high performance workloads"); // doc 2

    // Boolean query: docs that mention Rust but not Python.
    let matches = index.search_boolean("rust AND NOT python").unwrap();
    assert_eq!(matches, vec![0, 2]);

    // Nested boolean query with parentheses.
    let matches = index
        .search_boolean("(rust OR python) AND performance")
        .unwrap();
    assert_eq!(matches, vec![0, 2]);

    // TF-IDF ranked search: most relevant documents for "performance" first.
    for result in index.search_ranked("performance") {
        println!("doc {} scored {:.4}", result.doc_id, result.score);
    }

    // Malformed queries return a real error instead of panicking.
    assert!(index.search_boolean("rust AND (python").is_err());
}

How it works

Tokenization

Text is lowercased and split into maximal runs of alphanumeric characters; every other character (whitespace, punctuation, symbols) is a separator and is discarded. There is no stemming: "running" and "run" are indexed and matched as two entirely distinct terms, and "database" will not match a query for "databases". This keeps the implementation small and its behavior predictable, at the cost of missing some real-world matches a stemmed or lemmatized index would catch.

Inverted index

Index maps each term to a postings list: a Vec<(DocId, usize)> of every document containing that term, paired with how many times it occurs there (its term frequency). Document ids are assigned sequentially starting at 0 as documents are added via add_document, and each document's original text and token length are kept alongside the postings so they can be retrieved and used for scoring.

TF-IDF scoring

search_ranked tokenizes the query, and for every document sums, over each unique query term:

score(t, d) = tf(t, d) * idf(t)

tf(t, d)  = count(t, d) / length(d)         // term frequency, normalized by document length
idf(t)    = ln(total_docs / docs_containing(t))   // inverse document frequency, natural log

Normalizing tf by document length keeps a term's weight from being inflated purely because a document is long. idf down-weights terms that appear in most documents (which carry little discriminating power) and up-weights rarer, more specific terms. Documents are returned sorted by descending score, with ties broken by ascending document id for deterministic output.

Boolean query parser

search_boolean runs a real recursive-descent parser over the query string — it is not a special-case matcher for one or two terms. The grammar (operator keywords are case-insensitive):

expr     := and_expr ( OR and_expr )*
and_expr := unary ( ( AND | NOT ) unary )*
unary    := NOT unary | atom
atom     := TERM | '(' expr ')'

Precedence, loosest to tightest: OR binds loosest, then AND, then NOT binds tightest — matching how most boolean/programming-language logical operators are conventionally read. Parentheses override precedence and can be nested arbitrarily, so queries like (rust OR python) AND (database OR framework) AND NOT slow parse and evaluate correctly, not just two-term cases. A bare NOT appearing where an AND could also appear (e.g. a NOT b) is treated as shorthand for a AND NOT b (set difference), so queries read naturally without forcing every negation to spell out AND NOT.

The parsed AST is evaluated against the index's postings by combining per-term document-id sets with set intersection (AND), union (OR), and complement relative to all indexed documents (NOT). Malformed queries — empty input, unbalanced parentheses, dangling operators — return a ParseError rather than panicking.

Testing

Run:

cargo test

This runs:

  • Unit tests for the tokenizer's boundary handling and no-stemming behavior.
  • Parser tests asserting the exact AST produced for precedence and parenthesized queries, and that malformed queries produce errors.
  • A hand-written 10-document corpus with genuine, deliberate term overlap (documents about Rust/databases/storage, Python/web/frameworks, and two documents built specifically to test TF-IDF term-frequency weighting). The expected matching doc_id sets for several AND/OR/NOT/nested boolean queries against that corpus are derived by hand (reading the corpus text, documented inline in src/lib.rs) before checking what the implementation returns, then asserted exactly.
  • A TF-IDF ranking test where one term appears 5 times in one document and once in another of comparable length, asserting the 5-occurrence document ranks strictly higher.
  • Runnable doctest examples on every public item.

Scope and limitations

This is a compact, honest implementation, not a production search engine:

  • No stemming or lemmatization — exact token matching only.
  • No fuzzy matching or typo tolerance.
  • No phrase search (e.g. "exact phrase" matching) — only individual term postings and boolean combinations of them.
  • In-memory only — no persistence, no incremental disk index, no concurrent/distributed indexing.
  • Scoring uses one standard TF-IDF variant (length-normalized term frequency times natural-log IDF); it is not configurable or pluggable.

License

MIT. See LICENSE.

About

A real mini full-text search engine: inverted index, TF-IDF ranking, and a boolean AND/OR/NOT query parser. Zero-dependency Rust.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages