Data structureadvanced
Signature file
Also called superimposed coding index.
Stores for each document a bit signature made by OR-ing hashed term codes, so a scan rejects most documents without false negatives.
- Time
- O(m D + F/w) insertO(m s + N F/w + c V) search
- Space
- O(N F/w) total
- Where
- D = the number of distinct terms of a document; F = the signature width in bits; N = the number of documents; V = the cost of checking one candidate against its document; c = the number of candidates; m = the bits set per term; s = the number of query terms; w = the word size in bits
- Model
- Word RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
A signature file is an index that stores, for each document, one string of bits, its signature: each distinct term of the document is hashed to a code with bits set, and the signature is the OR of these codes, a method called superimposed coding. A query is coded in the same way, and a document can contain all the query terms only if its signature has a 1 wherever the query code has one. A sequential scan of the signatures rejects most documents with a few word operations each, never rejects a document that matches, and passes some false drops, which a check against the document removes. Each signature is a Bloom filter of the terms of one document.
In plain words
For every word, a fixed rule picks a few positions in a row of bits. A document gets one row: switch on the positions of every word it contains. To ask whether a document holds the word "sorted", look at the positions of "sorted" in its row. If one of them is off, the document cannot hold the word, and it is skipped.
If all of them are on, the document probably holds the word, but other words may have switched on the same positions by chance. So the documents that pass are read and checked. The rows are short and the test is fast, so a scan over all rows is cheap. A wider row with well chosen positions per word lets fewer wrong documents pass.
The abstract type
The structure holds a sequence of documents, each an id and a set of terms. The operations are:
- INSERT: append the document with the set of terms .
- CANDIDATES: return the ids, in insertion order, of the documents whose signature covers the code of the query terms . This set contains every document whose terms include .
- SEARCH: return the ids of the documents whose terms include , in insertion order: the Boolean AND query of the Boolean retrieval model.
Representation
A term has the code , an -bit word with exactly bits set, at places chosen by a hash function of . The signature of a document with term set is . The file is the array of the signatures, each machine words, in the order of the documents, next to the documents or their term sets, which the check reads. The code here takes the places from 16-bit pieces of a keyed BLAKE2b hash, with rejection of the pieces that would bias a place and of places already taken, so that under the model of an ideal hash every set of places is equally likely.
Operations
SEARCH(S, Q)- 1
q ← 0 - 2
for each term t of Q do q ← q OR sig(t) ▷ the query code - 3
R ← () - 4
for each document d with signature s and terms T, in order do - 5
if s AND q = q then ▷ d is a candidate - 6
if Q ⊆ T then append d to R ▷ the check removes false drops - 7
return R
INSERT computes with one code for each distinct term and appends it. CANDIDATES is lines L1 to L5 without the check. The test of line L5 is one AND and one comparison per machine word of the signature.
Example
Take and on the toy collection. The code of "sorted" sets the bits 18 and 27, that of "merge" the bits 3 and 29, and that of "list" the bits 0 and 29. Apply these operations.
| operation | bits set | CANDIDATES and SEARCH after it |
|---|---|---|
| INSERT (8 terms) | 11: 3, 4, 7, 12, 15, 16, 18, 19, 22, 27, 30 | sorted: and |
| INSERT (9 terms) | 14 | merge: and |
| INSERT (10 terms) | 14: 0, 2, 3, 7, 9, 12, 15, 18, 19, 24, 25, 26, 29, 31 | merge: and ; list: and |
After , "merge" has a false drop: has bit 3 from "term" and bit 29 from "list", and it does not contain "merge".
With all 8 documents, the signatures have 11, 14, 14, 13, 16, 16, 14 and 12 bits set. The query "sorted" gives the candidates , , , and , and the check keeps , , and . "quantum" occurs in no document and still has the candidate . The query , "posting list merge", has the candidates and and no answer. Over the 326 pairs of a term of the vocabulary and a document that does not contain it, 58 are false drops; the formula below predicts 63.8 on average.
Correctness
The invariant is that each stored signature is the OR of the codes of the terms of its document. If , every bit of is a bit of some with , so : a matching document is always a candidate, and there are no false negatives. Line L6 is the exact test, so SEARCH returns exactly the documents of a direct scan, in the same order.
The rate of false drops depends on the hash. Model each term code as a uniform random set of of the places, independent across terms. For a one-term query whose term is not among the distinct terms of a document, the document is a false drop when each of the query places is set by some document term. By the inclusion-exclusion principle over the query places that stay empty,
The full proofs of both parts are in the proof file of this page.
Proof: The signature file has no false negatives, its search returns exactly the documents that contain the query, and the false drop rate has a closed formfull
Fix the width and the weight with . For a term , the term signature is a set of exactly of the places , written as an -bit word; it depends only on (and the fixed salt). For a finite set of terms, the signature is , the bitwise OR of the term signatures, with . A document has a set of terms . For a query, a finite set of terms, the answer is , in the order of insertion.
Invariant (I). The arrays , and have the same length, and for each , , where is the term set of document .
Lemma 1. The constructor makes (I) true and INSERT keeps it.
Proof. The empty file has three empty arrays. INSERT appends the id, the set of distinct terms, and SIGNATURE, which ORs over the distinct elements of , so it is .
Lemma 2 (no false negatives). If , then , that is, .
Proof. , since the second union runs over a superset of the terms of the first. A set of places is contained in exactly when as words.
The converse does not hold. Places of for a term can all be set by other terms of , and then passes the test of line L5 without containing . Such a document is a false drop.
Theorem 1. If (I) holds, SEARCH returns , in the order of insertion.
Proof. Lines L1 and L2 compute . Line L4 visits the documents in the order of insertion, with by (I). If , then line L5 passes by Lemma 2 and line L6 passes, so is appended. If , then line L6 fails, whatever line L5 does, so is not appended. So the output is the sequence of the with , in the order of insertion, which is . For , , every document passes both lines, and is every document.
The same argument shows that CANDIDATES, which stops after line L5, returns followed in order by the false drops: every answer is a candidate, and a candidate is not an answer exactly when it is a false drop.
The random model. To count false drops, model each term signature as a uniform random -subset of the places, independent for different terms. The code is built so that this model is the right one for an ideal hash: each 16-bit hash value below gives a uniform place modulo , values above it are rejected, and places already taken are skipped, so the distinct places form a uniform -subset when the hash values are independent and uniform. BLAKE2b is not proved to be such a hash; the model is the usual assumption, and the tests check the rate that it predicts.
Theorem 2 (the false drop rate). Let have distinct terms, and let be a term not in . In the random model, the probability that is a false drop for the query is
Proof. Condition on , a fixed set of places. The signatures of the terms of are independent of , since the terms are different. The document is a false drop when every place of is set in . For let be the event that is not set. By the inclusion-exclusion principle,
The event says that no term of sets a place of . One uniform -subset of the places avoids a fixed set of places with probability , the share of the -subsets of the other places, and the terms are independent, so the probability is that number to the power . It depends on only through , and has subsets of size . This gives the formula, and since it does not depend on , it is also the probability without the condition.
Remark (the usual approximation). If the places of each term were chosen with repetition, a place would stay unset with probability , and treating the places of the query as independent gives the false drop probability . For fixed and this is smallest near , the same analysis as for the Bloom filter. The exact formula of Theorem 2 is the one the code computes, with exact fractions.
Complexity
| operation | time | notes |
|---|---|---|
| INSERT | places for each of the distinct terms, in expectation over the rejections | |
| CANDIDATES | the query code, then one pass over all signatures | |
| SEARCH | plus one check of each of the candidates | |
| space | words | plus the documents for the check |
The scan reads every signature for every query, so the time grows with whatever the size of the answer. An inverted index reads only the posting lists of the query terms.
Variants
- Choice of m. For and , the formula gives the false drop rates 0.1457, 0.0713, 0.0520, 0.0472, 0.0490, 0.0551, 0.0654 and 0.0800 for to 8. The best is , near the value of the approximation , which gives 0.0466 at against the exact 0.0472. This is the same optimum as for a Bloom filter, on the page about the optimal number of hash functions. Doubling the width to with cuts the exact rate to 0.00489.
- Bit-sliced storage. Store the file by columns: one bit vector of length for each of the places. A query reads only the columns of its set bits and ANDs them, so the work per query is about columns of bits, not all bits. This is close to a bitmap index over hashed places.
- Signatures of blocks. Cut long documents into blocks of a fixed number of distinct terms, and give each block its own signature, so that stays near the value the width was chosen for.
- Several queries in one pass. A sequential scan can test many query codes against each signature it reads.
When to use it
Signature files suit conjunctive queries over many small records with a fixed upper bound on their terms, where appends are frequent, and where a scan of a compact file is acceptable. Zobel, Moffat and Ramamohanarao compared the two methods for text indexing and found inverted files distinctly superior: faster, smaller and more functional. A signature file keeps no term weights for ranking and no positions for phrase queries, and a NOT in a query cannot use the signatures at all, because a set bit does not prove that a term is present. For text search, use an inverted index; keep signatures for filters inside other structures.
Pitfalls
- Long documents. A document with many distinct terms sets most of the bits and becomes a candidate for almost every query. With and the toy documents of 10 terms already have a false drop rate of 0.22 for one query term. Choose for the largest , or split documents into blocks.
- Dropping the check. CANDIDATES is not the answer: "quantum" has a candidate on the toy collection. The check of line L6 needs access to the documents.
- Codes with fewer than m bits. Taking hash values modulo without removing repeats gives some terms fewer bits, and those terms pass more false drops. Choose distinct places.
- Biased places. Reducing a 16-bit value modulo an that does not divide makes small places more likely. Reject the values at or above the largest multiple of below .
- Testing the rate without a tolerance. A measured false drop rate is random. Compare it with the formula within a bound such as Hoeffding's inequality: with 150,000 trials, a gap of 0.00695 has probability at most about under the model.
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
# 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
signature_file.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/signature-file/. The authors are listed in prov/WA5X66.jsonl.
"""A sequential signature file with superimposed coding.
Each term sets m distinct bits out of F. The signature of a document is the
OR of the signatures of its distinct terms. A query is the OR of the
signatures of its terms, and a document is a candidate when its signature
has a 1 in every place where the query has one. Candidates are then checked
against the terms of the document, which removes the false drops.
"""
import hashlib
from typing import Hashable, Iterable
class SignatureFile:
"""Signatures of F bits, m bits per term, one signature per document, in insertion order.
The term sets of the documents are kept as well, in the role of the text
file that the verification step reads.
"""
def __init__(self, f: int = 64, m: int = 4, salt: bytes = b"") -> None:
if not (1 <= m <= f <= 65536):
raise ValueError("need 1 <= m <= f <= 65536")
self.f, self.m, self.salt = f, m, salt[:16]
self.ids: list[Hashable] = []
self.sigs: list[int] = []
self.terms: list[frozenset[str]] = []
self._cache: dict[str, int] = {}
def __len__(self) -> int:
return len(self.ids)
def term_signature(self, t: str) -> int:
"""Return the F-bit word of t: m distinct places, chosen by a keyed hash of t.
The places come from 16-bit values of BLAKE2b, with rejection of values
that would bias the place and of places already taken, so under the
usual model of an ideal hash every m-subset is equally likely.
Cost O(m) hash calls in expectation.
"""
if t in self._cache:
return self._cache[t]
f, places, counter = self.f, set(), 0
limit = 65536 - 65536 % f
while len(places) < self.m:
h = hashlib.blake2b(t.encode() + counter.to_bytes(4, "big"), key=self.salt, digest_size=32).digest()
counter += 1
for i in range(0, 32, 2):
x = int.from_bytes(h[i : i + 2], "big")
if x < limit:
places.add(x % f)
if len(places) == self.m:
break
w = 0
for p in places:
w |= 1 << p
if len(self._cache) < 1 << 16:
self._cache[t] = w
return w
def signature(self, terms: Iterable[str]) -> int:
"""Return the OR of the term signatures of the distinct terms. Cost O(m) per term."""
s = 0
for t in set(terms):
s |= self.term_signature(t)
return s
def insert(self, doc_id: Hashable, terms: Iterable[str]) -> None:
"""Append the signature of a document. Cost O(m) per distinct term of the document."""
ts = frozenset(terms)
self.ids.append(doc_id)
self.sigs.append(self.signature(ts))
self.terms.append(ts)
def candidates(self, query: Iterable[str]) -> list[Hashable]:
"""Return the ids whose signature covers the query signature: the answers and the false drops.
Cost: one scan of the N signatures, O(N F / w) word operations for words of w bits.
"""
q = self.signature(query)
return [d for d, s in zip(self.ids, self.sigs) if s & q == q]
def search(self, query: Iterable[str]) -> list[Hashable]:
"""Return the ids of the documents that contain every query term, in insertion order.
Cost: the scan of candidates, plus one check of the terms of each candidate.
"""
qs = frozenset(query)
q = 0 # @line L1
for t in qs: # @line L2
q |= self.term_signature(t)
r: list[Hashable] = [] # @line L3
for d, s, ts in zip(self.ids, self.sigs, self.terms): # @line L4
if s & q == q: # @line L5
if qs <= ts: # @line L6
r.append(d)
return r # @line L7
def check_invariant(self) -> None:
"""Raise AssertionError unless each stored signature is the OR of the signatures of its terms."""
assert len(self.ids) == len(self.sigs) == len(self.terms)
for s, ts in zip(self.sigs, self.terms):
assert s == self.signature(ts)
assert 0 <= s < 1 << self.f
def false_drop_probability(f: int, m: int, d: int) -> float:
"""The exact probability that a one-term query that is not in a document of d distinct terms is a false drop.
Model: each term sets a uniform random m-subset of the f places,
independently. By inclusion and exclusion over the m places of the query,
the result is sum over j of (-1)^j C(m, j) (C(f - j, m) / C(f, m))^d.
Cost O(m) big-integer operations.
"""
from fractions import Fraction
from math import comb
total = Fraction(0)
for j in range(m + 1):
total += (-1) ** j * comb(m, j) * Fraction(comb(f - j, m), comb(f, m)) ** d
return float(total)
test_signature_file.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/signature-file/. The authors are listed in prov/WA5X66.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
import irtoy
from signature_file import SignatureFile, false_drop_probability
def toy(f: int = 32, m: int = 2) -> SignatureFile:
s = SignatureFile(f, m)
for d, text in irtoy.DOCS.items():
s.insert(d, irtoy.tokenize(text))
s.check_invariant()
return s
def scan(docs: dict, query: list[str]) -> list:
return [d for d, ts in docs.items() if set(query) <= set(ts)]
def test_worked_example_of_the_page():
s = toy()
sig = s.term_signature("sorted")
assert [p for p in range(32) if sig >> p & 1] == [18, 27]
assert s.candidates(["sorted"]) == [1, 2, 4, 6, 8]
assert s.search(["sorted"]) == [1, 2, 4, 8]
assert s.candidates(["quantum"]) == [5]
assert s.search(["quantum"]) == []
q = irtoy.tokenize(irtoy.QUERIES["q2"])
assert s.candidates(q) == [3, 4]
assert s.search(q) == []
assert s.search(irtoy.tokenize(irtoy.QUERIES["q1"])) == [1]
def test_no_false_negatives_on_the_toy_collection():
s = toy()
docs = {d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()}
vocab = sorted({t for ts in docs.values() for t in ts})
for t in vocab + ["quantum", "lists", "document"]:
want = scan(docs, [t])
assert s.search([t]) == want
assert set(want) <= set(s.candidates([t]))
def test_edge_cases():
s = SignatureFile()
assert s.search(["a"]) == [] and s.candidates([]) == []
s.insert("e", [])
s.insert("x", ["a"])
s.check_invariant()
# The empty query has the zero signature, which every document covers.
assert s.search([]) == ["e", "x"]
assert s.search(["a"]) == ["x"]
assert s.search(["a", "a"]) == ["x"]
full = SignatureFile(8, 8)
full.insert(1, ["p"])
full.insert(2, ["q"])
# With m = F every term sets every bit, so every document is a candidate.
assert full.candidates(["r"]) == [1, 2]
assert full.search(["r"]) == []
with pytest.raises(ValueError):
SignatureFile(4, 5)
def test_term_signature_has_m_bits():
for f, m in [(1, 1), (7, 3), (64, 4), (100, 7), (16, 16)]:
s = SignatureFile(f, m, salt=b"k")
for i in range(200):
w = s.term_signature("t%d" % i)
assert bin(w).count("1") == m and w < 1 << f
def test_random_collections_against_a_direct_scan():
rng = random.Random(84)
for _ in range(600):
f = rng.choice([8, 16, 32, 64])
m = rng.randint(1, 4)
s = SignatureFile(f, m, salt=bytes([rng.randrange(256)]))
alphabet = ["w%d" % i for i in range(rng.randint(1, 30))]
docs = {}
for d in range(rng.randint(0, 12)):
docs[d] = rng.sample(alphabet, rng.randint(0, min(8, len(alphabet))))
s.insert(d, docs[d])
s.check_invariant()
for _ in range(5):
q = rng.sample(alphabet, rng.randint(1, min(3, len(alphabet))))
want = scan(docs, q)
assert s.search(q) == want
assert set(want) <= set(s.candidates(q))
def test_formula_against_full_enumeration():
# All (C(F, m))^(D+1) choices of the m-subsets, for small F, m and D.
for f, m, d in [(4, 1, 2), (5, 2, 2), (6, 2, 3), (6, 3, 2)]:
subsets = [frozenset(c) for c in itertools.combinations(range(f), m)]
hits = 0
for doc in itertools.product(subsets, repeat=d):
union = frozenset().union(*doc)
hits += sum(1 for q in subsets if q <= union)
exact = Fraction(hits, len(subsets) ** (d + 1))
assert math.isclose(false_drop_probability(f, m, d), float(exact), rel_tol=1e-12)
def test_false_drop_rate_matches_the_formula():
f, m, d, n = 16, 2, 4, 150000
s = SignatureFile(f, m, salt=b"rate")
rng = random.Random(1984)
drops = 0
for _ in range(n):
terms = ["d%d" % rng.getrandbits(60) for _ in range(d)]
q = "q%d" % rng.getrandbits(60)
doc = s.signature(terms)
qs = s.term_signature(q)
drops += doc & qs == qs
s._cache.clear()
p = false_drop_probability(f, m, d)
# Hoeffding: P(|rate - p| >= t) <= 2 exp(-2 n t^2) = delta.
delta = 1e-6
t = math.sqrt(math.log(2 / delta) / (2 * n))
assert abs(drops / n - p) < t
# The approximation (1 - e^(-m d / F))^m is close to the exact value.
assert abs((1 - math.exp(-m * d / f)) ** m - p) < 0.005
History
Faloutsos and Christodoulakis (1984) presented signature files with superimposed coding as an access method for documents and analyzed their performance and their false drop probability, and Faloutsos (1985) surveyed them with full text scanning, inversion and clustering as the access methods for text. Zobel, Moffat and Ramamohanarao (1998) compared signature files with compressed inverted files and found the inverted files better on time, space and the range of queries, and inverted indexes became the standard for text search.
References
- Christos Faloutsos and Stavros Christodoulakis, Signature files, An access method for documents and its analytical performance evaluation, ACM Transactions on Office Information Systems 2(4), 267 to 288, 1984, the signature file with superimposed coding of the words of a document, the false drop probability, and the choice of the number of bits per word
- Christos Faloutsos, Access methods for text, ACM Computing Surveys 17(1), 49 to 74, 1985, the survey of text access methods, with full text scanning, inversion, signature files and clustering
- Justin Zobel, Alistair Moffat and Kotagiri Ramamohanarao, Inverted files versus signature files for text indexing, ACM Transactions on Database Systems 23(4), 453 to 490, 1998, the experimental comparison, with the conclusion that inverted files are distinctly superior to signature files, being faster, smaller and more functional
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag WA5X66 Edit this page History Report an error Markdown