Comprehensive Information Retrieval: Indexing, Scoring, Evaluation, and Machine Learning

Foundations of Information Retrieval and the Inverted Index

  • Definition and Scope of Information Retrieval (IR):
    • Information Retrieval is the discipline of finding material—typically unstructured text documents—that satisfies an information need from within large collections stored on computer systems.
    • IR spans diverse operational scales:
    • Web Search: Querying across billions of documents hosted on millions of computers, addressing massive scale, hyperlink analysis, and adversarial content (spam).
    • Personal Information Retrieval: Desktop search, operating system search utilities (e.g., Apple Spotlight), and personal email searching.
    • Enterprise, Institutional, and Domain-Specific Search: Searching corporate intranets, legal databases, patent repositories, and biomedical literature collections.
    • IR sits at the intersection of three computing disciplines:

The Sweetspot of Information Retrieval, Distributed Systems, and Language Technology

  • Data Types in Information Retrieval:

    • Unstructured Data: Free text lacking predefined conceptual models or database schemas for computational parsing.
    • Structured Data: Information stored with formal schemas, such as relational databases with explicit entity types, attributes, and relational keys.
    • Semistructured Data: Text coupled with structured metadata or structural markup, such as document zones (title, abstract, body), field tags (author, publication date), and HTML/XML elements.
  • Fundamental Tasks in Document Organization:

    • Ad Hoc Retrieval: The standard IR task where an incoming query representing an arbitrary user information need is evaluated against a static document collection to return relevant documents.
    • Clustering: An unsupervised machine learning process that automatically groups documents into thematic clusters based on pairwise textual similarity without predefined categories.
    • Classification: A supervised machine learning process that assigns documents to predefined thematic classes or categories based on labeled training data.
  • Term-Document Incidence Matrix:

    • The conceptual precursor to modern indexing is a binary incidence matrix in which rows correspond to vocabulary terms and columns correspond to documents.
    • Each cell contains a binary bit: 11 indicates that the term occurs in the document, and 00 indicates that the term does not occur.
    • Answering a Boolean query involves retrieving the bit vectors for each term and applying bitwise logic:
    • Example: Evaluating the query Brutus∧Caesar∧¬Calpurnia\text{Brutus} \land \text{Caesar} \land \neg \text{Calpurnia} involves bitwise AND operations between the row vector of Brutus\text{Brutus}, the row vector of Caesar\text{Caesar}, and the bitwise complement of the row vector of Calpurnia\text{Calpurnia}.
    • Infeasibility at Scale:
    • For a collection of N=106N = 10^6 (1 million1\text{ million}) documents and a vocabulary of M=500,000M = 500{,}000 terms, a full incidence matrix requires 500,000×106=5×1011500{,}000 \times 10^6 = 5 \times 10^{11} bits (≈500 GB\approx 500\text{ GB}).
    • Assuming an average of 1,0001{,}000 words per document with 6 bytes6\text{ bytes} per word, the raw text collection requires 6 GB6\text{ GB}. The incidence matrix would be roughly 80×80\times larger than the raw text.
    • The matrix is extremely sparse: since at most 10910^9 term occurrences exist across the collection, over 99.8%99.8\% of the matrix cells are zeroes. Modern IR records only positive occurrences (1s1\text{s}).
  • The Inverted Index Architecture:

    • The standard data structure in IR is the inverted index, which maps each vocabulary term to a postings list of documents in which the term appears.

Structure of an Inverted Index: Dictionary and Postings lists

  • Core Components:

    • Dictionary (Lexicon/Vocabulary): The set of all unique terms extracted from the collection, sorted alphabetically. Each dictionary entry stores the term string, its document frequency (dfdf), and a memory pointer to its postings list.
    • Postings List: A list of document identifiers (docIDs) where the term occurs. Each entry in the list is called a posting.
    • DocID: A unique integer identifier assigned sequentially to each document in the collection.
  • Storage Considerations:

    • In secondary storage (disk), postings lists are written as contiguous blocks of integers to allow fast sequential streaming reads without random disk seeks.

    • In primary memory (RAM), postings lists utilize dynamic data structures such as singly linked lists or variable-length arrays (e.g., ArrayList).

    • Inverted Index Construction Pipeline:

Inverted Index Construction Pipeline

  • Step 1: Document Ingestion: Collecting raw byte streams, detecting file formats (PDF, HTML, DOCX), extracting raw text by stripping markup, identifying character encodings (e.g., UTF-8, CP1252), and identifying document language.
  • Step 2: Tokenization: Segmenting continuous text into linguistic tokens, resolving punctuation, hyphens, and contractions.
  • Step 3: Linguistic Preprocessing: Normalizing tokens into index terms via case folding, accent removal, equivalence class mapping, and stemming/lemmatization.
  • Step 4: Indexing (Sort and Group):
    • Emitting intermediate (term, docID) pairs for every token occurrence in the collection.
    • Sorting the full sequence of pairs primarily by term alphabetically, and secondarily by docID numerically.
    • Merging multiple occurrences of the same term within the same document and splitting into dictionary entries and sorted postings lists.

Step-by-step Transformation of Tokens into Postings Lists

  • Boolean Query Processing and Intersection Algorithm:
    • Evaluating a conjunctive query (Term1∧Term2\text{Term}_1 \land \text{Term}_2) requires finding the set intersection of two sorted postings lists p1p_1 and p2p_2.
    • The Two-Pointer Linear Merge Algorithm:
    • Maintain two pointers initialized at the start of lists p1p_1 and p2p_2.
    • While neither pointer has reached the end of its respective list:
      • If docID(p1)=docID(p2)\text{docID}(p_1) = \text{docID}(p_2), append the docID to the result list and advance both pointers.
      • Else if docID(p1)<docID(p2)\text{docID}(p_1) < \text{docID}(p_2), advance pointer p1p_1.
      • Else, advance pointer p2p_2.
    • Time complexity is linear in the sum of list lengths: O(m+n)\mathcal{O}(m + n), where m=∣p1∣m = |p_1| and n=∣p2∣n = |p_2|.

Intersection Algorithm Pseudocode for Two Postings Lists

  • Boolean Query Optimization:
    • Conjunctive Queries: For queries with three or more terms (t1∧t2∧⋯∧tkt_1 \land t_2 \land \dots \land t_k), intersection order dictates computational efficiency.
    • The size of the intersection of two sets cannot exceed the size of the smaller set: ∣S1∩S2∣≤min⁡(∣S1∣,∣S2∣)|S_1 \cap S_2| \le \min(|S_1|, |S_2|).
    • Optimal strategy: Sort query terms in ascending order of their document frequency (dfdf) and evaluate intersections pairwise from smallest to largest. This keeps intermediate postings lists as small as possible.
    • Example: Query Antony∧Brutus∧Calpurnia\text{Antony} \land \text{Brutus} \land \text{Calpurnia} with df(Antony)=500df(\text{Antony}) = 500, df(Brutus)=1000df(\text{Brutus}) = 1000, and df(Calpurnia)=50df(\text{Calpurnia}) = 50. Intersect Calpurnia\text{Calpurnia} with Antony\text{Antony} first (≤50\le 50 candidate matches), then intersect the resulting sublist with Brutus\text{Brutus}. Starting with Brutus\text{Brutus} and Antony\text{Antony} would require scanning up to 15001500 elements unnecessarily.
    • Arbitrary Boolean Expressions:
    • For expressions involving disjunctions, such as (m1∨m2)∧(i1∨i2)∧(k1∨k2)(m_1 \lor m_2) \land (i_1 \lor i_2) \land (k_1 \lor k_2), estimate the size of each OR clause as the sum of its constituent document frequencies: df(A∨B)≈df(A)+df(B)df(A \lor B) \approx df(A) + df(B).
    • Evaluate the OR clauses internally, then intersect the resulting sets in increasing order of their estimated sizes.

Term Vocabularies, Preprocessing, and Tolerant Retrieval

  • Linguistic Normalization and Token Handling:

    • Case Folding: Mapping all alphabetic characters to lowercase (e.g., Romans→romans\text{Romans} \to \text{romans}). Exceptions occur in specialized search (e.g., distinguishing Bush\text{Bush} the surname from bush\text{bush} the plant, or CAT\text{CAT} the gene sequence/PET scanner from cat\text{cat} the animal).
    • Punctuation and Hyphenation: Stripping periods in abbreviations (e.g., U.S.A.→usa\text{U.S.A.} \to \text{usa}), deciding whether hyphenated terms (e.g., state-of-the-art\text{state-of-the-art}) should be preserved, split into separate tokens, or indexed in both forms.
    • Equivalence Classes vs. Query Expansion:
    • Reduction (Equivalence Classes): Mapping related forms to a single canonical term at indexing time (e.g., automobile→car\text{automobile} \to \text{car}). Increases recall and reduces index footprint, but permanently discards semantic distinctions and requires full index reconstruction if mapping rules change.
    • Expansion (Query Expansion): Preserving unique terms at index time and expanding query strings at search time (e.g., converting car\text{car} to car∨automobile\text{car} \lor \text{automobile}). Flexible and easily updated, but increases query processing latency.
  • Stemming versus Lemmatization:

    • Stemming: Heuristic, rule-based chopping of derivational and inflectional affixes without morphological analysis. Fast and language-specific, but can produce non-linguistic stems.
    • Porter's Algorithm: The standard stemming algorithm for English, applying a sequence of conditional suffix-stripping rules (e.g., studies→studi\text{studies} \to \text{studi}, playing→play\text{playing} \to \text{play}, authorization→author\text{authorization} \to \text{author}).
    • Lemmatization: Full morphological analysis utilizing complete grammatical dictionaries to resolve words to their true base lemma (e.g., am, are, is→be\text{am, are, is} \to \text{be}, mice→mouse\text{mice} \to \text{mouse}, ran→run\text{ran} \to \text{run}). More computationally intensive, but avoids incorrect conflation.
  • Stop Word Elimination vs. Retention:

    • Stop words are high-frequency function words (e.g., the, of, and, to, a\text{the, of, and, to, a}) that carry minimal semantic selectivity.
    • Traditional systems discarded stop words using fixed stop lists to save space. Modern Web search engines retain stop words because they are critical for phrase queries (e.g., \text{\"to be or not to be\"}) and proximity operators.
  • Phrase Queries:

    • Standard inverted indices cannot verify word adjacencies. Two primary approaches solve this problem:
    • Biword Indexes:
    • Every pair of consecutive tokens in a document is indexed as a single distinct term (e.g., \text{\"Friends, Romans, Countrymen\"} yields the biwords \text{\"friends romans\"} and \text{\"romans countrymen\"}).
    • Two-word phrase searches execute as a single atomic dictionary lookup.
    • Phrases with N>2N > 2 words decompose into multiple biword lookups: \text{\"stanford university palo alto\"} \to \text{\"stanford university\"} \land \text{\"university palo\"} \land \text{\"palo alto\"}.
    • Drawbacks: Index size explodes dramatically (O(∣V∣2)\mathcal{O}(|V|^2) potential vocabulary space), and queries of length >2> 2 can produce false-positive matches where biwords occur disjointly.
    • Positional Indexes:
    • Positional indices record document positions alongside each docID in the postings list:       ⟨term,df;doc1:[pos1,pos2,… ];doc2:[pos1,pos2,… ];… ⟩\langle \text{term}, df; \text{doc}_1: [pos_1, pos_2, \dots]; \text{doc}_2: [pos_1, pos_2, \dots]; \dots \rangle
    • Positional Merge Algorithm: Traverse postings lists simultaneously. For matching docIDs, compare position arrays using two pointers to check if pos2−pos1=1\text{pos}_2 - \text{pos}_1 = 1 (for exact phrases) or ∣pos2−pos1∣≤k|\text{pos}_2 - \text{pos}_1| \le k (for proximity operator /k/k).
    • Storage Overhead: A positional index is typically 2× to 4×2\times \text{ to } 4\times larger than a non-positional index, but supports arbitrary phrase and proximity matching.
    • Hybrid Strategy: Combine positional indexing with precomputed biwords for extremely frequent phrase idioms (e.g., \text{\"Michael Jackson\"}) to avoid runtime positional merges.
  • Skip Lists / Skip Pointers:

    • Mechanism to accelerate postings list intersection by skipping over non-matching docIDs without scanning every element.

Skip List Traversal with Forward Skip Pointers

  • Operational Logic: When merging lists p1p_1 and p2p_2, if docID(p1)<docID(p2)\text{docID}(p_1) < \text{docID}(p_2) and p1p_1 has a skip pointer pointing to p1′p_1' such that docID(p1′)≤docID(p2)\text{docID}(p_1') \le \text{docID}(p_2), advance pointer p1p_1 directly to p1′p_1'.

  • Skip Placement Heuristic: For a postings list of length LL, place L\sqrt{L} evenly spaced skip pointers, each skipping L\sqrt{L} elements. This balances the frequency of skip opportunities with the cost of inspecting skip targets.

  • Limitations: Skip pointers only accelerate conjunctive (AND) queries; they do not assist disjunctive (OR) queries. They also require static, precomputed postings lists; dynamic insertions break skip offsets.

    • Tolerant Retrieval and Wildcard Queries:
  • Trailing Wildcard Queries (mon*\text{mon*}): Directly resolved using a standard lexicographically sorted dictionary. Locate the term matching the prefix via binary search and read consecutively until the prefix changes.

  • General Wildcard Queries (*mon\text{*mon}, fi*er\text{fi*er}):

    • Permuterm Index:
      • For each term TT, append an end-of-string symbol $ and generate all cyclic shifts (rotations).
      • Store all rotations in a sorted lexicon pointing to the original term.
      • Transform wildcard queries into equivalent prefix queries ending in *:

Permuterm Vocabulary Cyclic Rotations and Query Transformations

  * *Drawback:* The dictionary vocabulary explodes, expanding roughly 4×4\times in size for typical English text.
* **kk-gram Indexes:**
  * Deconstruct terms into overlapping character sequences of length kk padded with `$`. For example, the 3-grams of $\text{castle}$ are `{$ca, cas, ast, stl, tle, le$}`.
  * Build an auxiliary inverted index mapping each kk-gram to all dictionary terms containing it.
  * Process wildcard query re*ve\text{re*ve} by intersecting postings for `re‘and‘vere` and `ve` to yield candidate terms (e.g., relive, remove, retrieve\text{relive, remove, retrieve}).
  * Candidate terms must undergo **post-filtering** against the original wildcard pattern because kk-gram intersection can generate false positives (e.g., query red*\text{red*} yields `$re` and `red`, which matches $\text{retired}$ because it starts with `re` and contains `red`).
  • Lexicon Data Structures:
    • Hash Tables: Average lookup time is O(m)\mathcal{O}(m) (where mm is term length), but cannot support prefix lookups, range queries, or nearest-neighbor searches.
    • Tries (Prefix Trees): Character-labeled trees where paths from the root spell word prefixes. Lookup time is strictly O(m)\mathcal{O}(m), independent of vocabulary size NN, but node pointers consume significant memory.

Trie Data Structure for Dictionary Terms

  • Suffix Arrays: An array containing the starting integer indices of all suffixes of a string, sorted lexicographically.

Suffix Array Construction and Sorting for String banana$

  • Construction complexity is O(n2log⁡(n))\mathcal{O}(n^2 \log(n)) using naive sorting, or O(nlog⁡(n))\mathcal{O}(n \log(n)) with optimized suffix sorting algorithms.
  • Search for a pattern of length mm in text of length nn executes via binary search in O(mlog⁡(n))\mathcal{O}(m \log(n)) time.
  • Generalized Suffix Arrays: Extend suffix arrays across multiple documents by appending distinct document terminators, enabling phrase and substring searches across entire corpora:

Generalized Suffix Array Across Multiple Document Texts

  • Spelling Correction:
    • Levenshtein Edit Distance: The minimal number of single-character operations (insertions, deletions, substitutions) required to transform string s1s_1 into string s2s_2.
    • Damerau-Levenshtein Distance: Extends Levenshtein distance by including character transpositions of adjacent characters (ab↔ba\text{ab} \leftrightarrow \text{ba}) as a unit-cost primitive operation.
    • Dynamic Programming Computation:
    • Initialize matrix D[0…∣s1∣,0…∣s2∣]D[0 \dots |s_1|, 0 \dots |s_2|] where D[i,0]=iD[i, 0] = i and D[0,j]=jD[0, j] = j.
    • Recurrence relation:       D[i,j]=min⁡{D[i−1,j]+1(Deletion)D[i,j−1]+1(Insertion)D[i−1,j−1]+I(s1[i]≠s2[j])(Substitution)D[i−2,j−2]+1(Transposition, if s1[i]=s2[j−1]∧s1[i−1]=s2[j])D[i, j] = \min \begin{cases} D[i-1, j] + 1 & \text{(Deletion)} \\ D[i, j-1] + 1 & \text{(Insertion)} \\ D[i-1, j-1] + \mathbb{I}(s_1[i] \neq s_2[j]) & \text{(Substitution)} \\ D[i-2, j-2] + 1 & \text{(Transposition, if } s_1[i]=s_2[j-1] \land s_1[i-1]=s_2[j]\text{)} \end{cases}

Edit Table Dynamic Programming Grid Computing Distance between RELEVANT and ELEPHANT

  • Fast Dictionary Traversal via Trie Pruning (Shang & Merrett):
    • Instead of comparing the input query against every vocabulary term individually, store the dictionary in a trie.
    • Traverse the trie while dynamically constructing one column of the DP edit table per node.
    • Since words sharing a prefix share identical columns, early computations are reused across all descendants.
    • Branch Pruning: Define a maximum allowable edit threshold kk. If all values in the newly computed column exceed kk, prune that entire branch, skipping thousands of candidate words.
  • Aho-Corasick Multi-Pattern Matching Algorithm:
    • Constructs a finite-state machine (a trie augmented with failure transitions) from a set of target keywords to search a text stream in a single pass.
    • Failure Links (Suffix Links): Fallback pointers followed when the current character fails to match any trie child. The failure link points to the node representing the longest proper suffix of the current prefix that exists as a prefix in the trie.
    • Processing complexity is linear with respect to the input text length plus the number of output matches, completely independent of the number of dictionary keywords.
  • Phonetic Hashing (Soundex):
    • Maps phonetically similar words to identical hash buckets to capture acoustic misspellings (common in personal names).
    • Algorithm steps:
    1. Retain the initial character of the string.
    2. Map subsequent letters to digits: A, E, I, O, U, H, W, Y →0\to 0; B, F, P, V →1\to 1; C, G, J, K, Q, S, X, Z →2\to 2; D, T →3\to 3; L →4\to 4; M, N →5\to 5; R →6\to 6.
    3. Collapse contiguous duplicate digits into a single digit.
    4. Eliminate all zeroes.
    5. Pad with trailing zeroes or truncate to produce exactly one letter followed by three digits (e.g., Hermann→H655\text{Hermann} \to \text{H655}, Herman→H655\text{Herman} \to \text{H655}).

Index Construction and External Sorting

  • Scalability Bottlenecks in Index Construction:

    • Standard memory-based indexing fails when collections exceed available RAM.
    • Utilizing raw disk storage as virtual memory for in-place sorting fails because random disk seeks take milliseconds, making standard sorting algorithms intractable at scale.
    • Secondary storage indexing requires external sorting algorithms that process contiguous data blocks sequentially.
  • Blocked Sort-Based Indexing (BSBI):

    • Splits the collection into blocks of documents that fit in RAM.
    • Algorithm Steps:
    1. Parse documents into intermediate (termID, docID) pairs until the memory block is exhausted.
    2. Sort intermediate pairs in memory by termID, then by docID.
    3. Convert sorted pairs into intermediate postings lists and write the block run to disk.
    4. Repeat until all documents are processed.
    5. Perform a multi-way external merge of all sorted disk runs into a unified inverted index.
    • Time complexity is O(Tlog⁡(T))\mathcal{O}(T \log(T)), where TT is the total number of postings in the collection.
    • Bottleneck: BSBI requires a global in-memory dictionary mapping term strings to unique integer termIDs throughout the entire indexing pipeline. For large collections, this mapping dictionary exceeds available RAM.
  • Single-Pass In-Memory Indexing (SPIMI):

    • Eliminates the global termID mapping bottleneck by managing dynamic, block-local string dictionaries.
    • Algorithm Steps:
    1. Initialize a new block with an empty hash-table dictionary.
    2. For each incoming token, look up its raw string in the local hash table. If missing, allocate a new postings list. Append the docID directly to the term's dynamic postings list.
    3. When RAM is exhausted, sort the block's local vocabulary strings alphabetically.
    4. Write the block-level inverted index directly to disk.
    5. Repeat for subsequent blocks using fresh, independent dictionaries.
    6. Execute an external multi-way merge across all block files to produce the final index.
    • Advantages: Operates in linear time O(T)\mathcal{O}(T), requires zero global term-to-termID coordination, and maximizes RAM utilization by constructing postings lists directly.
  • Distributed Indexing via MapReduce:

    • Web-scale indexing distributes processing across compute clusters using the MapReduce programming model.

Distributed Indexing Architecture with Map and Reduce Phases

  • Splits: The input corpus is partitioned into logical document chunks called splits.

  • Map Phase (Parsers): Worker nodes run map functions on assigned splits, outputting key-value streams of (term, docID) pairs and partitioning them into jj segment files based on term hash or alphabetical ranges (e.g., a-f, g-p, q-z).

  • Shuffle/Sort Phase: Collects and groups intermediate data across nodes, routing all pairs for a specific term range to a designated reducer.

  • Reduce Phase (Inverters): Reducer nodes receive sorted sequences (term, [docID, docID, ...]) and write final, contiguous postings lists to distributed storage.

  • Index Partitioning Architectures:

    • Term-Partitioned: Each machine hosts full postings lists for a subset of terms. Queries require routing to specific nodes holding the query terms.

    • Document-Partitioned: Each machine hosts a fully functional inverted index over a disjoint subset of documents. Queries broadcast to all nodes simultaneously, and results are merged. This is the industry standard for fault tolerance and query concurrency.

    • Dynamic Indexing Strategies:

  • Collections undergo continuous document insertions, deletions, and updates.

  • Auxiliary and Main Index Scheme: Maintain a large static main index on disk and accumulate new postings in a dynamic in-memory auxiliary index. Queries query both indices and compute set unions. Document deletions are tracked in an invalidation bit vector to filter out dead documents.

  • Merge Bottleneck: Periodically merging an auxiliary index of size nn into a main index of size TT rewrites the entire main index, yielding a total re-indexing complexity of O(T2/n)\mathcal{O}(T^2 / n).

  • Logarithmic Merge:

    • Decomposes disk storage into a logarithmic hierarchy of indices I0,I1,I2,…I_0, I_1, I_2, \dots, where index IkI_k has capacity 2k⋅n2^k \cdot n.
    • Postings enter in-memory index I0I_0. When I0I_0 reaches capacity nn, it flushes to disk. If I1I_1 is unoccupied, it becomes I1I_1; if occupied, I0I_0 and I1I_1 merge into a newly allocated I2I_2, propagating upward.
    • Reduces total construction merge time to O(Tlog⁡(T/n))\mathcal{O}(T \log(T/n)), at the cost of expanding search across O(log⁡(T/n))\mathcal{O}(\log(T/n)) independent index files.

Index Compression and Statistical Properties of Text

  • Motivations for Index Compression:

    • Compressing the index yields three major systems benefits: saves disk storage, increases the fraction of the index that fits into fast main memory, and accelerates transfer speeds from secondary storage to memory (provided decompression algorithms are CPU-efficient).
    • Lossless vs. Lossy Compression: Lossless techniques preserve exact data representations (mandatory for inverted indices). Lossy techniques discard information to maximize space savings (e.g., stop word elimination, aggressive stemming, case folding).
  • Vocabulary Growth and Heaps' Law:

    • Heaps' Law models vocabulary growth as a power-law function of the total number of processed tokens:     M=kTbM = k T^b     Where MM is the vocabulary size, TT is the cumulative token count, and kk and bb are empirical parameters (30≤k≤10030 \le k \le 100 and b≈0.5b \approx 0.5).
    • In logarithmic space, Heaps' law forms a linear equation: log⁡(M)=log⁡(k)+blog⁡(T)\log(M) = \log(k) + b \log(T).
    • When b=0.5b = 0.5, M=kTM = k \sqrt{T}, meaning quadrupling the corpus size only doubles the unique vocabulary. Vocabulary growth never plateaus entirely because typographical errors, domain terms, and serial identifiers continuously introduce new words.
    • Worked Parameter Estimation:
    • Given measurements of M1=3,000M_1 = 3{,}000 terms at T1=10,000T_1 = 10{,}000 tokens, and M2=30,000M_2 = 30{,}000 terms at T2=1,000,000T_2 = 1{,}000{,}000 tokens:       b=log⁡(30,000)−log⁡(3,000)log⁡(1,000,000)−log⁡(10,000)=12=0.5b = \frac{\log(30{,}000) - \log(3{,}000)}{\log(1{,}000{,}000) - \log(10{,}000)} = \frac{1}{2} = 0.5k=M1T10.5=3,00010,000=3,000100=30k = \frac{M_1}{T_1^{0.5}} = \frac{3{,}000}{\sqrt{10{,}000}} = \frac{3{,}000}{100} = 30
    • Projecting to a Web collection of 2×10102 \times 10^{10} pages with an average of 200 tokens/page200\text{ tokens/page} (T=4×1012T = 4 \times 10^{12} total tokens):       M=30×4×1012=30×(2×106)=60,000,000 unique termsM = 30 \times \sqrt{4 \times 10^{12}} = 30 \times (2 \times 10^6) = 60{,}000{,}000\text{ unique terms}
  • Term Distribution and Zipf's Law:

    • Zipf's Law states that the frequency of the ii-th most frequent term in a collection (cficf_i) is inversely proportional to its frequency rank ii.     cfi∝1i  ⟹  cfi=Kicf_i \propto \frac{1}{i} \implies cf_i = \frac{K}{i}     Where KK is a normalization constant equal to the frequency of the most common word (cf1=Kcf_1 = K).

Zipf's Law Curve: Term Frequency versus Rank Order

  • Consequences: Text collections follow a severe Pareto power-law distribution. A tiny handful of function words dominate the token count (e.g., \text{\"the\"} accounts for ≈7%\approx 7\% of occurrences), while the vast majority of vocabulary items appear rarely (the long tail of hapax legomena).

    • Dictionary Compression Techniques:

Dictionary Compression Techniques: Fixed-Width, Dictionary-as-String, Blocking, and Front Coding

  • Fixed-Width Array: Allocates fixed field widths for each dictionary term entry: 20 bytes20\text{ bytes} for term string, 4 bytes4\text{ bytes} for dfdf, and 4 bytes4\text{ bytes} for postings pointer (28 bytes/term28\text{ bytes/term} total). Highly wasteful because the average English word is only ≈8 characters\approx 8\text{ characters}, leaving 12 bytes12\text{ bytes} empty per entry while truncating words exceeding 20 characters20\text{ characters}.
  • Dictionary-as-a-String: Concatenates all term strings into a single contiguous character array. Each dictionary entry keeps its 4 bytes4\text{ bytes} for dfdf and 4 bytes4\text{ bytes} for postings pointer, replaces the 20 bytes20\text{ bytes} term field with a 3 bytes3\text{ bytes} pointer into the string, and consumes an average of 8 bytes8\text{ bytes} of actual text (19 bytes/term19\text{ bytes/term} total). Reduces a 400,000400{,}000-term vocabulary from 11.2 MB11.2\text{ MB} to 7.6 MB7.6\text{ MB}.
  • Blocking: Groups terms into blocks of size kk and stores a string pointer only for the first word in each block. All terms within the block are preceded by a 1 byte1\text{ byte} length prefix.
    • For k=4k = 4, eliminates 3 string pointers (3×3 bytes=9 bytes3 \times 3\text{ bytes} = 9\text{ bytes} saved) at the cost of 4 length bytes, yielding a net savings of 5 bytes5\text{ bytes} per block (0.5 MB0.5\text{ MB} total for 100,000100{,}000 blocks), compressing the lexicon to 7.1 MB7.1\text{ MB}.
    • Tradeoff: Higher kk increases compression, but lookups require binary searching down to the block level followed by a linear scan through the kk terms in the block.

Binary Search Comparison Steps With and Without Blocking

  • Front Coding: Exploits alphabetical sorting where adjacent terms share extensive prefixes. The common prefix is stored once for the block, followed by suffixes with their corresponding character lengths (e.g., 8automata, 8automate, 9automatic, 10automation encodes as 8automat*a1◇e2◇ic3◇ion). Compresses the RCV1 dictionary down to 5.9 MB5.9\text{ MB}.

Front Coding String Prefix Compression

TechniqueRCV1 Dictionary Size
Fixed width (28 bytes/term28\text{ bytes/term})11.2 MB11.2\text{ MB}
Dictionary-as-String (19 bytes/term19\text{ bytes/term})7.6 MB7.6\text{ MB}
Blocking (k=4k = 4)7.1 MB7.1\text{ MB}
Blocking + Front Coding5.9 MB5.9\text{ MB}
  • Postings List Compression via Gap Encoding:

    • Postings lists account for the vast majority of index storage (>90%> 90\%). In a collection of N=800,000N = 800{,}000 documents (such as RCV1), storing full docIDs requires ⌈log⁡2(800,000)⌉=20 bits\lceil \log_2(800{,}000) \rceil = 20\text{ bits} per posting.
    • dd-gap Encoding: Since postings lists are sorted strictly in ascending docID order, store the gap between consecutive docIDs instead of absolute values:     docIDs: [283042,283043,283044,283045]  ⟹  gaps: [283042,1,1,1]\text{docIDs: } [283042, 283043, 283044, 283045] \implies \text{gaps: } [283042, 1, 1, 1]
    • Frequent terms yield tiny gaps (g=1g = 1), which can be stored in far fewer bits using variable-length integer encoding schemes.
  • Variable Byte (VB) Encoding:

    • Allocates variable numbers of whole bytes to represent integers. Each byte uses 7 bits for data payload and 1 bit as a continuation bit (most significant bit):
    • Continuation bit = 11 indicates the final (or only) byte of the number.
    • Continuation bit = 00 indicates further bytes follow.
Bytes UsedPayload BitsValue Range
170 to 27−1=1270 \text{ to } 2^7 - 1 = 127
214128 to 214−1=16,383128 \text{ to } 2^{14} - 1 = 16{,}383
32116,384 to 221−1=2,097,15116{,}384 \text{ to } 2^{21} - 1 = 2{,}097{,}151
  • Encoding Algorithm Example (G=1337G = 1337):

    • Binary representation: 1337=1024+256+32+16+8+1=1010011100121337 = 1024 + 256 + 32 + 16 + 8 + 1 = 10100111001_2 (11 bits11\text{ bits}, requiring 2 bytes).
    • Segment into 7-bit chunks from right: [0001010, 0111001].
    • Prefix continuation bits (00 for leading byte, 11 for terminal byte): 00001010 10111001.
  • Decompression is fast because processors operate natively on byte boundaries.

    • Elias Gamma (γ\gamma) Encoding:
  • A bit-level, parameter-free encoding scheme where each integer G≥1G \ge 1 is decomposed into a length component and an offset component.

  • Offset: Write GG in binary and discard the leading 11 (takes ⌊log⁡2(G)⌋\lfloor \log_2(G) \rfloor bits).

  • Length: The length of the offset represented in unary code: ⌊log⁡2(G)⌋\lfloor \log_2(G) \rfloor ones followed by a terminal zero.

  • γ\gamma-code: length concatenated with offset.

  • The total number of bits required is strictly 2⌊log⁡2(G)⌋+12 \lfloor \log_2(G) \rfloor + 1.

Elias Gamma Encoding Table and Bit Breakdown

  • Comparison: Elias γ\gamma-encoding achieves greater compression than VB on very small gaps (G=1G = 1 takes only 1 bit1\text{ bit} vs. 8 bits8\text{ bits} in VB), but decompressing bit-level streams requires bit-shifting operations that are significantly slower than byte-aligned decoding.

Vector Space Model and Ranked Retrieval

  • Limitations of Pure Boolean Retrieval:

    • The Boolean retrieval model forces a binary decision: a document matches or it does not.
    • Feast or Famine Problem: Conjunctive queries (AND\text{AND}) often return zero results if any term is missing, while disjunctive queries (OR\text{OR}) return tens of thousands of unranked documents, overwhelming users.
    • Ranked retrieval models replace Boolean logic with a continuous scoring function that measures relevance and returns the top-KK results.
  • Jaccard Similarity Coefficient:

    • A simple set-theoretic measure of overlap between query term set XX and document term set YY:     J(X,Y)=∣X∩Y∣∣X∪Y∣J(X, Y) = \frac{|X \cap Y|}{|X \cup Y|}
    • Critical Flaws for Text Retrieval:
    1. Ignores term frequency (tftf): mentioning a term ten times contributes no more than mentioning it once.
    2. Ignores term rarity (idfidf): matches on ubiquitous stop words carry the same weight as matches on rare, highly informative keywords.
    3. Penalizes long documents too heavily: dividing by the size of the union (∣X∪Y∣|X \cup Y|) systematically favors very short documents.
  • Term Frequency (tftf) Logarithmic Weighting:

    • A document discussing a topic frequently is generally more relevant, but relevance does not scale linearly with raw term frequency. Ten occurrences of a word do not make a document ten times more relevant than one occurrence.
    • Log-Frequency Weighting: Dampens the raw frequency using a base-10 logarithm:     wt,d={1+log⁡10(tft,d)if tft,d>00otherwisew_{t,d} = \begin{cases} 1 + \log_{10}(tf_{t,d}) & \text{if } tf_{t,d} > 0 \\ 0 & \text{otherwise} \end{cases}
  • Document Frequency (dfdf) and Inverse Document Frequency (idfidf):

    • Rare terms are far more informative than common terms.
    • Document Frequency (dftdf_t): The number of documents containing term tt (equal to the length of its postings list).
    • Collection Frequency (cftcf_t): The total number of times term tt appears across the entire corpus, including repetitions within documents.
    • Why dfdf is superior to cfcf for term weighting: Two words can have identical collection frequencies, but one might appear once in thousands of documents (low specificity, e.g., try\text{try}), while the other is clustered heavily in a few documents (high specificity, e.g., insurance\text{insurance}). The term concentrated in a few documents is far more predictive of topical relevance. Document frequency captures this difference; collection frequency does not.
    • Inverse Document Frequency (idftidf_t): Measures the informativeness of term tt across a collection of NN documents:     idft=log⁡10(Ndft)idf_t = \log_{10}\left(\frac{N}{df_t}\right)
  • Combined tf-idftf\text{-}idf Weighting:

    • Assigns each term tt in document dd a weight combining its local prominence with its global rarity:     wt,d=(1+log⁡10(tft,d))×log⁡10(Ndft)w_{t,d} = (1 + \log_{10}(tf_{t,d})) \times \log_{10}\left(\frac{N}{df_t}\right)
    • The total matching score between a query qq and document dd is the sum of their shared tf-idftf\text{-}idf weights:     Score(q,d)=∑t∈q∩dtf.idft,d\text{Score}(q, d) = \sum_{t \in q \cap d} tf.idf_{t,d}

Term-Document Matrix with tf-idf Weights for Shakespearean Plays

  • Vector Space Representation and Distance Metrics:
    • Both documents and queries are represented as high-dimensional, sparse vectors in an R∣V∣\mathbb{R}^{|V|} metric space, where each unique vocabulary term forms an orthogonal coordinate axis.
    • Euclidean Distance: Measuring straight-line geometric distance d(q,d)=∥q−d∥d(\mathbf{q}, \mathbf{d}) = \|\mathbf{q} - \mathbf{d}\| fails because vector length dominates. A long document and a short query with identical term distributions will have a large Euclidean distance simply because the document vector is longer.

Euclidean Distance Failure on Query and Document Vectors

  • Cosine Similarity: Measures the angle θ\theta between vectors, making it invariant to document length. Parallel vectors have θ=0∘  ⟹  cos⁡(θ)=1\theta = 0^\circ \implies \cos(\theta) = 1, while orthogonal vectors have θ=90∘  ⟹  cos⁡(θ)=0\theta = 90^\circ \implies \cos(\theta) = 0:   cos⁡(q,d)=q⋅d∥q∥∥d∥=∑i=1∣V∣qidi∑i=1∣V∣qi2∑i=1∣V∣di2=q^⋅d^\cos(\mathbf{q}, \mathbf{d}) = \frac{\mathbf{q} \cdot \mathbf{d}}{\|\mathbf{q}\| \|\mathbf{d}\|} = \frac{\sum_{i=1}^{|V|} q_i d_i}{\sqrt{\sum_{i=1}^{|V|} q_i^2} \sqrt{\sum_{i=1}^{|V|} d_i^2}} = \hat{\mathbf{q}} \cdot \hat{\mathbf{d}}

Cosine Similarity on Normalized Unit Hypersphere

  • Length Normalization: Dividing a vector by its Euclidean L2L_2 norm (v^=v/∥v∥\hat{\mathbf{v}} = \mathbf{v} / \|\mathbf{v}\|) maps all document endpoints onto the surface of a unit hypersphere, making cosine similarity mathematically equivalent to Euclidean distance.

    • Worked Example: Cosine Similarity between Literary Works:
  • Comparing Sense and Sensibility (SaS), Pride and Prejudice (PaP), and Wuthering Heights (WH):

Term Frequencies, Log Weights, and Length Normalization for Literary Works

  • Calculating length-normalized dot products:   cos⁡(SaS,PaP)≈(0.789×0.832)+(0.515×0.555)+(0.335×0.0)+(0.0×0.0)≈0.94\cos(\text{SaS}, \text{PaP}) \approx (0.789 \times 0.832) + (0.515 \times 0.555) + (0.335 \times 0.0) + (0.0 \times 0.0) \approx 0.94cos⁡(SaS,WH)≈(0.789×0.524)+(0.515×0.465)+(0.335×0.405)+(0.0×0.588)≈0.79\cos(\text{SaS}, \text{WH}) \approx (0.789 \times 0.524) + (0.515 \times 0.465) + (0.335 \times 0.405) + (0.0 \times 0.588) \approx 0.79cos⁡(PaP,WH)≈(0.832×0.524)+(0.555×0.465)+(0.0×0.405)+(0.0×0.588)≈0.69\cos(\text{PaP}, \text{WH}) \approx (0.832 \times 0.524) + (0.555 \times 0.465) + (0.0 \times 0.405) + (0.0 \times 0.588) \approx 0.69
  • Jane Austen's two works exhibit a much higher similarity (0.940.94) than either does to Emily Brontë's novel (0.790.79 and 0.690.69).

Efficient Scoring, Ranking, and Search Architecture

  • Top-KK Retrieval Bottleneck:

    • Computing cosine scores against all documents with non-zero term overlap (JJ documents) and sorting them takes O(Jlog⁡(J))\mathcal{O}(J \log(J)) time, which is too slow for large collections.
    • Min-Heap Selection: Maintain a min-heap bounded at capacity KK. For each computed score, compare it to the heap's minimum element and insert if greater (O(Jlog⁡(K))\mathcal{O}(J \log(K)) time).
    • Non-Exact Top-KK Retrieval: To bypass computing all JJ cosine scores, define a candidate set AA where K<∣A∣≪NK < |A| \ll N, evaluate full scores only for documents in AA, and return the top KK.
  • Index Elimination Techniques:

    • High-idfidf Terms Only: When evaluating multi-word queries, ignore terms with low idfidf. High-dfdf terms have very long postings lists and contribute minimally to the score, so skipping them dramatically reduces candidate set AA.
    • Document Intersection Thresholds: Restrict scoring to documents that contain at least a threshold fraction of the query terms (e.g., at least 3 out of 4 terms).
  • Champion Lists (Fancy Lists / Top Docs):

    • During index construction, precompute and store a separate sublist of the top rr documents with the highest weights (tftf or tf-idftf\text{-}idf) for each term tt.
    • At query time, form candidate set AA as the union of the champion lists for all query terms, computing cosine similarity only on this restricted pool.
    • Limitation: If r<Kr < K, the champion pool may not yield enough matching documents, requiring fallback to the full postings lists.
  • Static Quality Scores and Net Score Computation:

    • High-quality search results must be both query-relevant and globally authoritative.
    • Static Quality Score (g(d)g(d)): A query-independent quality measure normalized to [0,1][0, 1] (e.g., PageRank, link count, citation count, or domain authority).
    • Combined Net Score:netscore(q,d)=g(d)+cos⁡(q,d)\text{netscore}(q, d) = g(d) + \cos(q, d)
    • Alternatively, weights can be tuned via machine learning.
  • Postings Traversal Strategies: DAAT vs. TAAT:

    • Document-at-a-Time (DAAT):
    • Postings lists are sorted globally (e.g., by docID or static score g(d)g(d)).
    • The query processor traverses all term postings lists concurrently, calculating the complete net score for one document before advancing.
    • Pros: Minimal memory usage (no intermediate score accumulators needed); works well with top-KK heaps and early-termination bounds.
    • Term-at-a-Time (TAAT):
    • Postings lists are processed sequentially, one term at a time.
    • An in-memory hash table of accumulators tracks partial scores for each candidate document, adding term contributions until all lists have been read.
    • Pros: Supports variable-ordered lists that lack a global sorting order.
    • Cons: Requires significant memory to store score accumulators for all candidate documents.
DimensionDocument-at-a-Time (DAAT)Term-at-a-Time (TAAT)
TraversalConcurrent across all query listsSequential, one list at a time
Accumulator MemoryMinimal (bounded by KK)Substantial (one per candidate doc)
Required List OrderMust share identical global sort (docID or g(d)g(d))Arbitrary per-list ordering permitted
Impact OrderingIncompatibleNative fit
Response DeadlinesSimple to truncate (scored docs are complete)Complex (partially scored docs)
  • Impact-Ordered Postings:

    • Sort each term's postings list in descending order of that term's importance to the document (e.g., by term frequency tftf or weight wt,dw_{t,d}), rather than by docID.
    • Since each list has its own order, processing must use TAAT.
    • Early Termination: Stop reading each postings list once the term weight falls below a threshold, or after scanning a fixed number of postings rr.
    • idfidf-Ordered Processing: Process query terms in descending order of their global idfidf. If top-KK scores stabilize after evaluating the rarest terms, truncate processing before scanning the remaining high-frequency lists.
  • Cluster Pruning:

Cluster Pruning Structure with Leaders and Followers

  • Preprocessing step to accelerate nearest-neighbor vector searches over NN documents:

    1. Sample N\sqrt{N} documents at random to serve as leaders.
    2. Assign each remaining document (follower) to its closest leader by cosine similarity.
  • Query execution:

    1. Compare query vector q\mathbf{q} to all N\sqrt{N} leaders and find the closest leader LL.
    2. Form candidate set AA from LL and its assigned followers (≈N\approx \sqrt{N} documents).
    3. Score the candidate set and return the top KK.
  • Generalized Variant (b1,b2b_1, b_2): Associate each follower with its b1b_1 closest leaders, and evaluate the b2b_2 closest leaders to the query, trading increased computation for higher recall.

    • Parametric and Zone Indexes:
  • Field: Structured metadata with fixed values (e.g., date, author, file format).

  • Zone: A semi-structured region of free text within a document (e.g., title, abstract, body, references).

  • Implementation Approaches:

    • Fat Dictionary: Create distinct dictionary entries for each term-zone pair (e.g., william.title, william.abstract), each with its own postings list. Keeps postings simple, but inflates the lexicon.
    • Fat Postings: Maintain a single dictionary entry for each term, and encode zone identifiers into the postings list entries (e.g., doc 2: [author, title]). Keeps the lexicon small, but increases postings size.
  • Weighted Zone Scoring: Compute a linear combination of zone matches using normalized weights: ∑j=1Zgj⋅sj\sum_{j=1}^{Z} g_j \cdot s_j, where ∑gj=1\sum g_j = 1.

    • Tiered Indexes:
  • Break postings lists into hierarchical tiers based on term importance:

    • Tier 1: High-relevance documents (e.g., tf>20tf > 20 or high g(d)g(d)).
    • Tier 2: Moderate-relevance documents (e.g., 10<tf≤2010 < tf \le 20).
    • Tier 3: Low-relevance documents (all remaining postings).
  • Query execution searches Tier 1 first. If it yields at least KK results, the query terminates. Otherwise, it falls back to Tier 2 and Tier 3 progressively.

Tiered Postings Inverted Index Hierarchy

  • Query-Term Proximity Scoring:

    • Users strongly prefer documents where query terms appear close to one another, rather than scattered across the document.
    • Let ω\omega be the smallest word window in a document that contains all query terms.
    • Smaller ω\omega values indicate stronger proximity matches, providing a soft conjunctive signal that can be integrated into the document's ranking score alongside vector similarity.
  • Complete Search Engine System Architecture:

Comprehensive Search Engine Architecture Pipeline

  • Ingestion parses raw text into document caches for snippet generation, while indexers build tiered positional, metadata, and kk-gram indices.
  • Incoming queries pass through a query parser (which tests phrase constraints, disjunctions, and relaxed operators) and a spelling correction module.
  • Candidate documents retrieved from the indices are ranked by a machine-learned scoring function that combines vector similarity, proximity window ω\omega, and static quality g(d)g(d).

Evaluation of Information Retrieval Systems

  • Evaluation Foundations and Standard Test Collections:

    • Measuring search quality requires standardized benchmarks rather than raw computational metrics (such as throughput or latency).
    • Cranfield Paradigm: A standard test collection consists of three components:
    1. A static document collection (benchmark corpus\text{benchmark corpus}).
    2. A set of realistic, predefined test queries (topics\text{topics}).
    3. A set of binary or graded relevance assessments (relevance judgments, or gold standard labels) for every query-document pair.
    • The Text REtrieval Conference (TREC): Organized by the National Institute of Standards and Technology (NIST), TREC produces large-scale benchmark collections to enable reproducible IR research.
    • Evaluating Human Inter-Annotator Agreement: Measured using Cohen's Kappa (κ\kappa):     κ=P(A)−P(E)1−P(E)\kappa = \frac{P(A) - P(E)}{1 - P(E)}     Where P(A)P(A) is the observed proportion of agreement, and P(E)P(E) is the agreement expected by chance. κ=1\kappa = 1 indicates complete agreement, while κ=0\kappa = 0 indicates agreement no better than chance.
  • Information Need vs. Query Formulation:

    • An information need is the user's underlying topic of desire, whereas a query is the concrete text string submitted to the search engine. Relevance judgments are always evaluated against the user's underlying information need, not against literal keyword matches.
  • Unranked Evaluation Metrics:

Confusion Matrix for Unranked IR Evaluation

  • Precision (PP): Fraction of retrieved documents that are relevant:     P=tptp+fp=∣Relevant∩Retrieved∣∣Retrieved∣P = \frac{tp}{tp + fp} = \frac{|\text{Relevant} \cap \text{Retrieved}|}{|\text{Retrieved}|}

  • Recall (RR): Fraction of all relevant documents that are retrieved:     R=tptp+fn=∣Relevant∩Retrieved∣∣Relevant∣R = \frac{tp}{tp + fn} = \frac{|\text{Relevant} \cap \text{Retrieved}|}{|\text{Relevant}|}

  • Why Accuracy Fails in IR: Accuracy is tp+tntp+fp+fn+tn\frac{tp + tn}{tp + fp + fn + tn}. In IR, the vast majority of documents are not relevant (tntn is enormous). A trivial system that returns an empty set for every query achieves ≈99.99%\approx 99.99\% accuracy, despite being completely useless. Precision and recall ignore true negatives, correctly penalizing such systems.

  • FF-Measure (Balanced and Weighted):

    • The weighted harmonic mean of precision and recall:       Fβ=(1+β2)⋅P⋅Rβ2P+RF_\beta = \frac{(1 + \beta^2) \cdot P \cdot R}{\beta^2 P + R}
    • Parameter β\beta controls the relative weighting: β>1\beta > 1 emphasizes recall, whereas β<1\beta < 1 emphasizes precision.
    • When β=1\beta = 1, it yields the balanced harmonic mean (F1F_1-score):       F1=2PRP+RF_1 = \frac{2PR}{P + R}
    • The harmonic mean penalizes systems with extreme imbalances: if a system retrieves all documents (R=1.0R = 1.0, but P→0P \to 0), its arithmetic mean is 0.50.5, but its harmonic mean correctly drops near 00.
  • Breakeven Point: The point in a ranked list where precision equals recall (P=RP = R). At this exact threshold, F1=P=RF_1 = P = R.

    • Ranked Retrieval Evaluation Metrics:
  • Precision at KK (P@KP@K): The proportion of relevant documents among the top KK retrieved positions (e.g., P@10P@10 corresponds to the first page of search results).

  • Precision-Recall Curves and Interpolated Precision:

    • Plotting precision against recall as more documents are retrieved produces a jagged, sawtooth curve. Precision drops when non-relevant documents are retrieved and jumps upward when relevant ones appear.

Precision-Recall Curves with Sawtooth Pattern and Interpolated Step Function

  • Interpolated Precision (Pinterp(r)P_{\text{interp}}(r)): Eliminates the sawtooth pattern by setting the precision at recall level rr to the maximum precision observed at any recall level r′≥rr' \ge r:     Pinterp(r)=max⁡r′≥rP(r′)P_{\text{interp}}(r) = \max_{r' \ge r} P(r')
    • Mean Average Precision (MAP):
  • The gold-standard single-number summary for ranking performance across binary relevance judgments.
  • Average Precision (AP): For a single query, compute precision at every rank where a relevant document appears, and divide by the total number of relevant documents (∣R∣|R|):     AP=1∣R∣∑k=1n(P@k×I(dock∈R))AP = \frac{1}{|R|} \sum_{k=1}^{n} (P@k \times \mathbb{I}(\text{doc}_k \in R))
  • MAP: The arithmetic mean of AP across a set of test queries QQ:     MAP=1∣Q∣∑q=1∣Q∣AP(q)MAP = \frac{1}{|Q|} \sum_{q=1}^{|Q|} AP(q)
  • Worked Example: A query has 6 relevant documents. System 1 returns relevant results at ranks 1, 3, 4, 5, 6, 10. System 2 returns relevant results at ranks 2, 5, 6, 7, 9, 10.

Worked AP Comparison for Two Different Ranked Retrieval Results

      AP1=16(11+23+34+45+56+610)=1.0+0.67+0.75+0.80+0.83+0.606=0.78AP_1 = \frac{1}{6} \left( \frac{1}{1} + \frac{2}{3} + \frac{3}{4} + \frac{4}{5} + \frac{5}{6} + \frac{6}{10} \right) = \frac{1.0 + 0.67 + 0.75 + 0.80 + 0.83 + 0.60}{6} = 0.78AP2=16(12+25+36+47+59+610)=0.50+0.40+0.50+0.57+0.56+0.606=0.52AP_2 = \frac{1}{6} \left( \frac{1}{2} + \frac{2}{5} + \frac{3}{6} + \frac{4}{7} + \frac{5}{9} + \frac{6}{10} \right) = \frac{0.50 + 0.40 + 0.50 + 0.57 + 0.56 + 0.60}{6} = 0.52

  • Mean Reciprocal Rank (MRR): Focuses exclusively on the rank position of the first relevant document (rank1\text{rank}_1). Used for question-answering systems where users only need one correct answer:   MRR=1∣Q∣∑i=1∣Q∣1rankiMRR = \frac{1}{|Q|} \sum_{i=1}^{|Q|} \frac{1}{\text{rank}_i}
  • Discounted Cumulative Gain (DCG) and Normalized DCG (NDCG):
    • Designed for search domains (e.g., Web search) with graded relevance judgments (e.g., 0=bad0 = \text{bad}, 1=marginal1 = \text{marginal}, 2=good2 = \text{good}, 3=perfect3 = \text{perfect}).
    • Cumulative Gain (CG): Sum of relevance grades down the ranked list.
    • Discounted Cumulative Gain (DCG): Applies a logarithmic discount to penalize relevant documents that appear lower down the list:     DCGp=∑i=1prelilog⁡2(max⁡(i,2))DCG_p = \sum_{i=1}^{p} \frac{\text{rel}_i}{\log_2(\max(i, 2))}
Rank (ii)Logarithmic Discount Factor (1log⁡2(i)\frac{1}{\log_2(i)})
1No discount (evaluated at full gain)
21.01.0
40.50.5
80.3330.333
160.250.25
  • Ideal DCG (IDCG): The DCG score achieved by sorting all known relevant documents in perfect, descending order of their relevance grades.
  • Normalized DCG (NDCG): Normalizes DCG into a [0,1][0, 1] range to allow fair comparison across queries:   NDCGp=DCGpIDCGpNDCG_p = \frac{DCG_p}{IDCG_p}
  • Limitation: NDCG can be inflated by duplicate documents. Presenting identical highly relevant documents at ranks 1 and 2 increases NDCG, even though it provides zero additional utility to the user.

Relevance Feedback and Query Refinement

  • The Query Refinement Spectrum:

    • Addresses the vocabulary mismatch problem: different words can describe the same underlying concept (synonymy), degrading recall.
    • Global Methods: Adjust queries using corpus-wide or language-wide lexical knowledge, independent of the initial search results (e.g., manual/automatic thesaurus expansion, spelling correction).
    • Local Methods: Adjust queries based on the documents returned by the initial search (e.g., explicit relevance feedback, pseudo-relevance feedback, clickstream analysis).
  • The Rocchio Algorithm for Relevance Feedback:

    • Standard vector-space method that incorporates user relevance feedback by shifting the query vector toward relevant documents and away from non-relevant ones.

Rocchio Query Movement Toward Relevant Centroids

  • Centroid Concept: The centroid μ(C)\mu(C) represents the geometric center of a set of document vectors CC:     μ(C)=1∣C∣∑d∈Cd\mu(C) = \frac{1}{|C|} \sum_{\mathbf{d} \in C} \mathbf{d}

  • The Theoretically Optimal Query (Unachievable in Practice):qopt=μ(Cr)−μ(Cnr)=1∣Cr∣∑d∈Crd−1∣Cnr∣∑d∈Cnrd\mathbf{q}_{\text{opt}} = \mu(C_r) - \mu(C_{nr}) = \frac{1}{|C_r|} \sum_{\mathbf{d} \in C_r} \mathbf{d} - \frac{1}{|C_{nr}|} \sum_{\mathbf{d} \in C_{nr}} \mathbf{d}     Where CrC_r and CnrC_{nr} represent the complete sets of all relevant and non-relevant documents in the entire corpus.

  • The Practical Rocchio Equation: Operates on the small subsets of documents evaluated by the user (DrD_r and DnrD_{nr}):     qm=αq0+β1∣Dr∣∑d∈Drd−γ1∣Dnr∣∑d∈Dnrd\mathbf{q}_m = \alpha \mathbf{q}_0 + \beta \frac{1}{|D_r|} \sum_{\mathbf{d} \in D_r} \mathbf{d} - \gamma \frac{1}{|D_{nr}|} \sum_{\mathbf{d} \in D_{nr}} \mathbf{d}

    • q0\mathbf{q}_0 is the original query vector; qm\mathbf{q}_m is the revised query vector.
    • Weights α,β,γ\alpha, \beta, \gamma govern the relative influence of the initial query, positive feedback, and negative feedback.
    • Typical parameters: α=1.0\alpha = 1.0, β=0.75\beta = 0.75, and γ=0.15\gamma = 0.15.
    • β≫γ\beta \gg \gamma because positive feedback is far more reliable and informative than negative feedback; non-relevant documents can be unrelated in many different, contradictory ways.
    • Negative vector components are truncated to zero: any term where qm,i<0q_{m,i} < 0 is set to 00.
  • Worked Rocchio Computation:

    • Initial query q0=[1,0,0]\mathbf{q}_0 = [1, 0, 0], one relevant document dr=[0,2,0]\mathbf{d}_r = [0, 2, 0], one non-relevant document dnr=[0,0,2]\mathbf{d}_{nr} = [0, 0, 2].

    • Weights: α=1.0\alpha = 1.0, β=0.75\beta = 0.75, γ=0.15\gamma = 0.15.       qm=1.0[1,0,0]+0.75[0,2,0]−0.15[0,0,2]=[1.0,1.5,−0.3]\mathbf{q}_m = 1.0[1, 0, 0] + 0.75[0, 2, 0] - 0.15[0, 0, 2] = [1.0, 1.5, -0.3]

    • Truncate negative components to zero: qm=[1.0,1.5,0.0]\mathbf{q}_m = [1.0, 1.5, 0.0].

    • Assumptions and Failure Modes of Relevance Feedback:

  • Assumption 1: The user must be able to formulate a reasonable initial query. If the initial query returns zero relevant documents, the user has nothing to label, and the feedback loop cannot start.

  • Assumption 2: Relevant documents must form a single, cohesive cluster in vector space. If relevant documents form multimodal distributions (e.g., documents about the country named both Burma\text{Burma} and Myanmar\text{Myanmar}), their geometric centroid will land in the empty space between the clusters, degrading search performance.

  • System Drawbacks: Expands query vectors with dozens of new terms, significantly increasing query execution latency. In practice, most users are unwilling to manually label results.

    • Pseudo-Relevance Feedback (Blind Feedback):
  • Automates explicit feedback: assumes the top-kk documents returned by the initial search are relevant, and applies Rocchio feedback directly to those top-kk results without human intervention.

  • Substantially improves recall on average, but risks query drift: if the top results are off-topic, the query shifts further in the wrong direction, severely degrading search quality.

    • Indirect Relevance Feedback:
  • Derives implicit relevance signals from passive user behavior, such as search result clicks, dwell times, and query reformulations, bypassing the need for manual user labeling.

    • Automatic Thesaurus Construction:
  • Expands queries automatically using mined term relationships, avoiding the high cost of manual thesaurus curation.

  • Co-occurrence Analysis: Terms that frequently appear in the same documents or sliding windows are assumed to be semantically related (e.g., doctor\text{doctor} co-occurs with nurse, hospital, patient\text{nurse, hospital, patient}). Robust to grammatical errors, but conflates broader topical relatedness with true synonymy.

  • Grammatical Dependency Relations: Uses grammatical parsers to identify words that share identical syntactic roles (e.g., words acting as direct objects of verbs like cook, eat, digest\text{cook, eat, digest} indicate food items: apple, bread, rice\text{apple, bread, rice}). Produces cleaner synonyms, but is sensitive to parser failures on ungrammatical text.

Document Classification and Machine Learning

  • The Text Classification Problem:

    • Standing Queries: Persistent queries run periodically against streaming collections (e.g., alert systems, continuous legal discovery, spam filters). They partition incoming documents into two classes: matching and non-matching.
    • Formal Definition: Given a document space XX, a fixed set of classes C={c1,c2,…,cJ}C = \{c_1, c_2, \dots, c_J\}, and a training set DD of labeled pairs ⟨d,c⟩\langle d, c \rangle, learn a classifier function γ:X→C\gamma: X \to C that correctly maps unseen documents to their true categories.
    • Approaches: Manual classification (accurate but slow and expensive), handwritten Boolean rules (difficult to maintain at scale), and supervised machine learning (the standard approach).
  • Naive Bayes Text Classification:

    • A generative, probabilistic classifier grounded in Bayes' rule:     P(c∣d)=P(c)⋅P(d∣c)P(d)P(c | d) = \frac{P(c) \cdot P(d | c)}{P(d)}
    • The Maximum A Posteriori (MAP) decision rule drops the class-invariant denominator P(d)P(d):     cmap=arg⁡max⁡c∈CP(c)⋅P(d∣c)=arg⁡max⁡c∈CP(c)∏k=1ndP(tk∣c)c_{\text{map}} = \arg\max_{c \in C} P(c) \cdot P(d | c) = \arg\max_{c \in C} P(c) \prod_{k=1}^{n_d} P(t_k | c)
    • The Two \"Naive\" Assumptions:
    1. Conditional Independence: Words occur independently of one another within a document, given the class (P(t1,t2∣c)=P(t1∣c)⋅P(t2∣c)P(t_1, t_2 | c) = P(t_1 | c) \cdot P(t_2 | c)). Fails in natural language (e.g., New\text{New} and York\text{York} are highly correlated), but works well in practice because classification depends on correct rank ordering, not exact probabilities.
    2. Positional Independence: Word order is completely ignored; word probability depends only on the class, not on its position in the document (the bag-of-words assumption).
    • Parameter Estimation with Laplace (Add-One) Smoothing:
    • Class prior: P(c)=NcNP(c) = \frac{N_c}{N}, where NcN_c is the document count for class cc, and NN is the total document count.
    • If a word never appears in a training class, its conditional probability is zero (P(t∣c)=0P(t|c) = 0), which zeroes out the entire product. To prevent this, apply Laplace smoothing:       P^(t∣c)=Tct+1∑t′∈VTct′+∣V∣\hat{P}(t | c) = \frac{T_{ct} + 1}{\sum_{t' \in V} T_{ct'} + |V|}       Where TctT_{ct} is the count of term tt in class cc, and ∣V∣|V| is the total size of the vocabulary across all classes.
    • Underflow Prevention: Multiplying hundreds of tiny probabilities causes floating-point underflow. In practice, calculations are performed in log space:     cmap=arg⁡max⁡c∈C[log⁡(P(c))+∑k=1ndlog⁡(P(tk∣c))]c_{\text{map}} = \arg\max_{c \in C} \left[ \log(P(c)) + \sum_{k=1}^{n_d} \log(P(t_k | c)) \right]
  • Worked Example: Naive Bayes Classification with Boolean Features:

    • Six labeled training instances with binary features (b1,b2)(b_1, b_2), classified into classes + and o:
Instanceb1b_1b2b_2Class
x1x_101o
x2x_201+
x3x_300+
x4x_411o
x5x_510+
x6x_611+
xtestx_{\text{test}}01?
  • Step 1: Compute Priors:P(+)=46=23,P(o)=26=13P(+) = \frac{4}{6} = \frac{2}{3}, \quad P(o) = \frac{2}{6} = \frac{1}{3}

  • Step 2: Compute Smoothed Conditional Probabilities for xtest=(b1=0,b2=1)x_{\text{test}} = (b_1=0, b_2=1):

    • Feature values are binary (B=2B = 2 possible values), so add 11 to the numerator and 22 to the denominator:
    • For class + (4 instances4\text{ instances}):       P(b1=0∣+)=count(b1=0,+)+14+2=2+16=36=12P(b_1=0 | +) = \frac{\text{count}(b_1=0, +) + 1}{4 + 2} = \frac{2 + 1}{6} = \frac{3}{6} = \frac{1}{2}P(b2=1∣+)=count(b2=1,+)+14+2=2+16=36=12P(b_2=1 | +) = \frac{\text{count}(b_2=1, +) + 1}{4 + 2} = \frac{2 + 1}{6} = \frac{3}{6} = \frac{1}{2}
    • For class o (2 instances2\text{ instances}):       P(b1=0∣o)=count(b1=0,o)+12+2=1+14=24=12P(b_1=0 | o) = \frac{\text{count}(b_1=0, o) + 1}{2 + 2} = \frac{1 + 1}{4} = \frac{2}{4} = \frac{1}{2}P(b2=1∣o)=count(b2=1,o)+12+2=2+14=34P(b_2=1 | o) = \frac{\text{count}(b_2=1, o) + 1}{2 + 2} = \frac{2 + 1}{4} = \frac{3}{4}
  • Step 3: Evaluate Decision Scores:Score(+)=P(+)⋅P(b1=0∣+)⋅P(b2=1∣+)=23⋅12⋅12=212=16≈0.167\text{Score}(+) = P(+) \cdot P(b_1=0 | +) \cdot P(b_2=1 | +) = \frac{2}{3} \cdot \frac{1}{2} \cdot \frac{1}{2} = \frac{2}{12} = \frac{1}{6} \approx 0.167Score(o)=P(o)⋅P(b1=0∣o)⋅P(b2=1∣o)=13⋅12⋅34=324=18=0.125\text{Score}(o) = P(o) \cdot P(b_1=0 | o) \cdot P(b_2=1 | o) = \frac{1}{3} \cdot \frac{1}{2} \cdot \frac{3}{4} = \frac{3}{24} = \frac{1}{8} = 0.125

  • Since 16>18\frac{1}{6} > \frac{1}{8}, the classifier assigns xtestx_{\text{test}} to class +.

    • Rocchio Classification:
  • A vector-space classification method based on class centroids:

    1. Compute the centroid vector μc\mu_c for each training class cc.
    2. Assign an unlabeled document dd to the class of its closest centroid by Euclidean distance (or highest cosine similarity).
  • Forms linear decision boundaries between classes.

  • Limitation: Fails when classes are non-convex or consist of multiple distinct sub-clusters, because the centroid lands in empty space between the clusters.

    • kk-Nearest Neighbor (k-NNk\text{-NN}) Classification:
  • An instance-based lazy learning algorithm that defers computation until test time:

    • Training consists solely of storing labeled vectors.
    • To classify test vector x\mathbf{x}, locate its kk nearest neighbors in the training set and take a majority vote.
    • The parameter kk is typically an odd integer to prevent ties.
  • Forms non-linear, locally adaptive, piecewise-linear decision boundaries.

  • Computational Cost: High at test time (O(N)\mathcal{O}(N) distance calculations against all training vectors), requiring Approximate Nearest Neighbor (ANN) indices for fast retrieval.

    • The Bias-Variance Tradeoff:
  • Model prediction errors decompose into bias and variance:

    • Bias (Underfitting): Systematic error caused by overly restrictive model assumptions. Rocchio and Naive Bayes exhibit high bias because they enforce linear boundaries and independence assumptions.
    • Variance (Overfitting): Sensitivity to small fluctuations in the training data. 1-NN1\text{-NN} exhibits very high variance because individual noisy points create isolated decision boundaries.

Bias-Variance Tradeoff Illustrating Underfitting, Overfitting, and Balanced Fit

  • Multiclass Classification and Evaluation:
    • Multiclass Evaluation via Confusion Matrix:

Multiclass Confusion Matrix for Urgent, Normal, and Spam

  • Class-specific Precision: the diagonal cell divided by the sum of its predicted row (e.g., Precisionurgent=88+10+1=819\text{Precision}_{\text{urgent}} = \frac{8}{8 + 10 + 1} = \frac{8}{19}; Precisionnormal=605+60+50=60115\text{Precision}_{\text{normal}} = \frac{60}{5 + 60 + 50} = \frac{60}{115}; \text{Precision}_{\text{spam}} = \frac{200}{3 + 30 + 200} = \frac{200}{233}$).\n * Class-specific Recall: the diagonal cell divided by the sum of its gold column (e.g., \text{Recall}{\text{urgent}} = \frac{8}{8 + 5 + 3} = \frac{8}{16} = 0.5;;\text{Recall}{\text{normal}} = \frac{60}{10 + 60 + 30} = \frac{60}{100} = 0.6;;\text{Recall}_{\text{spam}} = \frac{200}{1 + 50 + 200} = \frac{200}{251}$).
    • Multi-Label vs. Single-Label Strategies:
  • Any-of (Multi-label): Documents can belong to zero, one, or multiple classes. Train JJ independent binary classifiers (one per class) that each output a yes/no decision.
  • One-of (Single-label / Multinomial): Documents belong to exactly one class. Train JJ binary classifiers using a one-vs-rest strategy, evaluate all JJ, and assign the document to the class with the highest confidence score.

Support Vector Machines and Kernel Methods

  • Maximum Margin Hyperplane Principles:
    • For linearly separable binary data, many separating hyperplanes exist. Support Vector Machines (SVMs) select the unique hyperplane that maximizes the geometric margin (the distance between the decision boundary and the closest training points from either class).

Support Vector Machine Maximum Margin Decision Hyperplane and Support Vectors

  • Mathematical Formulation:

    • Decision boundary: w⋅x+b=0\mathbf{w} \cdot \mathbf{x} + b = 0, where w\mathbf{w} is the normal weight vector perpendicular to the hyperplane, and bb is the bias offset.
    • Canonical classification rule: yi=+1y_i = +1 if w⋅xi+b>0\mathbf{w} \cdot \mathbf{x}_i + b > 0, and yi=−1y_i = -1 if w⋅xi+b<0\mathbf{w} \cdot \mathbf{x}_i + b < 0.
    • Margin boundaries are defined at w⋅x+b=±1\mathbf{w} \cdot \mathbf{x} + b = \pm 1.
    • Canonical separation condition: yi(w⋅xi+b)≥1y_i(\mathbf{w} \cdot \mathbf{x}_i + b) \ge 1 for all ii.
    • The geometric margin width equals 2∥w∥\frac{2}{\|\mathbf{w}\|}. Maximizing the margin is equivalent to minimizing the squared norm 12∥w∥2\frac{1}{2} \|\mathbf{w}\|^2.
  • Support Vectors:

    • The training points that lie directly on the margin boundaries (yi(w⋅xi+b)=1y_i(\mathbf{w} \cdot \mathbf{x}_i + b) = 1).

    • The optimal boundary depends solely on these support vectors; all other training points can be removed without altering the solution.

    • Dual Problem Formulation and Reconstruction:

  • The weight vector w\mathbf{w} can be reconstructed as a linear combination of training vectors using dual Lagrange multipliers αi\alpha_i:     w=∑i=1Nαiyixi\mathbf{w} = \sum_{i=1}^{N} \alpha_i y_i \mathbf{x}_i     Where αi>0\alpha_i > 0 exclusively for support vectors, and αi=0\alpha_i = 0 for all interior points.

  • The resulting decision function relies entirely on dot products between support vectors and the incoming test vector x\mathbf{x}, enabling the kernel trick:     f(x)=sign(∑i∈SVαiyi(xi⋅x)+b)f(\mathbf{x}) = \text{sign}\left( \sum_{i \in \text{SV}} \alpha_i y_i (\mathbf{x}_i \cdot \mathbf{x}) + b \right)

    • Soft-Margin SVM for Non-Separable Data:
  • When training data is noisy or linearly non-separable, a strict hard margin has no valid solution. Soft-margin SVMs introduce non-negative slack variables ξi≥0\xi_i \ge 0 to tolerate margin violations.

Soft Margin SVM with Slack Variables Allowing Margin Violations

  • The classification condition becomes: yi(w⋅xi+b)≥1−ξiy_i(\mathbf{w} \cdot \mathbf{x}_i + b) \ge 1 - \xi_i.
Slack Value (ξi\xi_i)Interpretation
ξi=0\xi_i = 0Correctly classified, lies on or outside the margin
0<ξi<10 < \xi_i < 1Correctly classified, but violates the margin (falls inside the margin boundary)
ξi=1\xi_i = 1Falls exactly on the decision boundary
ξi>1\xi_i > 1Misclassified (falls on the incorrect side of the decision boundary)
  • Soft-Margin Optimization Objective:min⁡w,b,ξ(12∥w∥2+C∑i=1Nξi)\min_{\mathbf{w}, b, \xi} \left( \frac{1}{2} \|\mathbf{w}\|^2 + C \sum_{i=1}^{N} \xi_i \right)

    • Parameter CC controls the regularization tradeoff: a large CC penalizes margin violations heavily (yielding narrow margins and risking overfitting), while a small CC tolerates violations more readily (yielding wider margins and risking underfitting).

    • Non-Linear SVMs and the Kernel Trick:

  • When data cannot be separated linearly in its native feature space, it can often be made linearly separable by projecting it into a higher-dimensional space via a non-linear mapping ϕ(x)\phi(\mathbf{x}).

Kernel Mapping Non-Linearly Separable Data to Linearly Separable Higher-Dimensional Space

  • The Kernel Trick: Computing coordinates in high-dimensional feature spaces is computationally expensive or impossible (e.g., spaces with infinite dimensions). However, SVM optimization requires only inner dot products between vectors, not the raw coordinates themselves.

  • A kernel function computes this inner product directly in the transformed space using the low-dimensional inputs:     K(xi,xj)=ϕ(xi)⋅ϕ(xj)K(\mathbf{x}_i, \mathbf{x}_j) = \phi(\mathbf{x}_i) \cdot \phi(\mathbf{x}_j)

  • Common kernels:

    • Linear Kernel: K(xi,xj)=xi⋅xjK(\mathbf{x}_i, \mathbf{x}_j) = \mathbf{x}_i \cdot \mathbf{x}_j
    • Polynomial Kernel: K(xi,xj)=(xi⋅xj+c)dK(\mathbf{x}_i, \mathbf{x}_j) = (\mathbf{x}_i \cdot \mathbf{x}_j + c)^d
    • Radial Basis Function (RBF / Gaussian): K(xi,xj)=exp⁡(−γ∥xi−xj∥2)K(\mathbf{x}_i, \mathbf{x}_j) = \exp(-\gamma \|\mathbf{x}_i - \mathbf{x}_j\|^2)
  • Linear SVMs are generally preferred for text classification: document vocabularies already provide thousands of dimensions, making linear separation possible without projecting into higher-dimensional spaces.

    • Learning to Rank (Ranking SVM):
  • Adapts SVM classification to the ranking task by learning from pairwise document preferences instead of absolute document labels.

  • Given a query qq, training instances consist of pairs where document did_i should rank higher than document djd_j (di≻djd_i \succ d_j).

  • Construct difference vectors: ϕ(di,q)−ϕ(dj,q)\phi(d_i, q) - \phi(d_j, q).

  • Train an SVM on these difference vectors to learn an optimal ranking projection vector w\mathbf{w}, ordering documents by their projected score w⋅ϕ(d,q)\mathbf{w} \cdot \phi(d, q).

Link Analysis, PageRank, and Web Search Algorithms

  • The Web as a Directed Graph:
    • The Web can be modeled as a directed graph G=(V,E)G = (V, E), where vertices VV represent static Web pages, and directed edges EE represent hyperlinks.

Directed Web Graph Architecture

  • In-links: Hyperlinks pointing into a webpage from external sources. Serve as endorsements of quality and authority.

  • Out-links: Hyperlinks pointing from a webpage out to other resources.

  • Underlying Hypotheses:

    • Hypothesis 1 (Authority Signal): A hyperlink from page AA to page BB represents an implicit endorsement of BB by the author of AA.

    • Hypothesis 2 (Anchor Text Utility): The anchor text describing hyperlink A→BA \to B provides a succinct, accurate summary of the content and purpose of target page BB.

    • Anchor Text Indexing:

  • Anchor text is the visible, clickable text within an HTML hyperlink tag (<a href="...">anchor text</a>).

  • Text engines append anchor text directly into the index entry of the target page (BB), weighted by the authority of the originating page (AA).

  • Solving Web Search Anomalies: Allows search engines to retrieve pages that contain little native text (e.g., graphical landing pages like IBM's homepage) based on millions of inbound links anchored with terms like \text{\"IBM\"} or \text{\"IBM home page\"}.

  • Non-Nepotistic Weighting: Links from independent external domains are weighted far more heavily than internal site links to prevent self-promotional manipulation.

    • Connectivity Servers:
  • Specialized systems that store the Web link graph entirely in memory using compressed adjacency lists, supporting fast lookups for both in-links and out-links to assist crawlers and link-analysis algorithms.

    • Historical Precedents: Citation Analysis:
  • Link analysis originated in bibliometrics and academic citation indexing:

    • Citation Frequency: Raw citation counts indicate academic impact.

    • Bibliographic Coupling: Two papers that cite common references share thematic overlap.

    • Co-citation: Two papers frequently cited together by third-party papers are thematically related.

    • Pinski and Narin (1976): Proposed that citations from highly cited, prestigious journals should carry greater weight than citations from obscure journals, establishing the core mathematical intuition behind PageRank.

    • The PageRank Algorithm:

  • Computes a global, query-independent static authority score for every Web page based on recursive hyperlink structures: a page is important if it receives links from other important pages.

  • The Random Surfer Model:

    • A hypothetical user visits a random page and continuously clicks outgoing links with uniform probability (1/out-degree1/\text{out-degree}).
    • Dead Ends (Dangling Nodes): Pages with zero out-links trap the random surfer.
    • Spider Traps: Loops or cycles of pages that link only to each other, preventing the surfer from escaping.
    • Teleportation: Resolves dead ends and spider traps. At each step, the surfer follows an outgoing link with probability 1−α1 - \alpha (typically 0.850.85 to 0.900.90), and jumps to a completely random Web page with teleportation probability α\alpha (typically 0.100.10 to 0.150.15).
  • Markov Chain Foundations:

    • Web surfing models an ergodic Markov chain across NN states (pages), defined by an N×NN \times N transition probability matrix PP.
    • For a standard node with out-degree kk, transition probabilities are Pij=1kP_{ij} = \frac{1}{k}. For dangling nodes with zero out-links, transitions are set to 1N\frac{1}{N} for all pages.
    • Adding teleportation produces the irreducible, aperiodic Google transition matrix P′P':       P′=(1−α)P+α1NEP' = (1 - \alpha) P + \alpha \frac{1}{N} \mathbf{E}       Where E\mathbf{E} is an N×NN \times N all-ones matrix.
    • Steady-State Distribution: By the Perron-Frobenius theorem, an ergodic Markov chain has a unique stationary probability distribution vector a\mathbf{a} that satisfies:       a=aP′\mathbf{a} = \mathbf{a} P'
    • Vector a\mathbf{a} represents the long-term visit frequency of the random surfer, and its components provide the definitive PageRank scores.
  • Power Iteration Method:

    • Initialize a probability vector x0=[1N,1N,…,1N]\mathbf{x}_0 = [\frac{1}{N}, \frac{1}{N}, \dots, \frac{1}{N}].

    • Iteratively multiply by the transition matrix: xk+1=xkP′\mathbf{x}_{k+1} = \mathbf{x}_k P'.

    • Repeat until the Euclidean distance between successive iterations falls below an error threshold (∥xk+1−xk∥<ϵ\|\mathbf{x}_{k+1} - \mathbf{x}_k\| < \epsilon).

    • Hyperlink-Induced Topic Search (HITS):

  • A query-dependent link-analysis algorithm developed by Jon Kleinberg that identifies two distinct classes of authoritative pages:

    • Authorities: High-quality informational pages covering a query topic, pointed to by many good hubs.
    • Hubs: High-quality link collections or directories that point to many good authority pages.

HITS Subgraph Expansion from Root Set to Base Set

  • Sub-graph Construction:
    • Root Set: Retrieve the top 200 to 1000200\text{ to }1000 documents matching the user query from a standard inverted index.
    • Base Set: Expand the root set by adding all pages that point to any page in the root set (in-links), and all pages pointed to by any page in the root set (out-links).
  • Mutually Recursive Iterative Updates:
    • Initialize all hub scores h(x)=1h(x) = 1 and authority scores a(x)=1a(x) = 1.
    • Iteratively update scores across the base set:     h(x)=∑x→ya(y),a(x)=∑y→xh(y)h(x) = \sum_{x \to y} a(y), \quad a(x) = \sum_{y \to x} h(y)
    • After each iteration, normalize the score vectors to sum to 1 to prevent numerical overflow:     h(x)←h(x)∑h(z),a(x)←a(x)∑a(z)h(x) \leftarrow \frac{h(x)}{\sum h(z)}, \quad a(x) \leftarrow \frac{a(x)}{\sum a(z)}
    • Iterations typically converge to a stable ranking within 5 to 10 cycles.
FeaturePageRankHITS
Query DependencyQuery-independent (computed offline globally)Query-dependent (computed online on a sub-graph)
Metric SpaceSingle global authority score per pageDual scores: Hub score and Authority score
Computation ScopeFull global Web graph (1010+10^{10}+ pages)Small query-specific base set (10310^3 to 10410^4 pages)
Susceptibility to SpamSusceptible to Link Farms (combated via trust seeds)Susceptible to topic drift during base set expansion

Vector Embeddings, Approximate Nearest Neighbors, and Probabilistic Indexing

  • Dense Word Embeddings:
    • Traditional vector space models use one-hot representations where words form orthogonal dimensions, missing semantic similarities (e.g., v(plane)⋅v(aircraft)=0\mathbf{v}(\text{plane}) \cdot \mathbf{v}(\text{aircraft}) = 0).
    • Grounded in J.R. Firth's distributional hypothesis (\"You shall know a word by the company it keeps\"), dense embeddings map words into continuous low-dimensional spaces (Rd\mathbb{R}^d, typically d∈[100,1024]d \in [100, 1024]).
    • Linear Vector Arithmetic: Geometric directions in the embedding space encode semantic and grammatical relationships:     v(king)−v(man)+v(woman)≈v(queen)\mathbf{v}(\text{king}) - \mathbf{v}(\text{man}) + \mathbf{v}(\text{woman}) \approx \mathbf{v}(\text{queen})v(Paris)−v(France)+v(Italy)≈v(Rome)\mathbf{v}(\text{Paris}) - \mathbf{v}(\text{France}) + \mathbf{v}(\text{Italy}) \approx \mathbf{v}(\text{Rome})

Vector Arithmetic Capturing Semantic and Grammatical Relationships

  • Primary Embedding Generation Paradigms:

    • Co-occurrence Matrices with SVD: Build a large term-term co-occurrence matrix and apply Singular Value Decomposition to extract the top dd singular vectors.

    • Word2vec: A shallow two-layer neural architecture trained on local context windows to predict context words given a target word (Skip-gram) or predict a target word from context (CBOW).

    • GloVe (Global Vectors): Combines local context windows with global matrix factorization by fitting log-bilinear dot products directly to global co-occurrence counts.

    • Gradient Descent Optimization:

  • An iterative optimization algorithm used to train neural embeddings and machine-learning models by minimizing an objective loss function L(θ)\mathcal{L}(\theta).

Gradient Descent 3D Convex Optimization Landscape

  • Parameter update rule moves in the opposite direction of the gradient:   θt+1=θt−η∇θL(θ)\theta_{t+1} = \theta_t - \eta \nabla_\theta \mathcal{L}(\theta)     Where η\eta is the learning rate, and ∇L\nabla \mathcal{L} is the vector of partial derivatives.

  • Approximate Nearest Neighbor (ANN) Search:

    • Exact nearest-neighbor (k-NN) search requires computing distances between the query vector and all NN items in the database, costing O(N⋅d)\mathcal{O}(N \cdot d) time. This becomes a severe bottleneck when searching millions of high-dimensional vectors (d≥512d \ge 512).
    • ANN algorithms sacrifice absolute accuracy to achieve fast sub-linear search times (O(log⁡(N))\mathcal{O}(\log(N))), using space-partitioning and graph-traversal techniques.
    • Voronoi Diagrams: Partition a metric space into regions surrounding seed points, where every point inside a region is closer to its seed than to any other.

Voronoi Space Partitions for Euclidean Distance versus Manhattan Distance

  • The Five Core ANN Algorithmic Strategies:
    1. Brute Force: Linear search across all vectors. Impractical for large CPU workloads, but highly effective on GPUs using SIMD parallelism when datasets fit within GPU VRAM.
    2. Tree-Based (e.g., ANNOY): Recursively splits the vector space using random hyperplanes to build a forest of binary search trees. Queries traverse the trees to collect candidate vectors from the leaf nodes, trading accuracy for search speed.
    3. Locality-Sensitive Hashing (LSH): Uses specialized hash functions where the collision probability is proportional to vector similarity:      dist(x,y)→0  ⟹  P(h(x)=h(y))→1\text{dist}(\mathbf{x}, \mathbf{y}) \to 0 \implies P(h(\mathbf{x}) = h(\mathbf{y})) \to 1      Hashes similar vectors into identical buckets, allowing queries to search only the vectors in matching buckets.
    4. Product Quantization (PQ): Deconstructs a high-dimensional vector into mm smaller sub-vectors, and clusters each sub-vector space into k∗k^* centroids using kk-means. Each sub-vector is replaced by the index of its nearest centroid, compressing the original vector into a compact array of byte identifiers. Distances to queries are approximated rapidly using precomputed lookup tables.
    5. Graph-Based (e.g., HNSW): Hierarchical Navigable Small World graphs organize vectors into a multi-layer graph hierarchy. Top layers contain coarse links for rapid routing across the space, while bottom layers contain dense graphs for fine-grained local searches, achieving search times of O(log⁡(N))\mathcal{O}(\log(N)).

HNSW Hierarchical Multi-Layer Coarse-to-Fine Graph Routing

  • Bloom Filters:
    • A space-efficient probabilistic data structure used to test set membership (x∈S\mathbf{x} \in S).

Bloom Filter Architecture and Database Disk Read Skipping

  • Structure: A bit array of mm bits (all initialized to 0) paired with kk independent uniform hash functions: h1,h2,…,hkh_1, h_2, \dots, h_k.

  • Insertion: For each element xx, compute h1(x),…,hk(x)h_1(x), \dots, h_k(x) and set those bit positions in the array to 11.

  • Lookup: Check bit positions h1(y),…,hk(y)h_1(y), \dots, h_k(y). If any position is 00, the element is definitely not in the set (zero false negatives). If all positions are 11, the element is probably in the set (false positives are possible due to hash collisions).

  • False Positive Rate: For nn inserted elements, the false-positive probability is:     P(FP)≈(1−e−kn/m)kP(\text{FP}) \approx \left( 1 - e^{-kn/m} \right)^k

  • Deletions: Standard Bloom filters do not support deletions because clearing a bit may destroy hash mappings for other elements. Deletions require variants like Counting Bloom Filters (which replace single bits with integer counters) or Cuckoo Filters.

    • Bit-Signature Indices (BitFunnel):
  • An alternative index architecture that replaces inverted lists with document-level Bloom filter signatures, used in search engines such as Microsoft Bing.

  • Document Signatures: Each document is converted into an mm-bit signature by hashing its terms across kk hash functions and setting the corresponding bits to 11.

  • Query Processing via Bit-Slicing:

    • Invert the physical layout: store signatures as bit slices (one row per bit position across all documents, where columns represent docIDs).
    • To process a query Brutus∧Caesar\text{Brutus} \land \text{Caesar}, generate the query's hash bits, retrieve only those specific bit slice rows from memory, and apply bitwise AND operations across the rows.
    • Processors evaluate 64 documents per instruction using standard registers, or hundreds per instruction using SIMD extensions, without needing to decompress postings lists.
  • Handling False Positives in Web Search:

    • BitFunnel yields false positives (documents that match the bit signature without containing the query terms), but zero false negatives.
    • In Web search, false positives are acceptable because downstream machine-learned rankers verify and score the candidate documents, pushing false matches down the ranked list without degrading top-KK results.

Questions & Discussion

  • Question: Is it possible to use a binary linear classifier (such as a Support Vector Machine trained on relevant vs. non-relevant labels) to produce a ranked retrieval result?

    • Response: Yes. A binary linear Support Vector Machine defines a continuous decision hyperplane: w⋅x+b=0\mathbf{w} \cdot \mathbf{x} + b = 0. Although the final classification threshold applies a sign function (sign(w⋅x+b)\text{sign}(\mathbf{w} \cdot \mathbf{x} + b)), the underlying signed distance from the vector to the decision boundary is given by:     dist(x)=w⋅x+b∥w∥\text{dist}(\mathbf{x}) = \frac{\mathbf{w} \cdot \mathbf{x} + b}{\|\mathbf{w}\|}     This signed distance provides a natural ranking metric: documents positioned deeper inside the positive, relevant half-space achieve higher scores, allowing the SVM to rank candidate results effectively.
  • Question: What is the formal difference between Document-at-a-Time (DAAT) and Term-at-a-Time (TAAT) postings list evaluation, and how do they impact system memory?

    • Response: In DAAT, the query engine advances through all postings lists for the query terms simultaneously. It computes the complete relevance score for one document before moving to the next. This requires very little working memory, as it only needs to maintain a small min-heap of the top-KK scores seen so far. However, DAAT requires all postings lists to be sorted in the same global order (such as by docID or a static quality score g(d)g(d)).   In TAAT, the query engine evaluates one query term's postings list completely before moving to the next term. It accumulates partial scores in an in-memory hash table across all candidate documents. This allows postings lists to use custom sorting orders (such as impact-ordering by term frequency tftf), but can consume large amounts of memory to store score accumulators for thousands of candidate documents.
  • Question: Why does Elias γ\gamma-coding compress small gaps better than Variable Byte (VB) encoding, and why is Variable Byte still widely preferred in production systems?

    • Response: Variable Byte encoding operates strictly on whole-byte boundaries. Its smallest possible value (G=1G = 1) still consumes an entire 8-bit byte. Elias γ\gamma-coding operates at the bit level, requiring 2⌊log⁡2(G)⌋+12 \lfloor \log_2(G) \rfloor + 1 bits, meaning a gap of G=1G = 1 takes only a single bit (0). However, modern CPU architectures are optimized to read and process byte-aligned memory. Decompressing bit-level γ\gamma-streams requires intensive bit-masking and bit-shifting operations, which create CPU bottlenecks. Variable Byte encoding offers much faster decompression speeds that outweigh its slightly larger index size in high-throughput production systems.
  • Question: Under what circumstances does the Rocchio relevance feedback algorithm degrade search performance?

    • Response: Rocchio feedback relies on two key assumptions that can fail in practice:
    1. The initial query must return at least some relevant documents. If the user's initial query is poor or misspelled, no relevant documents will be retrieved, leaving the system with no positive examples to learn from.
    2. The relevant documents must form a single, coherent cluster in vector space. If the information need covers multiple distinct topics or synonyms (such as documents referring to the same country as either \text{\"Burma\"} or \text{\"Myanmar\"}), the relevant documents will form separate, disjoint clusters. Rocchio computes a single centroid, which lands in the empty space between the clusters, shifting the revised query away from all relevant documents and degrading search results.