Algorithmadvanced
Geometric partitioning
Also called Lester-Moffat-Zobel geometric partitioning.
Keeps index partitions whose sizes grow geometrically by a ratio r, or at most p of them, trading merge cost against the number of partitions a query reads.
- Time
- O(r T log(T/b) / log r) buildO(T (T/b)^(1/p)) build_fixed_pO(r log(T/b) / log r) amortized insertO(log(T/b) / log r) partitions_per_query
- Space
- O(T) diskO(b) memory
- Where
- T = the number of postings added so far; b = the number of postings in the in-memory buffer; m = the number of buffer flushes (the floor of T/b); p = the bound on the number of partitions in the fixed-p variant; r = the radix (the ratio between partition sizes)
- Properties
- comparison baseddeterministicnot in placeonlineiterative
- Evidence
- Full proofCode in 1 languages
Geometric partitioning keeps an inverted index up to date while documents arrive, by holding the index in a few partitions on disk whose sizes grow by a factor from one level to the next. A full in-memory buffer of postings is merged with the smaller partitions in one multiway merge, and the partitions behave like the digits of a counter in base . Lester, Moffat and Zobel proposed it in 2005, with a second form that fixes the number of partitions at and lets grow. Logarithmic merging is close to the case , but it merges pairwise; this page covers the general radix, the cost in postings written as a function of , and the fixed- form. The log-structured merge tree uses the same idea for key-value stores.
In plain words
A growing index on disk can be kept as one big file, but then each batch of new documents forces a rewrite of the whole file. It can also be kept as many small files, but then each search has to open all of them. Geometric partitioning is a middle way. It keeps a few files, each one about times larger than the one before. New documents fill a buffer in memory. When the buffer is full, it is joined with the small files into one new file. Large files are rewritten only rarely. A larger means fewer files to search but more rewriting. A smaller means less rewriting but more files.
The problem
Postings arrive one at a time. After each arrival a query for a term must return its full posting list. The cost to measure is the number of postings written to disk by merges, and the number of partitions a query must read. With one partition, the remerge strategy, each flush rewrites the whole index, and flushes write postings. With no merge at all, a query reads partitions. The general problem is dynamic index maintenance.
The algorithm
Partition , for , is one sorted index on disk. It is either empty or holds postings with , so it is full when it holds . is the buffer in memory.
GEOM-ADD(x) ▷ r ≥ 2, buffer capacity b- 1
add x to the buffer Z - 2
if |Z| = b then - 3
k ← 1 - 4
while P_k holds (r - 1) r^(k-1) b postings do k ← k + 1 - 5
P_k ← MULTIWAY-MERGE(Z, P_1, ..., P_k) ▷ one pass, written to disk - 6
make Z and P_1, ..., P_(k-1) empty QUERY(t)- 7
read the list of t from Z and from each partition that is not empty - 8
return the union of these lists, in increasing document id order
Line L1 puts the posting in the buffer. When the buffer is full (line L2), lines L3 and L4 look for the first partition that is not full. Line L5 merges the buffer with all partitions up to that one in a single pass, as a k-way merge, and stores the result as the new . The partitions below were full, so their content now sits in , and line L6 empties them. Because held postings, the buffer and these partitions add exactly postings to , one unit of its level. So, after flushes, holds postings, where is digit of in base . Lines L7 and L8 answer a query from the buffer and all partitions.
Example
Take and count postings in units of . Nine flushes give this trace. The digits are those of the flush count in base 3, with on the right.
| flush | in base 3 | first partition not full | merged at line L5 | sizes of after | written |
|---|---|---|---|---|---|
| 1 | 1 | 0, 0, 1 | 1 | ||
| 2 | 2 | , | 0, 0, 2 | 2 | |
| 3 | 10 | , , | 0, 3, 0 | 3 | |
| 4 | 11 | 0, 3, 1 | 1 | ||
| 5 | 12 | , | 0, 3, 2 | 2 | |
| 6 | 20 | , , | 0, 6, 0 | 6 | |
| 7 | 21 | 0, 6, 1 | 1 | ||
| 8 | 22 | , | 0, 6, 2 | 2 | |
| 9 | 100 | , , , | 9, 0, 0 | 9 |
The nine flushes write postings, against for remerge into one index. The postings of flush 1 are written 5 times: twice at level 1, twice at level 2 and once at level 3. This is the case shown in the figure of Lester, Moffat and Zobel, nine bufferloads that end as one partition of .
For a longer run, take flushes. The postings written, in units of , and the partitions are:
| strategy | postings written | partitions that can exist | nonempty after 1000 flushes |
|---|---|---|---|
| remerge, one partition | 500,500 | 1 | 1 |
| 14,500 | 4 | 1 | |
| 7,560 | 5 | 4 | |
| 6,670 | 7 | 4 | |
| 5,060 | 10 | 6 |
Correctness
After flushes and further postings, the buffer holds postings and partition holds postings, where is the -th digit of in base . A partition is full exactly when its digit is . A flush finds the first digit below , and the merge of line L5 holds postings, which is the new digit at level with all lower digits 0. This is the addition of 1 in base . Each merge moves postings and never copies them, so the buffer and the partitions hold disjoint sets whose union is everything added, and a query that takes the union of all lists is correct. The full proof is in the proof file below.
Proof: Geometric partitioning keeps all postings, follows a radix-r counter, and writes each posting at most (r-1)(1 + floor(log_r m)) timesfull
Fix the radix and the buffer size . Let be the set of postings added so far, all distinct, with and . So is the number of flushes. Write with base- digits . We show that after each call of GEOM-ADD:
(G1) the buffer holds postings;
(G2) partition holds exactly postings, for each ;
(G3) and the partitions are pairwise disjoint, sorted, and their union is .
-
Base. With empty, , all digits are 0 and all partitions are empty.
-
A call with no flush. Line L1 adds the new posting to in sorted position. If after that, nothing else changes, grows by one, does not change, and the posting is new. (G1) to (G3) hold.
-
A call with a flush. Else after line L1. The capacity of is , and by (G2) is at capacity exactly when . Lines L3 and L4 find the least with . Such a exists because has finitely many nonzero digits. So . The merge of line L5 has postings. In base , adding 1 to turns the low digits into 0, adds 1 to digit , which is at most after the change, and leaves the higher digits alone. So after line L6, with and empty and holding the merge result, (G2) holds for , and (G1) holds with . The merge of sorted disjoint lists gives their sorted union, and the postings of the merged sources are moved, not copied, so (G3) holds.
-
Queries. By (G3), the list of a term over is the disjoint union of its lists in and in each partition. Lines L7 and L8 return it in document order.
-
The size of each merge. Let flush number be the one that takes the count from to . The low digits of that equal are the low digits of that equal 0, so , the number of times divides , and by step 3 the merge writes postings, where is digit of . The total after flushes is .
-
Writes of one posting. A posting is written once in each flush that includes it in line L5. Fix a level . The posting enters in some flush, which sets digit to some value and writes the posting once. While it stays in , it is written again only by flushes that stop at level , and each of them adds 1 to digit . A flush that stops at a higher level moves the posting out of for good, because partitions only move postings to higher levels. Digit can grow from to at most , so the posting is written at most times at level . A flush can reach level only when , so the levels used satisfy . Hence each posting is written at most times, and the total over all postings is at most .
-
The number of partitions. By (G2), the nonempty partitions are those with a nonzero digit, so at most of them exist, and a query reads at most that many partitions plus the buffer.
Complexity
- Merge size. Flush writes postings, where is the number of times divides . After flushes the total is .
- Writes for one posting. At each level a posting is written at most times: once when it enters the level and once for each later increase of that digit. The levels in use are at most . So each posting is written at most times, and the build costs postings written. For this is , as for logarithmic merging.
- Queries. A query reads the buffer and at most partitions. A larger means fewer partitions and more writes.
- Fixed number of partitions. If at most partitions may exist, the radix must grow with the index, to about . Then each posting is written times, and the build costs . With this is remerge, with its cost. With the cost is and each query reads at most two partitions.
- Space. words of memory for the buffer, and words of disk, plus room for the output of one merge.
Properties
- Online. A posting can be found by queries right after GEOM-ADD returns.
- One merge per flush. Unlike the chain of pairwise merges of logarithmic merging, one flush does one multiway merge, so a posting moves up several levels in one write.
- Tunable. The radix , or the bound , sets the trade-off between update cost and query cost.
- Deterministic. The partition sizes depend only on , and .
Variants and improvements
- Fixed . Lester, Moffat and Zobel also describe the form in which the number of partitions is bounded by , and the radix is chosen from the current size so that partitions are enough. The radix then grows slowly as the index grows.
- Hybrid with in-place update. Long posting lists can be kept in a separate structure that is updated in place, so that the merges only rewrite the short lists.
- Ratio 2 with pairwise merges. Manning, Raghavan and Schuetze present the case as logarithmic merging, with a chain of pairwise merges for a carry. See logarithmic merging.
- Leveled and tiered merge policies. In a log-structured merge tree, a leveled policy keeps one run per level, like remerge at each level, and a tiered policy keeps up to runs per level, like geometric partitioning.
- Deletions. As for other merge schemes, deleted documents go to an invalidation list, and the merges drop their postings when they rewrite a partition.
When to use it
Use geometric partitioning for a text index that grows all the time while it answers queries, when a full remerge at each flush is too slow and a large number of partitions would slow the queries. Pick from the ratio of queries to updates: a small for heavy update loads, a larger , or the fixed- form with or 3, when queries dominate. For a static collection, build once with single-pass in-memory indexing.
Pitfalls
- Merging only with the next partition. If line L5 merges the buffer only with and leaves in place, the partitions below stay full, the next flush finds the same again, and the sizes no longer follow the counter. The merge must take all of , as in line L5, and line L6 must empty the lower partitions.
- Wrong full test. The test of line L4 must compare with the capacity . With a smaller threshold such as , a level is merged up before it is full, the sizes stop following the base counter, and the bounds of the Complexity section no longer hold.
- Claiming a fixed number of partitions with a fixed . With a fixed radix, the number of partitions grows as . Only the fixed- form bounds it, and then the merge cost grows as a power of .
- Statistics per partition. A ranking function needs collection-wide document frequencies. They must be summed over the partitions, or kept in a separate table, or the scores change with the partition layout.
- Disk space during a merge. The new partition is written before the old ones are deleted, so the largest merge needs free disk space for a copy of most of the index.
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/geometric-partitioning/. The authors are listed in prov/J597QM.jsonl.
import bisect
import heapq
from typing import Any
Posting = tuple[Any, int, int] # (term, document id, term frequency)
class GeometricIndex:
"""Geometric partitioning with a fixed radix r >= 2 and an in-memory buffer of b postings.
Partition k (k = 1, 2, ...) is one sorted index on disk. It is empty or holds
j * r^(k-1) * b postings for some j in 1..r-1, so at most (r-1) r^(k-1) b.
A flush merges the buffer and partitions 1..k into partition k, where k is
the first partition that is not full. Postings must be distinct.
writes[p] counts how many times posting p was written to disk, and written
is the total over all postings.
"""
def __init__(self, r: int, b: int) -> None:
if r < 2 or b < 1:
raise ValueError("need r >= 2 and b >= 1")
self.r, self.b = r, b
self.buffer: list[Posting] = []
self.parts: list[list[Posting]] = [] # parts[k - 1] is partition k
self.writes: dict[Posting, int] = {}
self.written = 0
self.flushes = 0
def capacity(self, k: int) -> int:
"""The most postings that partition k may hold: (r - 1) r^(k - 1) b."""
return (self.r - 1) * self.r ** (k - 1) * self.b
def add(self, x: Posting) -> None:
"""Insert one posting. Cost O(b) for the buffer insert, plus one multiway merge on a flush."""
bisect.insort(self.buffer, x) # @line L1
self.writes[x] = 0
if len(self.buffer) == self.b: # @line L2
k = 1 # @line L3
while k <= len(self.parts) and len(self.parts[k - 1]) == self.capacity(k): # @line L4
k += 1
if k > len(self.parts):
self.parts.append([])
sources = [self.buffer] + self.parts[:k]
merged = list(heapq.merge(*sources)) # @line L5
for p in merged:
self.writes[p] += 1
self.written += len(merged)
for i in range(k - 1): # @line L6
self.parts[i] = []
self.parts[k - 1] = merged
self.buffer = []
self.flushes += 1
def postings(self, term: Any) -> list[tuple[int, int]]:
"""The posting list of term: the union over the buffer and all partitions, sorted by doc id."""
out: list[tuple[int, int]] = []
for part in [self.buffer] + self.parts: # @line L7
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 L8
def all_postings(self) -> list[Posting]:
"""Every posting held, in sorted order."""
out = list(self.buffer)
for part in self.parts:
out.extend(part)
out.sort()
return out
def check_invariant(self) -> None:
assert len(self.buffer) < self.b and self.buffer == sorted(self.buffer)
m = self.flushes
for k, part in enumerate(self.parts, start=1):
digit = (m // self.r ** (k - 1)) % self.r
assert len(part) == digit * self.r ** (k - 1) * self.b
assert part == sorted(part)
test_geometric_partitioning.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geometric-partitioning/. The authors are listed in prov/J597QM.jsonl.
import random
from geometric_partitioning import GeometricIndex
def random_postings(rng: random.Random, docs: int, vocab: int) -> list[tuple[str, int, int]]:
out = []
for d in range(1, docs + 1):
for t in rng.sample(range(vocab), rng.randint(0, min(vocab, 6))):
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 v(t: int, r: int) -> int:
"""The number of times r divides t, for t >= 1."""
c = 0
while t % r == 0:
t //= r
c += 1
return c
def floor_log(m: int, r: int) -> int:
"""floor(log_r m) for m >= 1, in integers."""
c = 0
while m >= r:
m //= r
c += 1
return c
def exact_total(m: int, r: int, b: int) -> int:
"""Postings written by m flushes: flush t forms (t mod r^(v_r(t)+1)) b postings."""
return b * sum(t % r ** (v(t, r) + 1) for t in range(1, m + 1))
def fill(idx: GeometricIndex, count: int) -> None:
for i in range(count):
idx.add(("x", i + 1, 1))
def test_radix_three_nine_bufferloads() -> None:
idx = GeometricIndex(3, 1)
sizes = []
for t in range(1, 10):
before = idx.written
idx.add(("x", t, 1))
sizes.append(idx.written - before)
idx.check_invariant()
assert sizes == [1, 2, 3, 1, 2, 6, 1, 2, 9]
assert idx.written == 27
assert [len(p) for p in idx.parts] == [0, 0, 9]
def test_radix_two_matches_doubling_sizes() -> None:
idx = GeometricIndex(2, 4)
fill(idx, 32)
assert [len(p) for p in idx.parts] == [0, 0, 0, 32]
assert idx.written == 4 * (1 + 2 + 1 + 4 + 1 + 2 + 1 + 8)
def test_partition_contents() -> None:
idx = GeometricIndex(3, 2)
fill(idx, 2 * 14) # 14 = 112 in base 3
assert [len(p) for p in idx.parts] == [4, 6, 18]
idx.check_invariant()
def test_edge_cases() -> None:
idx = GeometricIndex(2, 1)
assert idx.postings("a") == [] and idx.all_postings() == []
idx.add(("a", 3, 1))
assert idx.parts == [[("a", 3, 1)]] and idx.buffer == []
for bad in [(1, 1), (2, 0)]:
try:
GeometricIndex(*bad)
except ValueError:
pass
else:
raise AssertionError("bad parameters were accepted")
def test_random_union_and_write_bound() -> None:
rng = random.Random(20261118)
for _ in range(150):
r = rng.randint(2, 5)
b = rng.randint(1, 6)
stream = random_postings(rng, rng.randint(0, 40), rng.randint(1, 12))
idx = GeometricIndex(r, b)
inserted = []
for x in stream:
idx.add(x)
inserted.append(x)
idx.check_invariant()
assert idx.all_postings() == sorted(inserted)
m = idx.flushes
bound = (r - 1) * (1 + floor_log(m, r)) if m >= 1 else 0
assert max(idx.writes.values()) <= bound
assert idx.written == exact_total(m, r, b)
want = direct(inserted)
for t in set(want) | {"absent"}:
assert idx.postings(t) == want.get(t, [])
def test_bound_is_reached() -> None:
# With r^K flushes, the first postings are written (r - 1) K + 1 times: r - 1 at
# each of the levels 1..K and once more when they reach level K + 1.
for r in (2, 3, 4):
idx = GeometricIndex(r, 1)
fill(idx, r ** 3)
assert max(idx.writes.values()) == (r - 1) * 3 + 1
assert (r - 1) * 3 + 1 <= (r - 1) * (1 + floor_log(r ** 3, r))
History
Lester, Moffat and Zobel introduced geometric partitioning at CIKM 2005, after a study of the rebuild, in-place and remerge strategies for on-line index construction, and they extended the work in a 2008 journal paper in ACM Transactions on Database Systems. The same structure with ratio 2 appears as logarithmic merging in the textbook of Manning, Raghavan and Schuetze, and it is a form of the binary transformation of Bentley and Saxe for decomposable searching problems.
References
- Nicholas Lester, Alistair Moffat and Justin Zobel, Fast on-line index construction by geometric partitioning, Proceedings of the 14th ACM International Conference on Information and Knowledge Management (CIKM 2005), pages 776 to 783, Section 3 (merge-based update, rebuild, in-place update and remerge) and Section 4 (geometric partitioning, the radix r and the fixed number p of partitions)
- Nicholas Lester, Alistair Moffat and Justin Zobel, Efficient online index construction for text databases, ACM Transactions on Database Systems 33(3), Article 19, 2008, the journal version, with geometric partitioning and its comparison with in-place and remerge strategies
- 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)
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 4, Section 4.5 (dynamic indexing and logarithmic merging, the case of ratio 2)
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 J597QM Edit this page History Report an error Markdown