Algorithm Search⌘K

Algorithmcore

Sorted neighborhood method

Also called SNM, merge/purge sorted neighborhood.

Sort the records by a key and compare each record only with the w - 1 records before it. Several passes with different keys and a transitive closure give the duplicate clusters.

Time
O(p (n log n + w n)) worst · average · best
Space
O(n + p w n) extra
Where
n = the number of records; p = the number of passes; w = the window size
Properties
deterministicnot exactnot externalnot in placeofflineiterative
Origin
Mauricio A. Hernández, Salvatore J. Stolfo, 1995

The sorted neighborhood method (SNM) is a way to cut the number of comparisons in entity resolution. It sorts the records by a key, slides a window of ww records over the sorted list, and runs the match rule only on pairs inside the window, which gives (w−1)n−w(w−1)/2(w - 1) n - w(w-1)/2 comparisons per pass instead of n(n−1)/2n(n-1)/2. Several passes with different keys are joined by a transitive closure. Standard blocking compares the records whose keys are equal; SNM compares the records whose keys are near in sort order, so a typo late in a key still leaves the record close to its duplicates. Key functions such as Soundex and match rules based on edit distance are inputs to SNM, not part of it.

In plain words

You have a long list of customer records with many duplicates that are spelled a little differently. Comparing every record with every other one takes too long. So you sort the list by a key, for example the first letters of the last name and the year of birth. Duplicates now sit close together. You walk down the list and compare each record only with the few records just before it. A typo near the start of the key can move a duplicate far away, so you sort again by another key and walk again. At the end, if A matched B and B matched C, you put A, B and C into one group.

The problem

The input is a set DD of nn records, keys K1,…,KpK_1, \ldots, K_p (functions from records to sortable values), a window size w≥2w \ge 2, and a pairwise rule match(r,s)\mathit{match}(r, s). Hernández and Stolfo call the rules the equational theory: for example, "same year of birth and at most two edits between the names". The output is a partition of DD into clusters, one for each entity found. The aim is the result of comparing all pairs with match\mathit{match} and taking the closure, at a fraction of the cost. How close it comes is a matter of the keys and the data, so SNM is a heuristic for the problem entity resolution.

The algorithm

  1. SNM(D, K_1 ... K_p, w, match)
  2. 1P ← ∅ ▷ the matched pairs
  3. 2for each key K in K_1, ..., K_p do ▷ one pass for each key
  4. 3L ← the records of D sorted by K
  5. 4for i ← 1 to |L| do
  6. 5for j ← max(1, i - w + 1) to i - 1 do ▷ the w - 1 records before L[i]
  7. 6if match(L[j], L[i]) then add {L[j], L[i]} to P
  8. 7C ← the connected components of the graph (D, P), found with union-find
  9. 8return C

Line L3 is the sort phase. A key usually joins parts of several fields, such as the first consonants of the last name and the first letters of the first name, with the most stable characters first. On disk the sort is an external merge sort. Lines L4 to L6 are the merge phase: the window moves down by one record at a time, as in the sliding window model, and the new record is compared with the w−1w - 1 records already in it. Line L7 is the multi-pass closure. A weighted union-find does it in near linear time.

Example

Six records with a last name and a year of birth. The rule is: same year and at most one edit between the names.

record name year
r1 smith 1970
r2 smyth 1970
r3 jones 1962
r4 smith 1985
r5 jonas 1962
r6 brown 1970

Pass 1, key = name, w=2w = 2. The order is r6 brown, r5 jonas, r3 jones, r1 smith, r4 smith, r2 smyth. The 5 calls compare neighbours only. Only r5 and r3 match. The duplicate pair r1 and r2 is missed, because r4 (another person, born in 1985) sits between them.

The same pass with w=3w = 3 makes (3−1)⋅6−3=9(3 - 1) \cdot 6 - 3 = 9 calls and also finds r1 and r2.

Pass 2, key = (year, name), w=2w = 2. The order is r5, r3, r6, r1, r2, r4. Neighbours r5 and r3 match, and so do r1 and r2. With both passes at w=2w = 2 the method makes 10 calls and returns the clusters {r1, r2}, {r3, r5}, {r4} and {r6}, the same result as all 15 pairs.

A larger run. On generated data with 60 people and 144 records (141 true duplicate pairs, Python seed 42, typos in the names and a changed first letter of the last name in 15% of the copies), comparing all 10296 pairs with a rule like the one above gives pairwise precision 1.0 and recall 0.922. One pass with w=4w = 4 (426 calls) gives recall 0.681, 0.624 or 0.901 for the three keys used. Three passes with w=4w = 4 (1278 calls, 12% of all pairs) give recall 0.922, the same as all pairs. These numbers are measurements on that data only.

Correctness

One pass calls match\mathit{match} exactly once on each pair of records that are less than ww positions apart in its sort order, and on no other pair. So PP is the set of matching pairs that some pass placed in its window, and line L7 returns the components of the graph of these pairs. With w≥nw \ge n this is the transitive closure of the match rule over all pairs. With smaller ww it is a refinement of that closure: SNM can miss merges, but it never makes a merge that the full comparison would not make. There is no guarantee about the true entities; that depends on the keys and the rule. The full proof is in the proof page.

Proof: The sorted neighborhood method compares exactly the pairs inside the window and returns the closure of their matchesfull

We use the pseudocode of the page. DD has nn records, there are pp keys, the window size is w≥1w \ge 1, and match\mathit{match} is any function on pairs of records that always returns. The claims are about what the method computes. Whether its clusters are the true entities depends on the keys and on the match rule, and nothing is proved about that.

Lemma 1 (the pairs of one pass). Let L[1..n]L[1..n] be the sorted list of line L3. Lines L4 to L6 call match\mathit{match} exactly once on each pair of positions (j,i)(j, i) with 1≤i−j≤w−11 \le i - j \le w - 1, and on no other pair.

Proof. Line L4 visits each ii once, and line L5 visits the jj with max⁡(1,i−w+1)≤j≤i−1\max(1, i - w + 1) \le j \le i - 1, which are exactly the j<ij < i with i−j≤w−1i - j \le w - 1. Two different values of ii give disjoint sets of pairs, because the larger position of the pair is ii. □\square

Lemma 2 (the number of calls). One pass makes ∑i=1nmin⁡(i−1,w−1)\sum_{i=1}^{n} \min(i - 1, w - 1) calls. This is n(n−1)/2n(n-1)/2 if n≤wn \le w, and (w−1)n−w(w−1)/2(w - 1) n - w (w - 1)/2 if n≥wn \ge w.

Proof. The first form is Lemma 1. If n≤wn \le w, then i−1≤w−1i - 1 \le w - 1 for every ii, and the sum is 0+1+⋯+(n−1)0 + 1 + \cdots + (n - 1). If n≥wn \ge w, the positions i=1,…,w−1i = 1, \ldots, w - 1 give 0+1+⋯+(w−2)=(w−1)(w−2)/20 + 1 + \cdots + (w - 2) = (w - 1)(w - 2)/2, and the n−w+1n - w + 1 positions i≥wi \ge w give w−1w - 1 each. The total is (w−1)(n−w+1)+(w−1)(w−2)/2=(w−1)(n−w/2)(w - 1)(n - w + 1) + (w - 1)(w - 2)/2 = (w - 1)(n - w/2). □\square

Lemma 3 (the output). Let PP be the set after line L6 of the last pass. Then PP is the set of pairs {x,y}\{x, y\} of records such that for some key KtK_t, xx and yy are less than ww positions apart in the order of KtK_t and match\mathit{match} returned true on them. Line L8 returns the connected components of the graph (D,P)(D, P).

Proof. Line L1 starts with P=∅P = \emptyset, and by Lemma 1 the pass for KtK_t adds exactly the matching pairs inside its window; the passes only add. Line L7 computes the components with union-find: each union joins the sets of the two ends of an edge of PP, so two records end in the same set if and only if a path of edges of PP joins them. □\square

Corollary (the full window). If w≥nw \ge n, one pass calls match\mathit{match} on all n(n−1)/2n(n-1)/2 pairs, so PP is the set of all matching pairs, and the output is the transitive closure of the match relation. For w<nw < n, PP is a subset of that set, and every cluster of the output lies inside one cluster of the full closure: the method can miss merges but never adds a merge that the full comparison would not make.

Termination and cost. Each pass sorts nn records in O(nlog⁡n)O(n \log n) key comparisons and makes the calls of Lemma 2, so the total is O(p(nlog⁡n+wn))O(p (n \log n + w n)) key comparisons and match calls. Line L7 makes at most ∣P∣≤p(w−1)n|P| \le p (w - 1) n unions, each in near constant amortized time. All loops are bounded, so the method stops. ■\blacksquare

Complexity

  • Sort. O(nlog⁡n)O(n \log n) key comparisons per pass. For data on disk, this is the cost of an external sort.
  • Merge. (w−1)n−w(w−1)/2(w - 1) n - w (w - 1)/2 match calls per pass for n≥wn \ge w, so O(wn)O(w n). The match rule is often the most expensive step, so this term counts most in practice.
  • Closure. At most p(w−1)np (w - 1) n unions, near linear with union-find.
  • Total. O(p(nlog⁡n+wn))O(p (n \log n + w n)) time and O(n)O(n) memory besides the pairs; the window itself needs only ww records in memory.

Properties

  • Not exact. It returns a subset of the merges of the all-pairs closure, and its quality depends on the keys. Its window size and keys are heuristics, not results of a proof.
  • Fixed cost. The number of comparisons depends only on nn, ww and pp, not on the data. Blocking, by contrast, can blow up when one key value is frequent.
  • Order dependent. Ties in the sort order and the choice of the first characters of the key change which pairs are compared.
  • Closure can chain. The transitive closure can join two different entities through a chain of near matches.

Variants and improvements

  • Multi-pass. The main form of the method, as above. Hernández and Stolfo measured on their generated data that several passes with small windows found more duplicates than one pass with a large window at a similar cost.
  • Clustering method. The paper also partitions the records by a coarse key and runs the window inside each part, which suits parallel machines.
  • Incremental merge/purge. The journal version keeps a representative of each cluster, so that a new batch of records is compared with the representatives instead of the full old data.
  • Adaptive windows. Later work grows or shrinks the window by the similarity of the keys at its edge, so that runs of similar keys get a larger window.
  • A window over key values. Another variant slides the window over the sorted list of distinct key values instead of records, so that all records with the same key are always compared.

When to use it

Use SNM when you have a reasonable sort key and want a predictable number of comparisons, for example to deduplicate a large list of names and addresses. Use two or three passes with keys built from different fields. If many records share one key value and must all be compared with each other, standard blocking on that key is simpler. If you can afford to compare all pairs with an expensive rule, R-Swoosh also merges the records and compares the merged results.

Pitfalls

  • A typo in the first character. A different first character moves a record far away in the order. Only another pass with another key can find it.
  • Window too small for large clusters. An entity with more than ww records cannot have all its records in one window, so its pairs are found only through the closure, and a missing link splits the cluster.
  • Frequent keys. If more than ww records share a key value, the window sees only some of them, and the result depends on the tie order. Break ties by a second field, not by input position, if the order of input is not random.
  • Closure without checks. Line L7 joins chains, so one wrong match can merge two large clusters. Check large clusters or use a stricter rule for merges through the closure.

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.

sorted_neighborhood_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sorted-neighborhood-method/. The authors are listed in prov/7P2CSB.jsonl.
"""The sorted neighborhood method (SNM) of Hernandez and Stolfo, with several passes.

Records are any values. A key function maps a record to a sortable value, and
match(r, s) is the pairwise rule (the "equational theory" of the paper). One
pass sorts the records by its key and compares each record with the w - 1
records before it in the sorted order. The multi-pass method runs one pass per
key, takes the union of the matched pairs, and returns the connected
components (the transitive closure) as clusters of record numbers.
"""


def snm_pass(records, key, match, w):
    """One pass. Return (set of matched pairs (i, j) with i < j, number of match calls)."""
    n = len(records)
    order = sorted(range(n), key=lambda i: (key(records[i]), i))  # @line L3
    pairs = set()
    calls = 0
    for p in range(n):  # @line L4
        for q in range(max(0, p - w + 1), p):  # @line L5
            calls += 1
            a, b = order[q], order[p]
            if match(records[a], records[b]):  # @line L6
                pairs.add((min(a, b), max(a, b)))  # @line L6
    return pairs, calls


def expected_calls(n, w):
    """The number of match calls of one pass: (w - 1) n - w (w - 1) / 2 for n >= w."""
    if w <= 1:
        return 0
    if n <= w:
        return n * (n - 1) // 2
    return (w - 1) * n - w * (w - 1) // 2


class UnionFind:
    """Union by size with path halving, for the closure of line L7."""

    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, x, y):
        rx, ry = self.find(x), self.find(y)
        if rx == ry:
            return
        if self.size[rx] < self.size[ry]:
            rx, ry = ry, rx
        self.parent[ry] = rx
        self.size[rx] += self.size[ry]


def clusters_from_pairs(n, pairs):
    """Connected components of the graph on 0 .. n - 1 with the given edges, sorted."""
    uf = UnionFind(n)
    for a, b in sorted(pairs):
        uf.union(a, b)
    groups = {}
    for i in range(n):
        groups.setdefault(uf.find(i), []).append(i)
    return sorted(groups.values())


def sorted_neighborhood(records, keys, match, w):
    """Multi-pass SNM. Return (clusters, matched pairs, total match calls)."""
    pairs = set()  # @line L1
    calls = 0
    for key in keys:  # @line L2
        found, c = snm_pass(records, key, match, w)
        pairs |= found
        calls += c
    clusters = clusters_from_pairs(len(records), pairs)  # @line L7
    return clusters, pairs, calls  # @line L8


def all_pairs(records, match):
    """The baseline that compares every pair: the result SNM approximates."""
    pairs = set()
    n = len(records)
    for a in range(n):
        for b in range(a + 1, n):
            if match(records[a], records[b]):
                pairs.add((a, b))
    return pairs


def pair_set(clusters):
    """All pairs (i, j), i < j, that share a cluster."""
    out = set()
    for c in clusters:
        c = sorted(c)
        for x in range(len(c)):
            for y in range(x + 1, len(c)):
                out.add((c[x], c[y]))
    return out


def precision_recall(found_clusters, true_clusters):
    """Pairwise precision and recall of found clusters against the true ones."""
    found = pair_set(found_clusters)
    true = pair_set(true_clusters)
    hit = len(found & true)
    precision = hit / len(found) if found else 1.0
    recall = hit / len(true) if true else 1.0
    return precision, recall
test_sorted_neighborhood_method.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sorted-neighborhood-method/. The authors are listed in prov/7P2CSB.jsonl.

import random

from sorted_neighborhood_method import (
    all_pairs,
    clusters_from_pairs,
    expected_calls,
    precision_recall,
    snm_pass,
    sorted_neighborhood,
)

FIRST = ["anna", "boris", "carla", "david", "elena", "frank", "greta", "hugo", "irene", "jonas",
         "karin", "lukas", "maria", "nils", "olga", "paul", "rosa", "simon", "tina", "viktor"]
LAST = ["adler", "becker", "fischer", "graf", "hahn", "keller", "lang", "meyer", "neumann", "otto",
        "peters", "richter", "schulz", "vogel", "wagner", "weber", "wolf", "ziegler", "brandt", "kraus"]
CITY = ["bonn", "essen", "kiel", "mainz", "trier", "ulm", "jena", "hof"]


def typo(rng, s):
    """One random edit: substitute, delete, insert or swap two neighbours."""
    i = rng.randrange(len(s))
    kind = rng.randrange(4)
    letter = rng.choice("abcdefghijklmnopqrstuvwxyz")
    if kind == 0:
        return s[:i] + letter + s[i + 1:]
    if kind == 1 and len(s) > 2:
        return s[:i] + s[i + 1:]
    if kind == 2:
        return s[:i] + letter + s[i:]
    if i + 1 < len(s):
        return s[:i] + s[i + 1] + s[i] + s[i + 2:]
    return s + letter


def synthetic(seed, entities=60):
    """Records (first, last, city, year) and the true clusters of record numbers."""
    rng = random.Random(seed)
    records, truth = [], []
    for _ in range(entities):
        base = (rng.choice(FIRST), rng.choice(LAST), rng.choice(CITY), rng.randint(1950, 1999))
        ids = []
        for copy in range(1 + rng.randint(0, 3)):
            first, last, city, year = base
            if copy > 0:
                for _ in range(rng.randint(0, 2)):
                    if rng.random() < 0.5:
                        first = typo(rng, first)
                    else:
                        last = typo(rng, last)
                if rng.random() < 0.15:
                    last = rng.choice("bcdfgklmprstw") + last[1:]
                if rng.random() < 0.1:
                    city = rng.choice(CITY)
            ids.append(len(records))
            records.append((first, last, city, year))
        truth.append(ids)
    return records, truth


def edit_distance(a, b):
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]


def match(r, s):
    """The pairwise rule: same year and at most 2 edits over the two names."""
    return r[3] == s[3] and edit_distance(r[0], s[0]) + edit_distance(r[1], s[1]) <= 2


KEYS = [
    lambda r: (r[1][:3], r[0][:1], r[3]),
    lambda r: (r[0][:3], r[1][:1], r[3]),
    lambda r: (r[3], r[2], r[1][:1]),
]


def test_call_count_formula():
    for n in range(0, 30):
        for w in range(1, 12):
            records = list(range(n))
            _, calls = snm_pass(records, lambda r: r, lambda r, s: False, w)
            assert calls == expected_calls(n, w)
            if n >= w:
                assert calls == (w - 1) * n - w * (w - 1) // 2


def test_page_example():
    records = [("smith", 1970), ("smyth", 1970), ("jones", 1962), ("smith", 1985), ("jonas", 1962), ("brown", 1970)]

    def m(r, s):
        return r[1] == s[1] and edit_distance(r[0], s[0]) <= 1

    by_name = lambda r: r[0]
    by_year = lambda r: (r[1], r[0])
    assert snm_pass(records, by_name, m, 2) == ({(2, 4)}, 5)
    assert snm_pass(records, by_name, m, 3) == ({(0, 1), (2, 4)}, 9)
    assert snm_pass(records, by_year, m, 2) == ({(0, 1), (2, 4)}, 5)
    clusters, pairs, calls = sorted_neighborhood(records, [by_name, by_year], m, 2)
    assert clusters == [[0, 1], [2, 4], [3], [5]] and calls == 10


def test_full_window_equals_all_pairs():
    records, _ = synthetic(1, entities=25)
    n = len(records)
    for key in KEYS:
        pairs, calls = snm_pass(records, key, match, n)
        assert pairs == all_pairs(records, match)
        assert calls == n * (n - 1) // 2


def test_pass_finds_subset_of_all_pairs():
    records, _ = synthetic(2)
    full = all_pairs(records, match)
    for key in KEYS:
        for w in (2, 4, 8):
            pairs, _ = snm_pass(records, key, match, w)
            assert pairs <= full


def test_precision_and_recall_seed_42():
    records, truth = synthetic(42)
    n = len(records)
    full_clusters = clusters_from_pairs(n, all_pairs(records, match))
    p_full, r_full = precision_recall(full_clusters, truth)
    single = []
    for key in KEYS:
        clusters, _, calls = sorted_neighborhood(records, [key], match, 4)
        assert calls == expected_calls(n, 4)
        single.append(precision_recall(clusters, truth))
    multi, _, calls = sorted_neighborhood(records, KEYS, match, 4)
    p_multi, r_multi = precision_recall(multi, truth)
    assert calls == 3 * expected_calls(n, 4) < n * (n - 1) // 2
    assert all(r_multi >= r for _, r in single)
    assert r_multi <= r_full + 1e-12
    assert r_multi > max(r for _, r in single)
    assert p_multi >= 0.9 and r_multi >= 0.8

History

Hernández and Stolfo described the method in 1995 for the merge/purge problem: the deduplication of mailing lists and other large files that come from many sources. They wrote the match rules as an equational theory in a rule language, ran the method on generated data with known duplicates and on real data, and showed the multi-pass approach with a transitive closure. The 1998 journal version adds the incremental algorithm and more experiments. Christen's book (2012) treats it as one of the main indexing methods for record linkage.

References

  1. Mauricio A. Hernández and Salvatore J. Stolfo, The merge/purge problem for large databases, Proceedings of the 1995 ACM SIGMOD International Conference on Management of Data, pages 127 to 138, the sorted neighborhood method (create keys, sort, merge with a window of fixed size), the multi-pass approach with the transitive closure of the matched pairs, and the experiments on generated mailing list data
  2. Mauricio A. Hernández and Salvatore J. Stolfo, Real-world data is dirty: data cleansing and the merge/purge problem, Data Mining and Knowledge Discovery 2(1), 1998, pages 9 to 37, the journal version, with the equational theory of the match rules and the incremental merge/purge
  3. Peter Christen, Data Matching: Concepts and Techniques for Record Linkage, Entity Resolution, and Duplicate Detection, Springer, 2012, the chapter on indexing, the section on sorted neighbourhood indexing

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/7P2CSB/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
  • a scene preset for the example