Algorithm Search⌘K

Algorithmcore

Logarithmic merging

Also called logarithmic index merging.

Keeps indexes of sizes n, 2n, 4n and so on, and merges two of equal size like a binary counter, so each posting is merged O(log(T/n)) times.

Time
Θ(T log(T/n)) buildO(log(T/n)) indexes_per_queryO(log(T/n)) amortized insert
Space
O(T) diskO(n) memory
Where
T = the number of postings added so far; n = the number of postings that the in-memory index holds
Properties
comparison baseddeterministicnot in placeonlineiterative

Logarithmic merging keeps an inverted index up to date while new documents arrive. New postings go into a small index in memory. When it holds nn postings it goes to disk, and the disk indexes are kept at sizes n,2n,4n,…n, 2n, 4n, \ldots, at most one of each size. When two indexes of the same size exist, they are merged into one of double size, in the same way that adding 1 to a binary counter turns two 1 bits into a carry. Each posting is then merged at most ⌊log⁡2(T/n)⌋\lfloor \log_2(T/n) \rfloor times in total, in place of up to T/nT/n times with one auxiliary index. It is the static-to-dynamic method of the decomposable searching problem applied to posting lists. The log-structured merge tree applies the same idea to key-value stores, with a fixed size ratio between levels. Geometric partitioning uses other ratios and limits the number of indexes. This page covers the scheme with ratio 2, in the form of Manning, Raghavan and Schuetze.

In plain words

Think of a pile of sorted card boxes. New cards go into a small box on your desk. When the desk box is full, you put it on the shelf. If the shelf already has a box of the same size, you do not keep two: you merge them into one box of double size. If a box of that new size is also there, you merge again, and so on. So the shelf never has two boxes of the same size. A card is merged again only when its box doubles, so it is merged only a few times, even when the collection grows very large. A search must look in each box on the shelf, but there are only a few boxes.

The problem

Postings arrive one at a time, in any order of terms. After each arrival, a query for a term must return its full posting list over all postings so far. The work to measure is the number of postings that merges write to disk. The simple scheme with one main index and one auxiliary index of nn postings in memory merges the auxiliary index into the main index each time it is full. Then the main index is rewritten at each flush, and building an index of TT postings costs Θ(T2/n)\Theta(T^2/n) postings written. The goal is to cut this cost, and to keep the number of indexes that a query reads small. The general problem, with deletions, is dynamic index maintenance.

The algorithm

Z0Z_0 is the index in memory, with room for nn postings. I0,I1,…I_0, I_1, \ldots are the indexes on disk, and IiI_i, when it exists, has exactly 2in2^i n postings. MERGE joins two indexes into one, list by list, as a k-way merge with k=2k = 2.

  1. LMERGE-ADD(x) ▷ x: one new posting
  2. 1Z0 ← MERGE(Z0, {x}) ▷ in memory
  3. 2if |Z0| = n then
  4. 3Z ← Z0, i ← 0
  5. 4while I_i exists do
  6. 5Z ← MERGE(I_i, Z), delete I_i ▷ now |Z| = 2^(i+1) n
  7. 6i ← i + 1
  8. 7I_i ← Z, Z0 ← empty ▷ written to disk
  9. QUERY(t)
  10. 8read the list of t from Z0 and from each I_i that exists
  11. 9return the union of these lists, in increasing document id order

Line L1 adds the posting to the in-memory index. When Z0Z_0 is full (line L2), lines L3 to L6 carry it up the levels. At level ii, if IiI_i exists, line L5 merges it with the carry, which doubles the size, and deletes it. Line L7 stores the carry at the first free level. This is the binary counter: the existing levels are the 1 bits of the number of flushes so far, and a flush clears the trailing 1 bits and sets the next 0 bit. Lines L8 and L9 answer a query from all indexes. The indexes hold disjoint sets of postings, so the union is the full list.

Example

Take n=4n = 4 and add 32 postings, so that Z0Z_0 is flushed 8 times. The table shows the levels after each flush and the number of postings that the merges of line L5 write in that flush.

flush tt tt in binary levels after the flush merges at line L5 postings written by merges
1 1 I0I_0 none 0
2 10 I1I_1 I0I_0 8
3 11 I0,I1I_0, I_1 none 0
4 100 I2I_2 I0I_0, I1I_1 8 + 16 = 24
5 101 I0,I2I_0, I_2 none 0
6 110 I1,I2I_1, I_2 I0I_0 8
7 111 I0,I1,I2I_0, I_1, I_2 none 0
8 1000 I3I_3 I0I_0, I1I_1, I2I_2 8 + 16 + 32 = 56

The merges write 96 postings in total. That is Tlog⁡2(T/n)=32⋅3T \log_2(T/n) = 32 \cdot 3: each of the 32 postings is merged exactly 3 times, once at each doubling from 4 to 32. With one auxiliary index, flush t≥2t \ge 2 rewrites the main index of 4t4t postings, which costs 4⋅(2+3+⋯+8)=1404 \cdot (2 + 3 + \cdots + 8) = 140 postings. The gap grows with TT: at 1,024 flushes of the same nn, logarithmic merging writes 4⋅1024⋅10=40,9604 \cdot 1024 \cdot 10 = 40{,}960 postings, while the auxiliary scheme writes 4⋅(1024⋅1025/2−1)=2,099,1964 \cdot (1024 \cdot 1025/2 - 1) = 2{,}099{,}196. Right after flush 7, a query reads three disk indexes; right after flush 8 it reads one.

Correctness

The proof keeps three statements true after each call. Z0Z_0 holds T mod nT \bmod n postings. The level IiI_i exists exactly when bit ii of ⌊T/n⌋\lfloor T/n \rfloor is 1, and then it holds 2in2^i n postings. And Z0Z_0 and the levels hold disjoint sets whose union is all postings added so far. A call that does not fill Z0Z_0 keeps all three. A call that fills Z0Z_0 carries through the trailing 1 bits of the flush count: the loop keeps ∣Z∣=2in|Z| = 2^i n and moves the postings of each merged level into ZZ, then line L7 sets the first 0 bit. So no posting is lost or copied, and a query that takes the union of all levels is correct. The full proof, with the count of merges, is in the proof file below.

Proof: Logarithmic merging keeps all postings, follows a binary counter, and merges each posting at most log2(T/n) timesfull

Fix the capacity n≥1n \ge 1. Let TT be the number of postings added so far, all distinct, and let XX be the set of these postings. Write T=qn+sT = qn + s with 0≤s<n0 \le s < n, and let q=∑ibi2iq = \sum_i b_i 2^i be the binary form of qq. An index is a sorted list of postings, and MERGE of two disjoint sorted lists returns the sorted list of their union. We show that after each call of LMERGE-ADD the following holds.

(I1) Z0Z_0 holds exactly ss postings.

(I2) IiI_i exists if and only if bi=1b_i = 1, and then ∣Ii∣=2in|I_i| = 2^i n.

(I3) Z0Z_0 and the indexes IiI_i that exist are pairwise disjoint, and their union is XX.

  1. Base. Before the first call, T=0T = 0, Z0Z_0 is empty and no IiI_i exists. All three statements hold.

  2. A call that does not fill Z0Z_0. Suppose the statements hold before the call that adds posting xx, with T=qn+sT = qn + s. Line L1 adds xx to Z0Z_0. If s+1<ns + 1 < n, the test of line L2 fails and nothing else changes. Now T+1=qn+(s+1)T + 1 = qn + (s + 1), so (I1) holds with s+1s + 1, (I2) is unchanged because qq is unchanged, and (I3) holds because xx is new and is now in Z0Z_0.

  3. A call that fills Z0Z_0. Else s+1=ns + 1 = n, so T+1=(q+1)nT + 1 = (q + 1) n. Let cc be the number of trailing 1 bits of qq, so b0=⋯=bc−1=1b_0 = \cdots = b_{c-1} = 1 and bc=0b_c = 0. By (I2), I0,…,Ic−1I_0, \ldots, I_{c-1} exist and IcI_c does not. The loop of lines L4 to L6 keeps the statement

    (L) at the start of a step with index ii, ∣Z∣=2in|Z| = 2^i n, the set ZZ is the union of the old Z0Z_0 with xx and of I0,…,Ii−1I_0, \ldots, I_{i-1}, and I0,…,Ii−1I_0, \ldots, I_{i-1} no longer exist.

    It holds at i=0i = 0 after line L3, since ∣Z0∣=n|Z_0| = n. If IiI_i exists, line L5 merges it into ZZ, which gives ∣Z∣=2in+2in=2i+1n|Z| = 2^i n + 2^i n = 2^{i+1} n, and deletes it. So (L) holds for i+1i + 1. The loop runs for i=0,…,c−1i = 0, \ldots, c-1 and stops at i=ci = c, where IcI_c does not exist. Line L7 stores ZZ as IcI_c with ∣Ic∣=2cn|I_c| = 2^c n, and empties Z0Z_0. In binary, q+1q + 1 has b0=⋯=bc−1=0b_0 = \cdots = b_{c-1} = 0, bc=1b_c = 1, and the same higher bits as qq. The indexes now present are exactly those of the bits of q+1q + 1, with the sizes of (I2). Z0Z_0 is empty, which is (I1) with s=0s = 0. No posting was lost or copied: each merge moves the postings of IiI_i into ZZ, and ZZ becomes IcI_c. So (I3) holds.

  4. Queries. By (I3), the posting list of a term tt in XX is the union of the lists of tt in Z0Z_0 and in each IiI_i that exists, and these lists are disjoint. Lines L8 and L9 return this union in document order, so the query is correct.

  5. Each merge doubles the index that holds a posting. A posting pp starts in Z0Z_0, which has nn postings when it is first merged. By step 3, pp takes part in a merge only at line L5, where it is in ZZ or in IiI_i, both of size 2in2^i n, and the result has size 2i+1n2^{i+1} n. After that merge, pp is in ZZ for the rest of the loop and then in IcI_c, of size 2cn2^c n, and the next merge of pp, in a later call, again starts from an index of the size that pp is in. So after jj merges, pp is in an index of 2jn2^j n postings. That index is a subset of XX, so 2jn≤T2^j n \le T, which gives j≤log⁡2(T/n)j \le \log_2(T/n). Since jj is an integer, j≤⌊log⁡2(T/n)⌋j \le \lfloor \log_2(T/n) \rfloor when T≥nT \ge n, and j=0j = 0 when T<nT < n.

  6. Total merge work. In the call that completes the tt-th flush, q=t−1q = t - 1 before the call, and the number cc of trailing 1 bits of t−1t - 1 is the number of trailing 0 bits of tt. The merges of that call write ∑i=0c−12i+1n=(2c+1−2)n\sum_{i=0}^{c-1} 2^{i+1} n = (2^{c+1} - 2) n postings. Summed over all postings, step 5 bounds the total by T⌊log⁡2(T/n)⌋T \lfloor \log_2(T/n) \rfloor. When T=2mnT = 2^m n, the sum of (2c+1−2)n(2^{c+1} - 2) n over t=1,…,2mt = 1, \ldots, 2^m is exactly m2mn=Tlog⁡2(T/n)m 2^m n = T \log_2(T/n): each of the 2mn2^m n postings is merged exactly mm times, since all of them end in the single index ImI_m. ■\blacksquare

Complexity

  • Merges for one posting. Each merge that a posting takes part in doubles the size of the index that holds it, from nn up to at most TT. So a posting is merged at most ⌊log⁡2(T/n)⌋\lfloor \log_2(T/n) \rfloor times. Manning, Raghavan and Schuetze state this as O(log⁡(T/n))O(\log(T/n)) merges for each posting.
  • Total merge work. Summed over the postings, the merges write at most T⌊log⁡2(T/n)⌋T \lfloor \log_2(T/n) \rfloor postings, so the build costs Θ(Tlog⁡(T/n))\Theta(T \log(T/n)), against Θ(T2/n)\Theta(T^2/n) for one auxiliary index. When T=2mnT = 2^m n the count is exactly mTmT. The amortized cost of one insertion is O(log⁡(T/n))O(\log(T/n)) postings written.
  • Worst case for one insertion. One flush can merge every level, which writes up to 2T2T postings. The bound is amortized, not a worst case per insertion.
  • Queries. A query reads Z0Z_0 and up to ⌊log⁡2(T/n)⌋+1\lfloor \log_2(T/n) \rfloor + 1 disk indexes, in place of 2 with one auxiliary index. This is the price of the cheaper merges.
  • Space. O(n)O(n) words of memory, and O(T)O(T) words of disk. During a carry, the old levels and the new one exist at the same time, so the disk can briefly hold up to twice the index.

Properties

  • Online. Each posting is visible to queries right after LMERGE-ADD returns.
  • Deterministic. The levels present depend only on ⌊T/n⌋\lfloor T/n \rfloor.
  • Sequential disk access. Each merge reads two sorted indexes from start to end and writes one.
  • Ratio 2. The size of each level is twice the size of the level below. With ratio rr, both the merge cost and the number of levels change, which is what geometric partitioning studies.

Variants and improvements

  • Geometric partitioning. Lester, Moffat and Zobel allow up to r−1r - 1 indexes per level for a ratio rr, and merge many of them in one multiway merge. A fixed bound on the number of indexes is also possible. See geometric partitioning.
  • One multiway merge per carry. In LMERGE-ADD, a carry through levels 0,…,c−10, \ldots, c-1 writes (2c+1−2)n(2^{c+1} - 2) n postings in a chain of pairwise merges. A single merge of Z0Z_0 and all these levels writes only 2cn2^c n. The example would then write 64 postings, not 96.
  • Deletions. A deleted document goes into an invalidation bit vector that queries filter against. The postings are removed when the merges rewrite their index, or by garbage collection. Buettcher, Clarke and Cormack discuss both methods.
  • Logarithmic method in general. Bentley and Saxe show the same transformation for any decomposable searching problem: a static structure that can be built in time P(n)P(n) becomes a dynamic one with amortized insertion cost O((P(n)/n)log⁡n)O((P(n)/n) \log n) and queries over O(log⁡n)O(\log n) structures.
  • Log-structured merge trees. Key-value stores keep levels with a fixed size ratio, often 10, and merge a level into the next one when it is full. See log-structured merge tree.

When to use it

Use logarithmic merging when documents arrive all the time and must be searchable soon, and when the cost of rebuilding or remerging the whole index at each flush is too high. It suits collections that grow by orders of magnitude. If queries are much more frequent than updates, the many indexes slow each query, so a scheme with fewer indexes, or a periodic full merge in the background, can be better. For a static collection, build the index once with single-pass in-memory indexing or blocked sort-based indexing.

Pitfalls

  • Wrong bound. The bound is O(log⁡(T/n))O(\log(T/n)) merges for each posting, not O(log⁡T)O(\log T). With T=nT = n there is no merge at all. The difference matters when nn is large, as it is in practice.
  • Merge without deleting the old level. If line L5 forgets to delete IiI_i, a query reads the postings of IiI_i twice, once in IiI_i and once in the new level. The level must be deleted after the merge, as in line L5.
  • Merge at the wrong level. Merging Z0Z_0 always into the largest level in place of the carry of lines L4 to L6 gives back the auxiliary scheme with its Θ(T2/n)\Theta(T^2/n) cost.
  • Collection statistics. A score such as BM25 needs the document frequency of a term over the whole collection. Each level only knows its own part, so the engine must add the counts over all levels, or keep the statistics in a separate global table.
  • Burst of work. One flush can rewrite the whole index. A system that must answer queries during updates needs to run the merge in the background, and to keep the old levels readable until the new one is complete.

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.

logarithmic_merging.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/logarithmic-merging/. The authors are listed in prov/GRDTV2.jsonl.

import bisect
from typing import Any

Posting = tuple[Any, int, int]  # (term, document id, term frequency)


def merge(a: list[Posting], b: list[Posting]) -> list[Posting]:
    """Merge two lists of postings sorted by (term, doc id) into one sorted list. Cost O(|a| + |b|)."""
    out: list[Posting] = []
    i = j = 0
    while i < len(a) and j < len(b):
        if a[i] < b[j]:
            out.append(a[i])
            i += 1
        else:
            out.append(b[j])
            j += 1
    out.extend(a[i:])
    out.extend(b[j:])
    return out


class LogarithmicIndex:
    """An index that takes postings one at a time and keeps them in an in-memory
    index Z0 of at most n postings and disk indexes I_0, I_1, ..., where I_i, when
    it exists, holds exactly 2^i n postings.

    Each index is a list of postings sorted by (term, doc id). The postings must
    be distinct. The counter merge_count[p] is the number of merges in which
    posting p took part, and merged is the total number of postings that all
    merges wrote.
    """

    def __init__(self, n: int) -> None:
        if n < 1:
            raise ValueError("the capacity n must be at least 1")
        self.n = n
        self.z0: list[Posting] = []
        self.levels: list[list[Posting] | None] = []  # levels[i] is I_i or None
        self.merge_count: dict[Posting, int] = {}
        self.merged = 0

    def add(self, x: Posting) -> None:
        """Insert one posting. Cost O(n) for the in-memory insert, plus the merges of a carry."""
        bisect.insort(self.z0, x)  # @line L1
        self.merge_count[x] = 0
        if len(self.z0) == self.n:  # @line L2
            z, i = self.z0, 0  # @line L3
            while i < len(self.levels) and self.levels[i] is not None:  # @line L4
                z = merge(self.levels[i], z)  # @line L5
                self.levels[i] = None
                self.merged += len(z)
                for p in z:
                    self.merge_count[p] += 1
                i += 1  # @line L6
            if i == len(self.levels):  # @line L7
                self.levels.append(None)
            self.levels[i] = z
            self.z0 = []

    def postings(self, term: Any) -> list[tuple[int, int]]:
        """The posting list of term: the union over Z0 and every I_i, sorted by doc id.

        Cost O(k log P + r log r) with k = number of indexes, P their size and r the answer size.
        """
        out: list[tuple[int, int]] = []
        for part in [self.z0] + [lv for lv in self.levels if lv is not None]:  # @line L8
            lo = bisect.bisect_left(part, (term,))
            while lo < len(part) and part[lo][0] == term:
                out.append((part[lo][1], part[lo][2]))
                lo += 1
        out.sort()
        return out  # @line L9

    def all_postings(self) -> list[Posting]:
        """Every posting held, in sorted order."""
        out = list(self.z0)
        for lv in self.levels:
            if lv is not None:
                out.extend(lv)
        out.sort()
        return out

    def check_invariant(self) -> None:
        assert len(self.z0) < self.n and self.z0 == sorted(self.z0)
        for i, lv in enumerate(self.levels):
            if lv is not None:
                assert len(lv) == (2 ** i) * self.n and lv == sorted(lv)
test_logarithmic_merging.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/logarithmic-merging/. The authors are listed in prov/GRDTV2.jsonl.

import random

from logarithmic_merging import LogarithmicIndex, merge


def random_postings(rng: random.Random, docs: int, vocab: int) -> list[tuple[str, int, int]]:
    """Postings of a random collection, document by document, as a stream to index."""
    out = []
    for d in range(1, docs + 1):
        terms = rng.sample(range(vocab), rng.randint(0, min(vocab, 6)))
        for t in terms:
            out.append((f"t{t}", d, rng.randint(1, 3)))
    return out


def direct(postings: list[tuple[str, int, int]]) -> dict[str, list[tuple[int, int]]]:
    m: dict[str, list[tuple[int, int]]] = {}
    for t, d, f in postings:
        m.setdefault(t, []).append((d, f))
    return {t: sorted(p) for t, p in m.items()}


def floor_log2(x: int) -> int:
    return x.bit_length() - 1


def trailing_zeros(x: int) -> int:
    return (x & -x).bit_length() - 1


def test_merge() -> None:
    assert merge([], []) == []
    assert merge([("a", 1, 1), ("b", 2, 1)], [("a", 3, 1)]) == [("a", 1, 1), ("a", 3, 1), ("b", 2, 1)]


def test_sizes_follow_binary_counter() -> None:
    idx = LogarithmicIndex(4)
    for t in range(1, 33):
        for j in range(4):
            idx.add(("x", 4 * (t - 1) + j + 1, 1))
        present = [i for i, lv in enumerate(idx.levels) if lv is not None]
        assert present == [i for i in range(t.bit_length()) if t >> i & 1]
        idx.check_invariant()
    # 32 flushes of 4 postings: k log2 k flushes of work, each worth n postings.
    assert idx.merged == 4 * 32 * 5


def test_example_eight_flushes() -> None:
    idx = LogarithmicIndex(4)
    per_flush = []
    for t in range(1, 9):
        before = idx.merged
        for j in range(4):
            idx.add(("x", 4 * (t - 1) + j + 1, 1))
        per_flush.append(idx.merged - before)
    assert per_flush == [0, 8, 0, 24, 0, 8, 0, 56]
    assert idx.merged == 96
    assert max(idx.merge_count.values()) == 3
    naive = sum(4 * t for t in range(2, 9))
    assert naive == 140


def test_edge_cases() -> None:
    idx = LogarithmicIndex(1)
    assert idx.postings("a") == [] and idx.all_postings() == []
    idx.add(("a", 1, 2))
    assert idx.levels[0] == [("a", 1, 2)] and idx.z0 == []
    assert idx.postings("a") == [(1, 2)]
    try:
        LogarithmicIndex(0)
    except ValueError:
        pass
    else:
        raise AssertionError("n = 0 was accepted")


def test_random_union_and_merge_bound() -> None:
    rng = random.Random(20261117)
    for _ in range(150):
        n = rng.randint(1, 9)
        stream = random_postings(rng, rng.randint(0, 40), rng.randint(1, 12))
        idx = LogarithmicIndex(n)
        inserted = []
        for x in stream:
            idx.add(x)
            inserted.append(x)
            idx.check_invariant()
            assert idx.all_postings() == sorted(inserted)
            T = len(inserted)
            bound = floor_log2(T // n) if T >= n else 0
            assert max(idx.merge_count.values()) <= bound
        want = direct(inserted)
        for t in set(want) | {"absent"}:
            assert idx.postings(t) == want.get(t, [])
        k = len(inserted) // n
        assert idx.merged == n * sum(2 ** (trailing_zeros(t) + 1) - 2 for t in range(1, k + 1))

History

Bentley and Saxe described the binary transformation for decomposable searching problems in 1980, with structures of sizes that are powers of two. For text indexes, Lester, Moffat and Zobel in 2005 compared merge-based update strategies such as rebuild, in-place update and remerge, and proposed geometric partitioning, which keeps partitions of geometrically growing sizes with any ratio. Manning, Raghavan and Schuetze describe logarithmic merging as the standard answer to dynamic indexing in their 2008 textbook, with the bound of O(log⁡(T/n))O(\log(T/n)) merges for each posting.

References

  1. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 4, Section 4.5 (dynamic indexing, the auxiliary index, the LMERGEADDTOKEN pseudocode, and the bound of O(log(T/n)) merges for each posting)
  2. Stefan Buettcher, Charles L. A. Clarke and Gordon V. Cormack, Information Retrieval, Implementing and Evaluating Search Engines, MIT Press, 2010, Chapter 7 (dynamic inverted indices), Section 7.2 (incremental index updates) and Section 7.3 (document deletions)
  3. Jon Louis Bentley and James B. Saxe, Decomposable searching problems I. Static-to-dynamic transformation, Journal of Algorithms 1(4), 1980, pages 301 to 358, the binary transformation, which keeps static structures of sizes that are powers of two
  4. Nicholas Lester, Alistair Moffat and Justin Zobel, Fast on-line index construction by geometric partitioning, Proceedings of CIKM 2005, pages 776 to 783, Section 3 (merge-based update strategies, the remerge cost that logarithmic schemes avoid)

Where this leads

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 proofH2 full proof
  • correctness: no review record reviews/GRDTV2/proof-correctness.yaml
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