Algorithmadvanced
R-Swoosh
Also called Swoosh algorithms, generic entity resolution.
Resolve entities with black-box match and merge functions: merge each record with the first resolved record it matches and put the result back. Under the ICAR properties the output is exact.
- Solves
- Entity resolution
- Time
- O(n^2) worst · averageO(n) best
- Space
- O(n) extra
- Where
- n = the number of input records
- Model
- Word RAM
- Properties
- deterministicexactnot externalnot in placeofflineiterative
- Evidence
- Full proofCode in 1 languages
- Origin
- Omar Benjelloun, Hector Garcia Molina, David Menestrina, Qi Su, Steven Euijong Whang, Jennifer Widom, 2009
R-Swoosh is an algorithm for entity resolution in which the match rule and the merge rule are black boxes. It keeps a list of resolved records. It takes the input records one by one, compares each with the resolved records, and at the first match it merges the two and puts the merged record back into the input. The merged record is compared again, so information from one record can join two others that did not match on their own. If the functions have the four ICAR properties (idempotence, commutativity, associativity and representativity), the output is exactly the set of maximal records of the merge closure. Methods such as the sorted neighborhood method and blocking decide which pairs to compare and do not merge records; collective entity resolution also uses links between records.
In plain words
You have a pile of records about people, and you can ask two questions about any two records: "are these the same person?" and "what is the combined record?". You keep a second pile of finished records. You take a record from the first pile and check it against the finished pile. If it matches one, you join the two, take the old one out of the finished pile, and put the joined record back on the first pile, because it now knows more and can match records that neither part matched. If it matches none, it goes on the finished pile. When the first pile is empty, the finished pile is the answer.
The problem
The input is a finite set of records, a match function that returns true or false, and a merge function that returns a new record for two matching records. Write for a match and for the merge. The merge closure is the smallest set that holds and every merge of two matching records in it. A record is dominated by if and : already holds all that adds. The result is the set of records of that no other record of dominates.
The ICAR properties are:
- Idempotence. and .
- Commutativity. if and only if , and then .
- Associativity. when both are defined.
- Representativity. If and , then : a merged record matches everything its parts match.
A typical example is a record as a set of attribute values, merge as the union, and a match rule that asks for shared values, such as "the same email, or the same name and the same phone".
The algorithm
R-Swoosh(I, match, merge)- 1
R ← I; R' ← ∅ ▷ R: records to do, R': resolved records - 2
while R ≠ ∅ do - 3
r ← remove a record from R - 4
buddy ← nil - 5
for each s in R' do - 6
if match(r, s) then buddy ← s; exit the loop - 7
if buddy = nil then add r to R' - 8
else remove buddy from R'; add merge(r, buddy) to R - 9
return R'
Line L6 stops at the first match, so each step makes at most calls. Line L8 drops both and its buddy: under ICAR the merged record dominates both, so they can never be needed again. The implementation keeps as a queue, so a merged record waits behind the records that are still to do, and keeps as a list.
Example
The rule is "the same email, or the same name and the same phone", and merge is the union of the values.
| record | name | phone | |
|---|---|---|---|
| r1 | ann | p1 | |
| r2 | ann | e1 | |
| r3 | p1 | e1 | |
| r4 | bob | p1 |
Of the 6 pairs, only r2 and r3 match. The transitive closure of the pairs gives the clusters {r1}, {r2, r3} and {r4}. R-Swoosh runs as follows.
| step | taken from R | compared with | result | R' after |
|---|---|---|---|---|
| 1 | r1 | none | no match | r1 |
| 2 | r2 | r1 | no match | r1, r2 |
| 3 | r3 | r1, r2 | match r2: m = (ann, p1, e1) goes to R | r1 |
| 4 | r4 | r1 | no match | r1, r4 |
| 5 | m | r1 | match r1 (same name and phone): m' = (ann, p1, e1) from r1, r2, r3 goes to R | r4 |
| 6 | m' | r4 | no match | r4, m' |
The output is {r1, r2, r3} and {r4}, after 6 calls. The merged record of r2 and r3 has both a name and a phone, so it matches r1, which neither part matched. Record r4 shares the phone but not the name, so it stays apart.
A larger run. On generated data with 40 people and 108 records (119 true duplicate pairs, Python seed 42), with copies that lose their email or phone, R-Swoosh made 3488 calls (all pairs are 5778) and returned 46 clusters with pairwise precision 0.926 and recall 0.840. Precision is below 1 because some people share a name and a phone number. On this data the clusters were the same as the closure of the pairwise matches. These numbers are measurements on that data only.
Correctness
Each step either moves a record to or merges it, so never holds two records that match. The merge of two records dominates both of them, and domination is a partial order under ICAR. From these facts, every input record is dominated by an output record. The set of records dominated by an output record is also closed under merges, so it covers all of . Since no two output records match, each one is maximal. So under ICAR the output is exactly , for any order of the input. Without the properties the output can be wrong, and the paper gives G-Swoosh for that case. The full proof is in the proof page.
Proof: Under the ICAR properties R-Swoosh returns the maximal records of the merge closure, with at most (n-1)^2 match callsfull
We use the pseudocode of the page. is the input, a finite set of records. We write for and for , which is defined when . The merge closure is the smallest set of records that contains and contains for all in it with . The record is dominated by , written , if and .
The ICAR properties are:
- Idempotence. and for every record .
- Commutativity. if and only if , and then .
- Associativity. whenever both sides are defined.
- Representativity. If and , then .
Termination and the bound on the calls hold for any functions and that always return. The correctness part uses ICAR.
Termination and the number of calls
Let and . A step is one run of lines L3 to L8. In a no-match step line L7 runs, the step makes calls, and becomes . In a merge step line L8 runs, the step makes at most calls, and becomes , because leaves , the merged record enters , and the buddy leaves .
So falls by one in each merge step and stays the same in each no-match step. It starts at and is never negative, so there are at most merge steps. The value never grows, and each no-match step lowers it by one, so there are at most no-match steps. The loop stops after at most steps, and it stops only when , so there are exactly no-match steps. If the output has records, then fell from to , so there are exactly merge steps and steps.
Lemma 1. The number of calls is at most for .
Proof. The calls are at most the sum of before each step. The sequence of steps is a word of no-match steps (N) and merge steps (M). The last step is N, because only N makes . A merge step needs before it, and every step needs , which holds for any order of the first steps because they hold only no-match steps. Exchanging an adjacent pair MN among these steps for NM changes the two values of before these steps from to , so the sum grows by 2. Hence the sum is largest for the word . Its values of are , then , then . The sum is
For the bound is , and the tests reach it for each with a match rule that makes each merged record match only the last record of . For there are no merge steps, and the count is exactly .
Correctness under ICAR
Lemma 2 ( is a partial order). Reflexive: and by idempotence. Antisymmetric: if and , then by commutativity. Transitive: let . From and , representativity gives , so is defined. Also is defined, and associativity gives .
Lemma 3 (a merge dominates its parts). If and , then and .
Proof. From and , representativity gives . Both and are defined, so associativity gives . So . By commutativity , and the same argument gives .
Let be the list at line L9.
Lemma 4 (invariants). At the start of each step: (a) every record in is in ; (b) no two records at different positions of match; (c) every record of is dominated by some record in .
Proof. All three hold at the start, with and , using reflexivity for (c). (a) A step adds only , which is already there, or with and , which is in by its definition. (b) Line L7 adds to only after lines L5 and L6 found that matches no record of , and line L8 only removes a record from . (c) A no-match step moves from to . A merge step removes and its buddy and adds , and , by Lemma 3. A record of that or dominated is now dominated by , by transitivity (Lemma 2).
Theorem. Under ICAR, is exactly the set of maximal records of under , with each record once.
Proof. At the end , so by Lemma 4, , no two records of match, and every record of is dominated by a record of . Two equal records match by idempotence, so the records of are distinct.
Let . We show that is closed under merges. Let and with and . From and , representativity gives . From and , it gives . No two different records of match, so . Let . From , representativity gives . Both and are defined, and associativity gives . So and .
contains and is closed under merges, so : every record of is dominated by a record of .
Now let and with . Then for some , so by transitivity. If , they would match, which (b) forbids. So , and gives by antisymmetry. So every record of is maximal in . Conversely, let be maximal in . Then for some , and maximality gives .
Remarks. The result does not depend on the order in which line L3 takes records from or on the order of the scan in line L5, because the set of maximal records of does not. The number of calls does depend on these orders. Without representativity the theorem can fail: R-Swoosh drops and its buddy after a merge, and a later record that matches but not the merged record is then never merged with the information of .
Complexity
- Calls. There are exactly steps without a match and merge steps, where is the size of the output. The number of match calls is at most , so at most . With no matches it is exactly .
- Best case. If every record matches the first resolved record, each step makes at most one call, about in total.
- Time. The calls times the cost of one call to , plus calls to . In practice the match rule is the main cost.
- Space. At most records in and together, but a merged record can be as large as all its parts.
Properties
- Exact under ICAR. The output equals when the four properties hold. It is a heuristic when they do not.
- Order independent result. The output does not depend on the input order, but the number of calls does.
- No transitive closure needed. Merging replaces the closure step of pairwise methods, and it can join more records than the closure of the pairs.
- Black box. It needs nothing about the records except the two functions. It does not build an index, so it compares more pairs than blocking methods.
Variants and improvements
- G-Swoosh. Makes no assumption on the functions. It compares all pairs of records, merged ones included, keeps the source records, and removes dominated records at the end. It can make many more calls.
- F-Swoosh. Assumes the match rule is a disjunction of feature comparisons. It records the feature values already compared, so a merged record does not repeat comparisons that failed before.
- With blocking. On large data, R-Swoosh runs inside each block of a blocking or sorted neighborhood pass, which cuts the quadratic cost.
When to use it
Use it when you have a reliable match rule and a merge that keeps all information, such as the union of attribute values, and want merged records instead of clusters of pairs. It suits small or blocked inputs, because its cost is quadratic. When the match rule gives a score instead of a yes or no, a probabilistic model such as Fellegi-Sunter decides the pairs, and a closure with union-find groups them.
Pitfalls
- A merge that loses values. If merge keeps only one of two values, for example the longer name, representativity can fail, and a record that matched a part no longer matches the merged record.
- Rules with thresholds. A rule such as "similarity at least 0.8" on a merged record is often not representative, because the merged value can be farther from a third record than one of its parts.
- Idempotence of the rule. A record must match itself. With the rule of the example, a record with no email and no phone does not, so the theory does not cover it.
- Large merged records. Each merge makes a larger record, and the cost of a match grows with it.
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/r-swoosh/. The authors are listed in prov/92B1R4.jsonl.
"""R-Swoosh: generic entity resolution with black-box match and merge functions.
match(r, s) returns a bool and merge(r, s) returns a new record; merge is called
only on records that match. When the two functions have the ICAR properties
(idempotence, commutativity, associativity, representativity), the result is
the set of maximal records of the merge closure of the input.
The module also has a record type for tests and examples: a record is a pair
(values, ids), where values is a frozenset of (attribute, value) pairs and ids
is the frozenset of input record numbers merged into it. union_merge and
rule_match below have the ICAR properties.
"""
from collections import deque
def r_swoosh(records, match, merge):
"""Return (resolved records, number of match calls)."""
R = deque(records) # @line L1
done = [] # @line L1
calls = 0
while R: # @line L2
r = R.popleft() # @line L3
buddy = None # @line L4
for k, other in enumerate(done): # @line L5
calls += 1
if match(r, other): # @line L6
buddy = k # @line L6
break # @line L6
if buddy is None: # @line L7
done.append(r) # @line L7
else:
other = done.pop(buddy) # @line L8
R.append(merge(r, other)) # @line L8
return done, calls # @line L9
def comparison_bound(n, j):
"""The worst case number of match calls for n inputs and j outputs: (n-1)^2 - (j-1)(j-2)/2."""
if n == 0:
return 0
return (n - 1) ** 2 - (j - 1) * (j - 2) // 2
def make_record(i, **fields):
"""A record with the input number i and the given attribute values (None means missing)."""
values = frozenset((a, v) for a, v in fields.items() if v is not None)
return (values, frozenset([i]))
def union_merge(r, s):
"""Merge by union of the values and of the input numbers."""
return (r[0] | s[0], r[1] | s[1])
def shares(r, s, attr):
vr = {v for a, v in r[0] if a == attr}
return any((attr, v) in s[0] for v in vr)
def rule_match(r, s):
"""Match if the records share an email, or share both a name and a phone."""
return shares(r, s, "email") or (shares(r, s, "name") and shares(r, s, "phone"))
def dominated(r, s, match, merge):
"""r <= s: r matches s and merging r into s gives s."""
return match(r, s) and merge(r, s) == s
def merge_closure(records, match, merge, limit=100000):
"""The smallest set that holds the input and is closed under merges of matching records."""
S = set(records)
frontier = list(S)
while frontier:
new = []
items = sorted(S, key=repr)
for x in frontier:
for y in items:
if x != y and match(x, y):
z = merge(x, y)
if z not in S:
S.add(z)
new.append(z)
if len(S) > limit:
raise ValueError("closure too large")
items = None
frontier = new
return S
def maximal_records(records, match, merge):
"""ER(I) under ICAR: the records of the merge closure that no other record dominates."""
S = merge_closure(records, match, merge)
return {x for x in S if not any(y != x and dominated(x, y, match, merge) for y in S)}
test_r_swoosh.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/r-swoosh/. The authors are listed in prov/92B1R4.jsonl.
import random
import unittest
from r_swoosh import (
comparison_bound,
make_record,
maximal_records,
r_swoosh,
rule_match,
union_merge,
)
EMAILS = ["e1", "e2", "e3", "e4"]
NAMES = ["ann", "bob", "cal"]
PHONES = ["p1", "p2", "p3"]
def random_records(rng, n):
out = []
for i in range(n):
while True:
email = rng.choice(EMAILS + [None, None])
name = rng.choice(NAMES + [None])
phone = rng.choice(PHONES + [None])
# Every record matches itself, so the match rule is idempotent.
if email is not None or (name is not None and phone is not None):
break
out.append(make_record(i, email=email, name=name, phone=phone))
return out
class TestRSwoosh(unittest.TestCase):
def test_page_example(self):
r1 = make_record(1, name="ann", phone="p1")
r2 = make_record(2, name="ann", email="e1")
r3 = make_record(3, phone="p1", email="e1")
r4 = make_record(4, name="bob", phone="p1")
out, calls = r_swoosh([r1, r2, r3, r4], rule_match, union_merge)
self.assertEqual(sorted(sorted(r[1]) for r in out), [[1, 2, 3], [4]])
self.assertEqual(calls, 6)
# The pairs alone match only r2 and r3.
recs = [r1, r2, r3, r4]
pairs = [(a + 1, b + 1) for a in range(4) for b in range(a + 1, 4) if rule_match(recs[a], recs[b])]
self.assertEqual(pairs, [(2, 3)])
def test_against_merge_closure(self):
rng = random.Random(20261118)
for _ in range(300):
n = rng.randint(0, 7)
recs = random_records(rng, n)
out, calls = r_swoosh(recs, rule_match, union_merge)
self.assertEqual(len(out), len(set(out)))
self.assertEqual(set(out), maximal_records(recs, rule_match, union_merge))
for a in range(len(out)):
for b in range(a + 1, len(out)):
self.assertFalse(rule_match(out[a], out[b]))
self.assertLessEqual(calls, comparison_bound(n, len(out)))
def test_order_does_not_change_result(self):
rng = random.Random(9)
for _ in range(100):
recs = random_records(rng, rng.randint(1, 8))
first, _ = r_swoosh(recs, rule_match, union_merge)
shuffled = recs[:]
rng.shuffle(shuffled)
second, _ = r_swoosh(shuffled, rule_match, union_merge)
self.assertEqual(set(first), set(second))
def test_bound_is_reached(self):
# A match rule (not ICAR) that makes every match the last record of R'.
for n in range(1, 10):
def match(r, s, n=n):
u = r | s
return not (r & s) and (n - 1) in u and max(u) - min(u) + 1 == len(u)
recs = [frozenset([i]) for i in range(n)]
out, calls = r_swoosh(recs, match, lambda r, s: r | s)
self.assertEqual(out, [frozenset(range(n))])
self.assertEqual(calls, comparison_bound(n, 1))
self.assertEqual(calls, (n - 1) ** 2)
# The ICAR rule of the page reaches the bound 4 for n = 3.
r1 = make_record(1, name="ann", phone="p1")
r2 = make_record(2, name="ann", email="e1")
r3 = make_record(3, phone="p1", email="e1")
out, calls = r_swoosh([r1, r2, r3], rule_match, union_merge)
self.assertEqual(len(out), 1)
self.assertEqual(calls, 4)
def test_no_matches(self):
for n in range(0, 12):
recs = [make_record(i, email="x%d" % i) for i in range(n)]
out, calls = r_swoosh(recs, rule_match, union_merge)
self.assertEqual(len(out), n)
self.assertEqual(calls, n * (n - 1) // 2)
self.assertLessEqual(calls, comparison_bound(n, n))
def test_precision_recall_synthetic(self):
rng = random.Random(42)
recs, truth = [], []
for e in range(40):
email = "mail%d" % e
name = rng.choice(["ann", "bob", "cal", "dan", "eve", "fay", "gus", "hal"])
phone = "ph%d" % rng.randint(0, 59)
for _ in range(rng.randint(1, 4)):
fields = {"email": email, "name": name, "phone": phone}
drop = rng.random()
if drop < 0.4:
fields["email"] = None
elif drop < 0.6:
fields["phone"] = None
if fields["email"] is None and fields["phone"] is None:
fields["phone"] = phone
if fields["email"] is None and fields["name"] is None:
fields["name"] = name
recs.append(make_record(len(recs), **fields))
truth.append(e)
out, calls = r_swoosh(recs, rule_match, union_merge)
found = set()
for r in out:
ids = sorted(r[1])
found |= {(a, b) for i, a in enumerate(ids) for b in ids[i + 1:]}
n = len(recs)
true = {(a, b) for a in range(n) for b in range(a + 1, n) if truth[a] == truth[b]}
hit = len(found & true)
precision = hit / len(found)
recall = hit / len(true)
self.assertEqual(sum(len(r[1]) for r in out), n)
# The numbers on the page: 108 records, 119 true pairs, 46 clusters.
self.assertEqual((n, len(true), len(out), calls), (108, 119, 46, 3488))
self.assertEqual(round(precision, 3), 0.926)
self.assertEqual(round(recall, 3), 0.840)
self.assertLessEqual(calls, comparison_bound(n, len(out)))
if __name__ == "__main__":
unittest.main()
History
Benjelloun, Garcia-Molina, Menestrina, Su, Whang and Widom of the Stanford InfoLab described the generic model of entity resolution and the Swoosh family of algorithms in The VLDB Journal in 2009. The model treats match and merge as black boxes given by a domain expert and asks which properties of these functions make the result well defined and the algorithms efficient. The paper defines the ICAR properties, the domination order and the result , and gives G-Swoosh for arbitrary functions, R-Swoosh for ICAR functions and F-Swoosh for feature-level rules. It also compares the algorithms in experiments on real data.
References
- Omar Benjelloun, Hector Garcia-Molina, David Menestrina, Qi Su, Steven Euijong Whang and Jennifer Widom, Swoosh: a generic approach to entity resolution, The VLDB Journal 18(1), 2009, pages 255 to 276, the generic model with match and merge functions, the ICAR properties and the domination order, and the algorithms G-Swoosh, R-Swoosh and F-Swoosh with their experiments
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 92B1R4 Edit this page History Report an error Markdown