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
- Evidence
- Full proofCode in 1 languages
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 postings it goes to disk, and the disk indexes are kept at sizes , 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 times in total, in place of up to 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 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 postings costs 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
is the index in memory, with room for postings. are the indexes on disk, and , when it exists, has exactly postings. MERGE joins two indexes into one, list by list, as a k-way merge with .
LMERGE-ADD(x) ▷ x: one new posting- 1
Z0 ← MERGE(Z0, {x}) ▷ in memory - 2
if |Z0| = n then - 3
Z ← Z0, i ← 0 - 4
while I_i exists do - 5
Z ← MERGE(I_i, Z), delete I_i ▷ now |Z| = 2^(i+1) n - 6
i ← i + 1 - 7
I_i ← Z, Z0 ← empty ▷ written to disk QUERY(t)- 8
read the list of t from Z0 and from each I_i that exists - 9
return the union of these lists, in increasing document id order
Line L1 adds the posting to the in-memory index. When is full (line L2), lines L3 to L6 carry it up the levels. At level , if 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 and add 32 postings, so that 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 | in binary | levels after the flush | merges at line L5 | postings written by merges |
|---|---|---|---|---|
| 1 | 1 | none | 0 | |
| 2 | 10 | 8 | ||
| 3 | 11 | none | 0 | |
| 4 | 100 | , | 8 + 16 = 24 | |
| 5 | 101 | none | 0 | |
| 6 | 110 | 8 | ||
| 7 | 111 | none | 0 | |
| 8 | 1000 | , , | 8 + 16 + 32 = 56 |
The merges write 96 postings in total. That is : each of the 32 postings is merged exactly 3 times, once at each doubling from 4 to 32. With one auxiliary index, flush rewrites the main index of postings, which costs postings. The gap grows with : at 1,024 flushes of the same , logarithmic merging writes postings, while the auxiliary scheme writes . 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. holds postings. The level exists exactly when bit of is 1, and then it holds postings. And and the levels hold disjoint sets whose union is all postings added so far. A call that does not fill keeps all three. A call that fills carries through the trailing 1 bits of the flush count: the loop keeps and moves the postings of each merged level into , 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 . Let be the number of postings added so far, all distinct, and let be the set of these postings. Write with , and let be the binary form of . 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) holds exactly postings.
(I2) exists if and only if , and then .
(I3) and the indexes that exist are pairwise disjoint, and their union is .
-
Base. Before the first call, , is empty and no exists. All three statements hold.
-
A call that does not fill . Suppose the statements hold before the call that adds posting , with . Line L1 adds to . If , the test of line L2 fails and nothing else changes. Now , so (I1) holds with , (I2) is unchanged because is unchanged, and (I3) holds because is new and is now in .
-
A call that fills . Else , so . Let be the number of trailing 1 bits of , so and . By (I2), exist and does not. The loop of lines L4 to L6 keeps the statement
(L) at the start of a step with index , , the set is the union of the old with and of , and no longer exist.
It holds at after line L3, since . If exists, line L5 merges it into , which gives , and deletes it. So (L) holds for . The loop runs for and stops at , where does not exist. Line L7 stores as with , and empties . In binary, has , , and the same higher bits as . The indexes now present are exactly those of the bits of , with the sizes of (I2). is empty, which is (I1) with . No posting was lost or copied: each merge moves the postings of into , and becomes . So (I3) holds.
-
Queries. By (I3), the posting list of a term in is the union of the lists of in and in each that exists, and these lists are disjoint. Lines L8 and L9 return this union in document order, so the query is correct.
-
Each merge doubles the index that holds a posting. A posting starts in , which has postings when it is first merged. By step 3, takes part in a merge only at line L5, where it is in or in , both of size , and the result has size . After that merge, is in for the rest of the loop and then in , of size , and the next merge of , in a later call, again starts from an index of the size that is in. So after merges, is in an index of postings. That index is a subset of , so , which gives . Since is an integer, when , and when .
-
Total merge work. In the call that completes the -th flush, before the call, and the number of trailing 1 bits of is the number of trailing 0 bits of . The merges of that call write postings. Summed over all postings, step 5 bounds the total by . When , the sum of over is exactly : each of the postings is merged exactly times, since all of them end in the single index .
Complexity
- Merges for one posting. Each merge that a posting takes part in doubles the size of the index that holds it, from up to at most . So a posting is merged at most times. Manning, Raghavan and Schuetze state this as merges for each posting.
- Total merge work. Summed over the postings, the merges write at most postings, so the build costs , against for one auxiliary index. When the count is exactly . The amortized cost of one insertion is postings written.
- Worst case for one insertion. One flush can merge every level, which writes up to postings. The bound is amortized, not a worst case per insertion.
- Queries. A query reads and up to disk indexes, in place of 2 with one auxiliary index. This is the price of the cheaper merges.
- Space. words of memory, and 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 .
- 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 , 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 indexes per level for a ratio , 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 writes postings in a chain of pairwise merges. A single merge of and all these levels writes only . 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 becomes a dynamic one with amortized insertion cost and queries over 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 merges for each posting, not . With there is no merge at all. The difference matters when is large, as it is in practice.
- Merge without deleting the old level. If line L5 forgets to delete , a query reads the postings of twice, once in and once in the new level. The level must be deleted after the merge, as in line L5.
- Merge at the wrong level. Merging always into the largest level in place of the carry of lines L4 to L6 gives back the auxiliary scheme with its 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.
# 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 merges for each posting.
References
- 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)
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GRDTV2 Edit this page History Report an error Markdown