Algorithm Search⌘K

Algorithmcore

Single-pass in-memory indexing

Also called SPIMI.

Builds a separate dictionary and posting lists for each block in one pass with no global term ids, then merges the blocks.

Time
O(T log T) worstO(T + W log T) average
Space
O(T) diskO(M) memory
Counts
io O((T/B) (1 + log_(M/B) k)) worstio O(T/B) best
Where
B = the number of words in a disk block; M = the number of tokens that one block takes in; T = the number of tokens; W = the number of terms summed over all blocks; k = the number of blocks (the ceiling of T/M)
Properties
not comparison baseddeterministicnot in placeofflineiterativestable

Single-pass in-memory indexing (SPIMI) builds an inverted index for a collection larger than memory. It reads tokens into a hash table from terms to growing posting lists, and when memory is full it sorts the terms of the table, writes the table to disk as one block, and starts a new, empty table. A final k-way merge joins the blocks by term. It differs from blocked sort-based indexing in two ways. It has no global map from terms to integer ids, so the dictionary of the whole vocabulary never has to fit in memory. And it never sorts the (term, document) pairs: the postings of a term arrive in document order and are appended in place, so only the distinct terms of each block are sorted.

In plain words

Read the documents one by one. Keep a notebook in memory with one page for each word you have seen. When you meet a word, open its page and write the number of the current document at the end, or add one to its count if that number is already the last entry. The numbers on each page are in order without any extra work, because you read the documents in order. When the notebook is full, put its pages in alphabetical order, store it on a shelf, and take a new empty notebook. At the end, read all the notebooks on the shelf together, alphabet order in each, and join the pages of each word into one list.

The problem

The input is a collection of NN documents d1<d2<⋯<dNd_1 < d_2 < \cdots < d_N with TT tokens in total. The output is, for each term tt, the list of pairs (d,tft,d)(d, \mathrm{tf}_{t,d}) for the documents that contain tt, in increasing order of dd. Memory holds a block of MM tokens with its dictionary, much less than TT. The model is the external memory model, with disk blocks of BB words.

The algorithm

  1. SPIMI(D, M) ▷ D: documents in increasing id order, M ≥ 1
  2. 1blocks ← empty list, dict ← empty hash map, used ← 0
  3. 2for each document d of D, for each token w of d do
  4. 3if w is not in dict then dict[w] ← empty list
  5. 4P ← dict[w]
  6. 5if P is not empty and its last posting has id d then add 1 to its count
  7. 6else append (d, 1) to P
  8. 7used ← used + 1
  9. 8if used = M then add WRITE-BLOCK(dict) to blocks, dict ← empty hash map, used ← 0
  10. 9if dict is not empty then add WRITE-BLOCK(dict) to blocks
  11. 10return MERGE-BLOCKS(blocks)
  12. WRITE-BLOCK(dict)
  13. 11return the pairs (w, dict[w]) in increasing order of w ▷ one block, written to disk
  14. MERGE-BLOCKS(blocks)
  15. 12put the first entry of each block in a min-heap H, keyed by (term, block number)
  16. 13while H is not empty do
  17. 14remove the least entry (w, P) of H, and put the next entry of its block in H
  18. 15if the output ends with term w then join P to its list, adding counts if the first id of P equals the last id
  19. 16else output (w, P)
  20. 17return the output

Line L1 starts with an empty table. For each token, lines L3 and L4 find or create the posting list of its term. Because the documents come in increasing id order, the new posting is either for the same document as the last posting of the list, and line L5 adds 1 to the count, or for a later document, and line L6 appends it. In a real engine the list is a dynamic array that doubles when full, as in array doubling. Line L7 counts the memory used, here in tokens. When the block is full, line L8 writes it and starts a new one, and line L9 writes the last block.

WRITE-BLOCK sorts only the terms of the block, so the block on disk is in term order. This is the one sort of SPIMI. It is needed for the merge.

MERGE-BLOCKS takes the block entries in order of term, and for one term in order of block number, which is also the order of the documents. Line L15 joins the lists of one term. A block can end in the middle of a document, so the first posting of a later list can have the same id as the last posting of the list so far. Then the two counts are added.

Example

Take the toy collection of the information retrieval pages: 8 documents, 79 tokens, 50 distinct terms and 74 postings. With M=16M = 16 tokens per block, line L8 writes a block after tokens 16, 32, 48 and 64, and line L9 writes a fifth block with the last 15 tokens.

block tokens documents terms postings list of "sorted" list of "list"
1 1 to 16 1, 2 14 15 (1, 1), (2, 1)
2 17 to 32 2, 3, 4 13 16 (2, 1) (3, 1), (4, 1)
3 33 to 48 4, 5 15 16 (4, 1) (4, 1)
4 49 to 64 5, 6, 7 15 15
5 65 to 79 7, 8 14 15 (8, 1)

Document 2 has "sorted" at its tokens 5 and 9, which are tokens 14 and 18 of the stream, so the boundary after token 16 cuts it. The merge takes the lists of "sorted" from blocks 1, 2, 3 and 5 in that order. Line L16 starts the output with (1,1),(2,1)(1, 1), (2, 1). Block 2 gives (2,1)(2, 1), whose id equals the last id, so line L15 makes the last pair (2,2)(2, 2). Blocks 3 and 5 append (4,1)(4, 1) and (8,1)(8, 1). The list is (1,1),(2,2),(4,1),(8,1)(1, 1), (2, 2), (4, 1), (8, 1). In the same way, "list" in document 4 is cut between blocks 2 and 3 and ends as (3,1),(4,2)(3, 1), (4, 2).

The five blocks hold 71 terms, against 50 distinct terms in the collection, because common words such as "a" and "array" are in several blocks. They hold 77 postings, and the merge joins 3 of them, which leaves the 74 postings of the index. Blocked sort-based indexing with the same block size writes the same 77 entries, but it sorts 79 pairs in its blocks, while SPIMI sorts only the 71 block terms.

Correctness

Inside one block, the list of each term holds the documents of the block that contain the term, with their counts, in increasing order of id. This holds because the documents are read in increasing order and the tokens of one document are consecutive, so a new posting is either for the last document of the list or for a later one. Each block on disk is sorted by term. The merge takes the lists of one term in block order, so the ids keep increasing from one list to the next, and the only possible repeat is the one document that a block boundary cuts, where line L15 adds the counts. The sum over the blocks is the term frequency. The full proof is in the proof file below.

Proof: Single-pass in-memory indexing builds the same index as a direct in-memory buildfull

Let the input be documents (d1,w1),…,(dN,wN)(d_1, w_1), \ldots, (d_N, w_N) with d1<d2<⋯<dNd_1 < d_2 < \cdots < d_N, where wiw_i is the token sequence of did_i, and let T=∑i∣wi∣T = \sum_i |w_i|. The reference index RR maps each term tt that occurs in the collection to the list of pairs (d,tft,d)(d, \mathrm{tf}_{t,d}) with tft,d≥1\mathrm{tf}_{t,d} \ge 1, in increasing order of dd. We show that SPIMI with any block size M≥1M \ge 1 returns RR.

  1. The blocks cut the token stream into pieces. Let SS be the sequence of (term, document) pairs of the tokens in reading order. Lines L7 and L8 count the tokens of the current block and write the block after every MM tokens; line L9 writes the last block if it is not empty. So the blocks correspond to consecutive pieces S1,…,SkS_1, \ldots, S_k of SS with S=S1S2⋯SkS = S_1 S_2 \cdots S_k.

  2. Invariant of one block. While a block is open, the dictionary holds, for each term tt that occurs in the part of the current piece read so far, a list of pairs (d,c)(d, c) in strictly increasing order of dd, where c≥1c \ge 1 is the number of tokens of tt in document dd inside this piece so far. The invariant holds for the empty dictionary. Take one more token ww of document dd. If ww is new, line L3 adds an empty list. Because documents are read in increasing order and the tokens of one document are consecutive, every pair already in the list of ww has an id at most dd, and only the last one can equal dd. If it does, line L5 adds 1 to its count. Else line L6 appends (d,1)(d, 1), which keeps the ids strictly increasing. Lists of other terms do not change. So the invariant holds after the token.

  3. Each written block is sorted and correct for its piece. Line L11 lists the terms of the dictionary in sorted order with their lists. By step 2, block ii holds, for each term tt of piece SiS_i, the list of (d,ci(t,d))(d, c_i(t, d)) with ci(t,d)c_i(t, d) the number of tokens of tt in dd inside SiS_i, in increasing order of dd.

  4. Document ranges of the blocks. Every document id of block ii is at most every document id of block i+1i + 1, because the pieces follow the reading order. Equality holds only for the one document that the boundary between SiS_i and Si+1S_{i+1} cuts, and that id is the last id of block ii and the first id of block i+1i + 1.

  5. The merge order. The heap of lines L12 to L14 holds at most one entry of each block, keyed by (term, block number). Each block is sorted by term, so this is a kk-way merge, and line L14 takes the entries of all blocks in increasing order of term, and for one term in increasing order of block number.

  6. Lines L15 and L16 build the list of each term. For a fixed term tt, let i1<i2<⋯<iri_1 < i_2 < \cdots < i_r be the blocks that contain tt. The first entry starts the output list of tt at line L16. Each later entry of block iji_j is joined to the output list at line L15. By step 4, the ids of the list from block iji_j are at least the last id already in the output list. Only the first of them can be equal to it, and only when the blocks between share one document that block boundaries cut. In that case the first pair has the same id as the last output pair and line L15 adds the counts. Else all ids are larger and the list is appended. So after the last block, the output list of tt is strictly increasing in dd, and the count for dd is ∑ici(t,d)\sum_i c_i(t, d), the number of tokens of tt in dd over all pieces, which is tft,d\mathrm{tf}_{t,d}.

  7. Conclusion. Every term of the collection occurs in some block and so gets an output list, and no other term does. With step 6, line L17 returns RR. ■\blacksquare

A document with more than MM tokens can span more than two blocks. The argument covers this case: each join adds the count of one more block to the same last pair, and a block in the middle that does not contain tt changes nothing.

Complexity

  • Inversion. Lines L2 to L8 do O(1)O(1) expected work for each token with a hash table, so O(T)O(T) expected time in total. Manning, Raghavan and Schuetze give Θ(T)\Theta(T) for SPIMI for this reason.
  • Sort of the block terms. A block with vv distinct terms costs O(vlog⁡v)O(v \log v) to sort, with v≤Mv \le M. Over all blocks this is O(Wlog⁡M)O(W \log M), where WW is the number of terms summed over the blocks.
  • Merge. The heap has at most kk entries, so the merge costs O(Wlog⁡k)O(W \log k) for the heap and O(T)O(T) to join the lists. With log⁡M+log⁡k=O(log⁡T)\log M + \log k = O(\log T), the total is O(T+Wlog⁡T)O(T + W \log T) expected, and W≤TW \le T gives O(Tlog⁡T)O(T \log T) in the worst case.
  • Disk transfers. Each block is written once and read once by the merge, so O(T/B)O(T/B) transfers when the kk blocks fit one merge pass, that is k≤M/Bk \le M/B. With more blocks the merge takes several passes, as in external merge sort.
  • Memory. One block: the table and its lists, O(M)O(M) words.

Properties

  • No global dictionary. Each block has its own dictionary, and the merge compares term strings. Memory does not depend on the size of the vocabulary of the whole collection.
  • Postings stay in document order. No sort of postings is needed, inside a block or in the merge.
  • One pass over the collection. The collection is read once. The merge then reads each block once.
  • Deterministic. The index does not depend on MM; only the blocks do.

Variants and improvements

  • Compressed blocks. The terms of a block can be stored with front coding and the lists as gaps with a variable-length code, which makes each block smaller and lets more tokens fit in memory. See postings gap encoding.
  • Memory in bytes. Real engines stop a block when the bytes used reach a limit, not after a fixed number of tokens. This changes the block boundaries but not the result.
  • Merge-based construction. Buettcher, Clarke and Cormack describe the same idea as in-memory construction for each part of the collection followed by a merge of the partial indexes. Heinz and Zobel describe a single-pass method of this kind with a careful in-memory structure.
  • Distributed indexing. The parsers of a MapReduce job can each run SPIMI on their part of the collection, and the inverters merge by term range. See index partitioning.
  • Dynamic indexes. The in-memory block of SPIMI is also the auxiliary index of logarithmic merging and geometric partitioning, which merge the blocks while new documents arrive.

When to use it

Use SPIMI to build an index for a static collection that does not fit in memory, in particular when the vocabulary is large or unbounded, as in web text with many rare tokens. Use blocked sort-based indexing when a global integer id per term is needed for other reasons and the vocabulary fits in memory. For a collection that grows, use SPIMI for each in-memory block and a merge policy from dynamic index maintenance.

Pitfalls

  • Documents out of order. Lines L5 and L6 assume that the documents arrive in increasing id order. With documents in any other order, line L6 appends ids out of order and the lists are not sorted. Feed the documents in id order, or give them ids in the order they are read.
  • Merge order of equal terms. The heap of line L12 must break ties between equal terms by block number. If it takes the lists of one term in any other order, the ids of the joined list are not increasing.
  • No join for a cut document. If line L15 appends the list without the test on the first id, a document cut by a block boundary gets two postings. In the example, "sorted" would hold (2,1)(2, 1) twice in place of (2,2)(2, 2).
  • Writing the block without sorting. If WRITE-BLOCK writes the terms in hash table order in place of line L11, the merge cannot work in one pass, because the blocks are no longer sorted by the merge key.
  • Counting memory in postings only. A block with many new terms uses memory for the dictionary entries too. An engine that limits only the number of postings can run out of memory on a block with many rare terms.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

irtoy.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.

Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""

DOCS = {
    1: "binary search finds a key in a sorted array",
    2: "merge sort merges two sorted runs into one sorted array",
    3: "an inverted index maps each term to a posting list",
    4: "a posting list is a sorted list of document ids",
    5: "skip pointers speed up the merge of two posting lists",
    6: "a hash table finds a key in constant expected time",
    7: "search engines rank documents by a score for the query",
    8: "the sorted array of ids is compressed with gap encoding",
}

N = len(DOCS)

QUERIES = {
    "q1": "sorted array search",
    "q2": "posting list merge",
    "q3": "rank documents",
    "q4": "quantum circuit",
}

# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
    "q1": {1: 2, 2: 1, 8: 1},
    "q2": {5: 2, 4: 1, 3: 1},
    "q3": {7: 2},
    "q4": {},
}

# A fixed run for the metric pages, as scores per query.
RUN = {
    "q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}


def tokenize(text):
    """Lower-case words split on spaces."""
    return text.lower().split()


_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}


def tf(term, doc_id):
    """Number of times term occurs in document doc_id."""
    return _TOKENS[doc_id].count(term)


def df(term):
    """Number of documents that contain term."""
    return sum(1 for toks in _TOKENS.values() if term in toks)


def cf(term):
    """Number of occurrences of term in the whole collection."""
    return sum(toks.count(term) for toks in _TOKENS.values())


def doc_len(doc_id):
    """Number of tokens in document doc_id."""
    return len(_TOKENS[doc_id])


def avgdl():
    """Average document length in tokens."""
    return sum(len(toks) for toks in _TOKENS.values()) / N
single_pass_in_memory_indexing.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-pass-in-memory-indexing/. The authors are listed in prov/8P8GD3.jsonl.

import heapq
from typing import Iterable

Postings = list[tuple[int, int]]  # (document id, term frequency), increasing ids
Block = list[tuple[str, Postings]]  # (term, postings), increasing terms


def write_block(dictionary: dict[str, Postings]) -> Block:
    """Sort the terms of one block and return the block as it goes to disk. Cost O(v log v) for v terms."""
    return [(w, dictionary[w]) for w in sorted(dictionary)]  # @line L11


def merge_blocks(blocks: list[Block]) -> dict[str, Postings]:
    """Merge blocks by term with a min-heap keyed on (term, block number).

    The lists of one term come out in block order, which is document order.
    If a block boundary cut a document, the first posting of the later list
    has the same id as the last posting of the earlier one, and the two
    frequencies are added. Cost O(v log k + P) for v block terms, k blocks and
    P postings.
    """
    heap: list[tuple[str, int, int]] = []
    for i, block in enumerate(blocks):  # @line L12
        if block:
            heap.append((block[0][0], i, 0))
    heapq.heapify(heap)
    out: list[tuple[str, Postings]] = []
    while heap:  # @line L13
        w, i, pos = heapq.heappop(heap)  # @line L14
        if pos + 1 < len(blocks[i]):
            heapq.heappush(heap, (blocks[i][pos + 1][0], i, pos + 1))
        plist = blocks[i][pos][1]
        if out and out[-1][0] == w:  # @line L15
            acc = out[-1][1]
            start = 0
            if acc[-1][0] == plist[0][0]:
                acc[-1] = (acc[-1][0], acc[-1][1] + plist[0][1])
                start = 1
            acc.extend(plist[start:])
        else:
            out.append((w, list(plist)))  # @line L16
    return dict(out)  # @line L17


def spimi(docs: Iterable[tuple[int, list[str]]], block_size: int) -> tuple[dict[str, Postings], list[Block]]:
    """Single-pass in-memory indexing.

    docs gives (doc id, tokens) in strictly increasing doc id order. block_size
    is M, the number of tokens that one block may take in before it is written,
    M >= 1. Returns the index (term -> list of (doc id, tf)) and the blocks that
    the merge read. Cost O(T) expected time for the inversion of T tokens, plus
    the sort of the terms of each block and the merge.
    """
    if block_size < 1:
        raise ValueError("block_size must be at least 1")
    blocks: list[Block] = []  # @line L1
    dictionary: dict[str, Postings] = {}
    used = 0
    for d, tokens in docs:  # @line L2
        for w in tokens:
            if w not in dictionary:  # @line L3
                dictionary[w] = []
            plist = dictionary[w]  # @line L4
            if plist and plist[-1][0] == d:  # @line L5
                plist[-1] = (d, plist[-1][1] + 1)
            else:
                plist.append((d, 1))  # @line L6
            used += 1  # @line L7
            if used == block_size:  # @line L8
                blocks.append(write_block(dictionary))
                dictionary = {}
                used = 0
    if dictionary:  # @line L9
        blocks.append(write_block(dictionary))
    return merge_blocks(blocks), blocks  # @line L10
test_single_pass_in_memory_indexing.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/single-pass-in-memory-indexing/. The authors are listed in prov/8P8GD3.jsonl.

import math
import random

import irtoy
from single_pass_in_memory_indexing import merge_blocks, spimi


def direct_index(docs: list[tuple[int, list[str]]]) -> dict[str, list[tuple[int, int]]]:
    """The reference: one dictionary of dictionaries, built in memory."""
    m: dict[str, dict[int, int]] = {}
    for d, tokens in docs:
        for w in tokens:
            m.setdefault(w, {})
            m[w][d] = m[w].get(d, 0) + 1
    return {w: sorted(p.items()) for w, p in m.items()}


def toy_docs() -> list[tuple[int, list[str]]]:
    return [(d, irtoy.tokenize(t)) for d, t in sorted(irtoy.DOCS.items())]


def check_blocks(blocks, tokens: int, m: int) -> None:
    assert len(blocks) == math.ceil(tokens / m)
    for block in blocks:
        terms = [w for w, _ in block]
        assert terms == sorted(set(terms))
        used = 0
        for _, plist in block:
            ids = [d for d, _ in plist]
            assert ids == sorted(set(ids))
            used += sum(f for _, f in plist)
        assert used <= m


def test_toy_collection_block_16() -> None:
    docs = toy_docs()
    index, blocks = spimi(docs, 16)
    assert index == direct_index(docs)
    assert [len(b) for b in blocks] == [14, 13, 15, 15, 14]
    assert [sum(len(p) for _, p in b) for b in blocks] == [15, 16, 16, 15, 15]
    assert dict(blocks[0])["sorted"] == [(1, 1), (2, 1)]
    assert dict(blocks[1])["sorted"] == [(2, 1)]
    assert index["sorted"] == [(1, 1), (2, 2), (4, 1), (8, 1)]
    assert index["list"] == [(3, 1), (4, 2)]
    check_blocks(blocks, 79, 16)


def test_toy_collection_every_block_size() -> None:
    docs = toy_docs()
    want = direct_index(docs)
    for m in range(1, 90):
        index, blocks = spimi(docs, m)
        assert index == want
        check_blocks(blocks, 79, m)


def test_merge_joins_cut_document() -> None:
    blocks = [[("x", [(1, 1), (2, 1)])], [("w", [(2, 1)]), ("x", [(2, 3), (5, 1)])]]
    assert merge_blocks(blocks) == {"w": [(2, 1)], "x": [(1, 1), (2, 4), (5, 1)]}
    assert blocks[0][0][1] == [(1, 1), (2, 1)]


def test_edge_cases() -> None:
    assert spimi([], 2) == ({}, [])
    assert spimi([(1, []), (3, [])], 2) == ({}, [])
    index, blocks = spimi([(7, ["y", "y", "y"])], 1)
    assert index == {"y": [(7, 3)]} and len(blocks) == 3
    try:
        spimi([(1, ["y"])], 0)
    except ValueError:
        pass
    else:
        raise AssertionError("block size 0 was accepted")


def test_random_collections() -> None:
    rng = random.Random(20261116)
    for _ in range(600):
        vocab = [f"w{i}" for i in range(rng.randint(1, 30))]
        docs = []
        d = 0
        for _ in range(rng.randint(0, 12)):
            d += rng.randint(1, 4)
            docs.append((d, [rng.choice(vocab) for _ in range(rng.randint(0, 15))]))
        tokens = sum(len(t) for _, t in docs)
        m = rng.randint(1, 12)
        index, blocks = spimi(docs, m)
        assert index == direct_index(docs)
        check_blocks(blocks, tokens, m)

History

Manning, Raghavan and Schuetze presented SPIMI in their 2008 textbook as the scalable alternative to blocked sort-based indexing. They credit the method to Heinz and Zobel, whose 2003 paper describes single-pass construction with in-memory partial indexes and a final merge. Buettcher, Clarke and Cormack describe the same scheme as merge-based index construction.

References

  1. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 4, Section 4.3 (single-pass in-memory indexing, the SPIMI-INVERT pseudocode), with Section 4.2 for the merge of the blocks
  2. Stefan Buettcher, Charles L. A. Clarke and Gordon V. Cormack, Information Retrieval, Implementing and Evaluating Search Engines, MIT Press, 2010, Chapter 4, Section 4.5.1 (in-memory index construction) and Section 4.5.3 (merge-based index construction)
  3. Efficient single-pass index construction for text databases, the single-pass construction with in-memory partial indexes and a final merge
  4. Justin Zobel and Alistair Moffat, Inverted files for text search engines, ACM Computing Surveys 38(2), Article 6, 2006, the section on index construction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.worst
  • a full proof of space.disk
  • a full proof of space.memory
  • a full proof of io.best
  • a full proof of io.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example