Skip to content

Unit 4 · Boolean & Tolerant Retrieval

3 h contact · 7 h self study Prerequisites: Unit 3 CLO 3

1. Setting the scene

Scenario: The legal clerk's query

Herr Aydın, a legal clerk in the Senate Department for Urban Development, needs every regulation that mentions rent control and termination of tenancy, but not commercial leases. He does not want "the best ten results"; he wants all of them, and he wants to know exactly why each one matched:

Mietpreisbremse AND Kündigung AND NOT Gewerbe

He also searches for a landlord named "Hermann", spelled "Herman" in half the scanned letters, and for the exact phrase "Berliner Mietendeckel".

Guiding questions

  1. Why would scanning all 2 million documents with grep be unacceptable?
  2. Which data structure lets us answer AND queries without reading every document?
  3. How can a system tolerate typos, spelling variants and wildcards?
  4. How do we know two words are next to each other?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 4.1 Represent a collection as a term, document incidence matrix and evaluate Boolean queries with bit vectors. APPLY 3
ILO 4.2 Construct an inverted index and execute AND/OR/NOT queries by merging postings lists. APPLY 3
ILO 4.3 Optimise conjunctive queries through term ordering and skip pointers. ANALYSE 3
ILO 4.4 Apply wildcard, edit distance, k gram and Soundex techniques for tolerant retrieval. APPLY 3
ILO 4.5 Compare biword and positional indexes for phrase and proximity queries. ANALYSE 3

3. The Boolean retrieval model

One of the oldest and simplest retrieval models. Queries are Boolean expressions over terms using AND, OR, NOT:

CAESAR AND BRUTUS AND NOT CALPURNIA
  • A document either matches or does not: exact matching.
  • The basic model produces a set, not a ranking.

Why not just grep?

Scanning Shakespeare's plays for Brutus, then Caesar, then removing Calpurnia is brute force: it is slow on large collections, line oriented rather than document oriented, handles NOT poorly, and cannot support advanced operators such as proximity. We need to do the work once, in advance: build an index.

4. First representation: the incidence matrix

Term Antony & Cleopatra Julius Caesar The Tempest Hamlet Othello Macbeth
Brutus 1 1 0 1 0 0
Caesar 1 1 0 1 1 1
Calpurnia 0 1 0 0 0 0

Each term is a bit vector over documents. The query becomes bitwise logic:

\[ \underbrace{110100}_{\text{Brutus}} \;\wedge\; \underbrace{110111}_{\text{Caesar}} \;\wedge\; \underbrace{101111}_{\neg\,\text{Calpurnia}} \;=\; 100100 \]

→ Antony & Cleopatra and Hamlet match.

Why the matrix does not scale

With \(N = 10^6\) documents and \(M = 500{,}000\) distinct terms the matrix has \(5 \times 10^{11}\) cells. With ~1,000 tokens per document there are at most \(10^9\) ones: over 99.8 % of entries are 0. Store only the ones.

5. The inverted index

For each term \(t\), store the sorted list of documents that contain \(t\).

flowchart LR
    subgraph DICT["Dictionary (in memory)"]
      B["Brutus · df=3"]
      C["Caesar · df=5"]
      P["Calpurnia · df=1"]
    end
    subgraph POST["Postings lists (sorted docIDs)"]
      BL["1 → 3 → 4"]
      CL["1 → 2 → 3 → 4 → 6"]
      PL["2"]
    end
    B --> BL
    C --> CL
    P --> PL

It is inverted because it reverses the natural view: not "which terms are in document 1?" but "in which documents does term t appear?"

Term Meaning
Dictionary The set of indexed terms (vocabulary) with metadata such as document frequency \(df\)
Postings list The list of docIDs for one term
Inverted index Dictionary + all postings lists

The same structure as a class diagram, the way you will implement it in the project:

classDiagram
    class InvertedIndex {
        dict dictionary
        add_document(doc_id, tokens)
        postings(term) list
        and_query(terms) list
    }
    class DictEntry {
        str term
        int df
        PostingsList postings
    }
    class PostingsList {
        list~int~ doc_ids
        list~int~ skips
        intersect(other) PostingsList
    }
    class Posting {
        int doc_id
        int tf
        list~int~ positions
    }
    InvertedIndex "1" *-- "many" DictEntry
    DictEntry "1" *-- "1" PostingsList
    PostingsList "1" *-- "many" Posting

Positions and term frequencies are optional here; we need positions for phrase queries (Section 10) and tf for ranking (Unit 7).

Building it

flowchart TB
    subgraph R1["Linguistic steps"]
      direction LR
      A["Collect<br/>documents"] --> B["Tokenise"] --> C["Normalise"]
    end
    subgraph R2["Indexing steps"]
      direction LR
      D["Emit (term, docID)<br/>pairs"] --> E["Sort by term,<br/>then docID"] --> F["Group into<br/>dictionary + postings"]
    end
    R1 --> R2

Worked example

D1: Brutus killed Caesar · D2: Calpurnia loved Caesar · D3: Brutus met Calpurnia

Term Postings
brutus 1, 3
caesar 1, 2
calpurnia 2, 3
killed 1
loved 2
met 3

6. Query processing

AND: intersecting postings lists

BRUTUS AND CALPURNIA with Brutus → [1, 3, 5, 8] and Calpurnia → [3, 6, 8]:

Step Compare Action
1 1 vs 3 1 < 3 → advance Brutus
2 3 vs 3 match → keep 3, advance both
3 5 vs 6 5 < 6 → advance Brutus
4 8 vs 6 6 < 8 → advance Calpurnia
5 8 vs 8 match → keep 8

Result: [3, 8]. Because both lists are sorted, the merge takes \(O(x + y)\) time for lists of length \(x\) and \(y\).

from collections import defaultdict

def build_index(docs: dict[int, str]) -> dict[str, list[int]]:
    index = defaultdict(set)
    for doc_id, text in docs.items():
        for term in text.lower().split():
            index[term].add(doc_id)
    return {t: sorted(ids) for t, ids in sorted(index.items())}

def intersect(p1: list[int], p2: list[int]) -> list[int]:
    answer, i, j = [], 0, 0
    while i < len(p1) and j < len(p2):
        if p1[i] == p2[j]:
            answer.append(p1[i]); i += 1; j += 1
        elif p1[i] < p2[j]:
            i += 1
        else:
            j += 1
    return answer

def and_query(index, *terms):
    lists = sorted((index.get(t, []) for t in terms), key=len)   # shortest list first
    result = lists[0]
    for p in lists[1:]:
        result = intersect(result, p)
    return result

print(intersect([1, 3, 5, 8], [3, 6, 8]))    # [3, 8]

The merge is a tiny state machine with two pointers:

stateDiagram-v2
    [*] --> Compare
    Compare --> Match : p1[i] == p2[j]
    Compare --> AdvanceFirst : p1[i] < p2[j]
    Compare --> AdvanceSecond : p1[i] > p2[j]
    Match --> Compare : keep docID, i++, j++
    AdvanceFirst --> Compare : i++
    AdvanceSecond --> Compare : j++
    Compare --> [*] : one list exhausted

Each step advances at least one pointer, so the loop runs at most \(x + y\) times.

OR and NOT

Operator Operation Example Effect
AND intersection \([1,3,5] \cap [3,5,7] = [3,5]\) narrows
OR union \([1,3,5] \cup [3,5,7] = [1,3,5,7]\) broadens
NOT complement / difference \(D \setminus [3,5]\) excludes

x AND NOT y is best computed as a merge that skips the docs in \(y\), never by materialising the (huge) complement.

Query optimisation: shortest list first

For BRUTUS AND CALPURNIA AND CAESAR with Brutus → [1, 2, 3, 4, 7, 9], Caesar → [2, 4], Calpurnia → [2, 4, 6]: process in order of increasing document frequency: Caesar ∩ Calpurnia ∩ Brutus. The intermediate result can never be longer than the shortest list, so every later merge is cheap. The dictionary stores \(df\) for exactly this reason.

Skip pointers

For data AND science with data → [1, 3, 5, 7, 9, 11, 13, 15] and science → [7, 15], a plain merge walks through 1, 3, 5 … one by one. Skip pointers let the algorithm jump over runs that cannot match.

flowchart LR
    a1["1"] --> a3["3"] --> a5["5"] --> a7["7"] --> a9["9"] --> a11["11"] --> a13["13"] --> a15["15"]
    a1 -.->|"skip"| a7
    a7 -.->|"skip"| a13

Comparing with 7: follow the skip 1 ⇒ 7 directly. A common heuristic is \(\sqrt{L}\) evenly spaced skips for a list of length \(L\); more skips mean shorter jumps but more comparisons and storage. Skips help most for AND queries on long, static lists.

Why \(\sqrt{L}\)? With \(k\) evenly spaced skips, a lookup follows at most \(k\) skip pointers and then walks at most \(L/k\) entries inside one segment:

\[ \text{cost}(k) \approx k + \frac{L}{k}, \qquad \frac{d\,\text{cost}}{dk} = 1 - \frac{L}{k^{2}} = 0 \;\Rightarrow\; k^{*} = \sqrt{L}, \qquad \text{cost}(k^{*}) = 2\sqrt{L} \]

For a postings list of \(L = 10{,}000\) entries: 100 skips and about 200 steps instead of up to 10,000.

7. Boolean retrieval in practice

Boolean search was the primary commercial retrieval model for decades and remains central in legal search, patent search, digital libraries, enterprise and email search (think Spotlight). Professionals value it because it is precise, transparent and controllable, the user knows exactly what a query means.

Case: Westlaw

Westlaw, a legal research service operating since 1975, serves lawyers, courts and researchers. Its query language adds operators beyond AND/OR/NOT:

  • Proximity: drunk /3 driver: the words must occur within 3 words of each other.
  • Root expansion: employ! → employee, employer, employment.
Strengths Limitations
Simple, interpretable No ranking in the basic model
Exact control over query meaning Exact matching can be too strict ("feast or famine")
Efficient with inverted indexes Users must formulate good queries
Valued in expert domains No partial relevance

8. The dictionary data structure

The dictionary stores each term with its document frequency and a pointer to its postings list.

Term df Postings
analysis 2 → [D2, D3]
data 2 → [D1, D2]
mining 1 → [D2]
science 2 → [D1, D3]
Structure Exact lookup Prefix lookup da* Notes
Hash table \(O(1)\) not supported no ordering; rehashing when vocabulary grows
B tree / sorted tree \(O(\log M)\) supported (data, database, date) balanced, disk friendly

9. Tolerant retrieval

Users are not exact. They type partial words (comput*), misspellings (recieve), spelling variants (colour / color) and phonetic variants (nite / night).

Wildcard queries

Query Matches Supported by
mon* money, month, monitor B tree over terms (prefix range)
*mon common, salmon B tree over reversed terms
m*nchen münchen, … permuterm index or k gram index + post filter

Wildcards are more expensive than exact lookups: gen* universit* expands to Geneva university, Genève université, general universities, …, which means many Boolean subqueries. And users would overuse them (pyth* theo* instead of pythagoras theorem). That is why web search engines prefer query suggestions / autocomplete.

Edit (Levenshtein) distance

The minimum number of insertions, deletions and substitutions to turn one string into another: dog → do = 1, cat → cut = 1, cat → act = 2, informaton → information = 1.

It is computed by dynamic programming:

\[ D[i][j] = \min\big(D[i-1][j] + 1,\; D[i][j-1] + 1,\; D[i-1][j-1] + [a_i \neq b_j]\big) \]

Worked example: cat → act

ε a c t
ε 0 1 2 3
c 1 1 1 2
a 2 1 2 2
t 3 2 2 2

The bottom right cell gives the distance: 2.

def levenshtein(a: str, b: str) -> int:
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]

print(levenshtein("cat", "act"), levenshtein("informaton", "information"))   # 2 1

k gram index for candidate generation

Computing edit distance against a 400,000 term vocabulary for every query is too slow. A k gram index narrows the candidates first.

flowchart TB
    subgraph R1["Generate candidates"]
      direction LR
      Q["Query term<br/>'bordroom'"] --> K["2 grams<br/>bo or rd dr ro oo om"] --> L["Look up each 2 gram<br/>in the k gram index"]
    end
    subgraph R2["Choose the best"]
      direction LR
      C["Candidates sharing<br/>many 2 grams<br/>boardroom, border, ..."] --> E["Rank by edit distance<br/>or Jaccard overlap"] --> S["Suggest:<br/>boardroom"]
    end
    R1 --> R2

bordroom and boardroom share 6 of their 9 distinct bigrams, a Jaccard overlap of \(6/9 \approx 0.67\): a strong candidate, confirmed by edit distance 1.

Soundex: phonetic matching

Soundex encodes a name as its first letter plus three digits for consonant groups (b, f, p, v → 1; c, g, j, k, q, s, x, z → 2; d, t → 3; l → 4; m, n → 5; r → 6), dropping vowels and repeats: HERMAN → H655, HERMANN → H655. This solves Herr Aydın's landlord problem. Soundex works well for names in noisy databases but poorly for general text.

10. Phrase and proximity queries

"stanford university" should match "Stanford University is great" but not "Stanford is a top university", although both contain stanford AND university. We need word order.

Index every pair of consecutive words as one term.

new york university is great → new york, york university, university is, is great

"new york" is a single lookup. Longer phrases are split into overlapping biwords ("new york university" → new york AND york university), which can produce false positives, and the dictionary grows considerably.

Store, for each document, the positions of the term.

stanford   → D1: [1]   D2: [1]
university → D1: [5]   D2: [2]

For "stanford university" we need positions \(p\) and \(p+1\): D1 has (1, 5) → no; D2 has (1, 2) → match. The same merge with \(|p_1 - p_2| \le k\) answers proximity queries like drunk /3 driver.

Biword index Positional index
Stores consecutive word pairs term positions per document
Best for short, frequent phrases arbitrary phrases and proximity
Cost large dictionary 2 to 4× larger postings

In practice, systems combine them: biwords for very common phrases, positional postings for everything else.

11. Classwork

Build and query (30 min)

Documents: D1 "new rent control rules for Berlin", D2 "rent control ends commercial leases", D3 "Berlin bike lanes and rent", D4 "new bike rules".

  1. Build the inverted index (lower case, no stemming).
  2. Evaluate rent AND berlin, bike OR control, rent AND NOT commercial.
  3. In which order would you process new AND rules AND rent? Why?
  4. Build positional postings for rent and control and answer "rent control".
Solutions
  1. rent → [1,2,3], berlin → [1,3], bike → [3,4], control → [1,2], new → [1,4], rules → [1,4], commercial → [2], …
  2. [1,3] · [1,2,3,4] · [1,3]
  3. new, rules (df 2) before rent (df 3): start with the shortest lists.
  4. rent → D1:[2], D2:[1], D3:[5]; control → D1:[3], D2:[2] → consecutive in D1 and D2 → [1, 2].

12. Check your understanding

Why must postings lists be sorted by docID?

Sorting enables the linear time merge for AND/OR/NOT and makes gap based compression possible (Unit 6).

Why does a hash table dictionary not support mon*?

Hashing destroys ordering; terms sharing a prefix land in unrelated buckets, so you cannot enumerate all terms in the range mon…mop.

Why do web search engines avoid full wildcard support?

A wildcard expands into many terms, and combinations of several wildcards multiply the number of Boolean subqueries. Autocomplete achieves the user's goal (less typing) at a fraction of the cost.

13. Key takeaways

  • The inverted index (dictionary + sorted postings) makes Boolean retrieval fast; the incidence matrix explains the idea but does not scale.
  • AND = merge of sorted lists; process shortest lists first; skip pointers avoid useless comparisons.
  • Tolerant retrieval: B trees for prefixes, k grams + edit distance for spelling, Soundex for names.
  • Positional indexes answer phrase and proximity queries.
  • Boolean retrieval is not outdated: it is the right tool when users need precision and control.

Project core requirement: "Implement retrieval: Boolean Retrieval OR Vector Space Model OR BM25." If you choose Boolean retrieval, implement your own inverted index and merge (not a library call), and demonstrate at least one tolerant or phrase feature.

Further reading

  • Manning, Raghavan & Schütze, Introduction to IR, ch. 1 to 3.
  • Croft, Metzler & Strohman, Search Engines: Information Retrieval in Practice, ch. 5.