DEV Community

Cover image for Is this the same customer? Explainable record linkage inside PostgreSQL, coming to Fuzzphony 1.1
Szj
Szj

Posted on Edited on

Is this the same customer? Explainable record linkage inside PostgreSQL, coming to Fuzzphony 1.1

William Smith, born 1975-03-12 in the CRM. Bill Smith, born 1975-12-03 in the billing system. Smith William in an import from 2019, with no birth date at all. Every business database I have worked with has rows like these: the same person (or the same company) entered three times by three people who never saw each other's work. LIKE '%smith%' finds all of them and a thousand other Smiths. A fuzzy search ranks them better, but it still cannot answer the question someone actually asks: are these the same customer, and why do you think so?

That question is what the next release of Fuzzphony adds, as an experimental part of the same package. Before I get to it, a short introduction, because most of you have never heard of the library.

Fuzzphony in one paragraph

Fuzzphony is a typo-tolerant, ranked full-text search library for PHP and Symfony applications that already run PostgreSQL. It uses what PostgreSQL ships with (pg_trgm for typos, unaccent for accents, full-text search for stemming in 28 languages) and keeps its index in a sidecar table next to your data. It never alters your tables, so it works on databases you are not allowed to change: a legacy ERP, tables another team owns. There is no search server to run, feed or secure. It has been stable since 1.0 (the current release is 1.0.2), and the public API (83 types, the bundle configuration keys and the console commands) follows Semantic Versioning.

$result = $fuzzphony->in(Product::class)
    ->query('wireles mouse -cable')          // a typo and an exclusion
    ->where('price', '<=', 20_000)
    ->highlight('name')
    ->get();
Enter fullscreen mode Exit fullscreen mode

The first post was about why it exists. This one is about where it stands now, and where it is going.

The Symfony and PHP side

If you write Symfony, the integration is the part you touch every day:

  • A bundle and attributes. Mark a Doctrine entity with #[Searchable], its properties with #[SearchField('A', fuzzy: true)] and #[SearchFilter], and the bundle builds the index definition. YAML and a PHP builder are there for tables without an entity, and fuzzphony:wizard writes a definition for an existing table, joins included.
  • Doctrine. The bundle uses your DBAL connection, can write a Doctrine migration instead of applying DDL (fuzzphony:schema --dump-migration=migrations), and the ORM sync mode refreshes the index from Doctrine's flush.
  • A demo you can run. A full Symfony app with a seeded catalogue of 500,000 products (about a minute to index), an ERP-like data set, Live Components and a search box in the header that searches every index at once. One docker compose up.
  • Current PHP, current Symfony. PHP 8.4+. CI runs PHP 8.4 and 8.5 against PostgreSQL 15, 16, 17 and 18, with Symfony 7.4 LTS and 8.1, plus a job against the next Symfony minor as an early warning.

What an enterprise team asks first

Is the index ever out of step with the data? The index lives in the same PostgreSQL as the data: no dual write, no second system that can disagree. In trigger mode a row and its index entry change in one transaction; in queue mode within one worker batch. A search is an ordinary read query, so it sees what your transaction sees.

Who may see what? Authorization is part of the engine, not a filter in your controller. A tenant-scoped index refuses a search without a tenant. A field can be granted to a role, and a field a viewer may not see is not matched, ranked, highlighted, counted or suggested from. Tests prove that the content of a hidden field cannot change a restricted viewer's results (ids, ranks, totals, facets, highlights). Since 0.10, a search that names no actor is made as the current user; a cron job has to say ->asSystem() explicitly.

How do we operate it?

  • fuzzphony:doctor checks the PostgreSQL version and extensions, schema drift, invalid indexes, the age of the sync queue and the index coverage, and prints the fix for anything it finds.
  • fuzzphony:schema prints idempotent DDL for review, --apply runs it (safe to run under load and in parallel), and --dump-grants prints the GRANTs for least-privilege database roles (search, worker, admin), so the web process never needs DDL rights.
  • fuzzphony:worker drains the sync queue; several workers can run side by side, the worker and reindex hold advisory locks, and a batch that fails on one row is split down to that row instead of stopping the queue.
  • A reindex is built next to the live index and swapped in, and it can resume.
  • The next release adds a production runtime checklist (docs/production.md): OPcache and preload, persistent connections or PgBouncer in transaction mode, PostgreSQL jit=off, worker limits, a measured batch_size table.

Our keys have two columns. Also coming in 1.1.0: composite ids. An index can be identified by up to 8 columns (id: [order_id, line_no], or a Doctrine composite identifier), a watch can key on several columns, and every sync mode follows them. A 200,000-row reindex of a composite-id index takes about 1.7 times the single-id time.

How big can it get? Measured up to 1,000,000 documents per index: a typical search takes from a few milliseconds to about a hundred; the commonest words, many-word queries and typo searches on wide indexes take longer. On 200,000 products a warm search takes a few milliseconds for a rare word and about 10 to 90 ms with typos, accents and stemming. Beyond a few million documents per index I have not measured; measure before you commit.

The new part: record linkage (experimental, coming in 1.1.0)

Record linkage (or entity resolution) is the problem from the first paragraph: given a person or a company, partly filled and possibly misspelt, which existing rows are the same real-world entity? It is not search. Linkage has to know that Bill is William, that 03-12 and 12-03 may be one date typed in two conventions, that a matching tax id says far more than a matching city, and that a common name agreeing says less than a rare one.

It ships inside the same package (Fuzzphony\RecordLinkage), opt-in: nothing is registered or built unless you add the fuzzphony.linkage key. It is experimental: its configuration keys and commands stay outside the backward-compatibility promise until a later minor declares them stable. 1.1.0 is not released yet; everything below is on a branch and may still change.

How it works

Candidates come from the index you already have. A profile names an existing Fuzzphony index and the fields to compare. The lookup runs a few blocking passes in one SQL statement: rows with the same tax id, rows born on the same date (also with day and month swapped, or one year off) whose name is close, rows whose name is close by trigram similarity. All of these read the sidecar's normalised text, its typed filter columns and its trigram index. Linkage adds no sidecar column and no sync code of its own, so candidates are as fresh as your search.

Each candidate is scored with the Fellegi-Sunter model. Every comparator puts a field pair into one of a few levels. The person name comparator has levels like exact, same_tokens, nickname, via_birth_name (a married name against the maiden name), family_given_close and disagree; the date comparator has exact, swapped, one_off, same_year; the identifier comparator distinguishes exact_valid from exact_invalid, because a checksum tells it whether a tax id is real. For each level the model holds two probabilities: m, how often true matches land there, and u, how often random pairs do. A field contributes log2(m/u) bits; the candidate's weight is the sum plus the prior log-odds, and that becomes a probability and a verdict: match, review or non_match (default thresholds 0.95 and 0.50).

The weights are learned from your data, per tenant, without labels. fuzzphony:linkage:train person estimates u from seeded random pairs and m by expectation-maximisation, starting from the comparators' priors. Identifiers act as anchors (so members of one household are not learned as "the same person"), common names count less than rare ones, and the same data and seed give the same weights. Weights are versioned per profile and tenant (the last five are kept); a run that did not converge is stored but not activated unless you force it. Each tenant trains on its own rows only; a tenant with fewer than 1,000 rows is refused, and a lookup without trained weights fails with LinkageNotTrained instead of guessing.

Every decision is explained. A candidate comes back with its probability, its weight in bits, the blocking passes that found it, and one line per field: the level, its bits, m, u, the similarity and a note. When a reviewer asks why two rows were matched, the answer is "tax id exact and valid, birth date day/month swapped, name a nickname", not a score.

Locales are data. Name order, titles, married-name forms, nicknames (Bill to William, Pista to István) and legal forms live in locale packs, plain PHP arrays. English and Hungarian ship; adding a language is a data file, not code. Identifier schemes with checksum or format validation cover the Hungarian tax id, tax number and company registration number, and the US EIN, UK company number and UK National Insurance number.

It is gated like a search. A lookup needs the tenant, takes a rate-limit token, passes the index guards and a FUZZPHONY_LINK authorization attribute, and writes a search-log row with the probe's keys, never its values. A granted field cannot be compared at all: restricted identifiers belong in a separate index, so linkage only uses what the caller may see.

Defining a profile

The profile sits next to an ordinary index. The date comparator needs a date filter, and the name comparators read fuzzy fields:

fuzzphony:
  indexes:
    people:
      source:
        query: |
          SELECT id, name, birth_name, mother_name, birth_place, birth_date,
                 regexp_replace(coalesce(tax_id, ''), '[^0-9]', '', 'g') AS tax_id
          FROM person
      fields:
        name: { weight: A, fuzzy: true }
        birth_name: { weight: B, fuzzy: true }
        mother_name: { weight: C, fuzzy: true }
        birth_place: { weight: C, fuzzy: true }
      filters:
        birth_date: date
        tax_id: string
      language: simple

  linkage:
    profiles:
      person:
        index: people
        locales: [hu, en]
        compare:
          name: { comparator: person_name, also_against: birth_name }
          mother_name: person_name
          birth_date: date
          birth_place: place
          tax_id: { comparator: identifier, scheme: hu.tax_id }
        block:
          - tax_id
          - { key: birth_date, swapped: true, with: name }
          - name
        thresholds: { match: 0.95, review: 0.50 }
Enter fullscreen mode Exit fullscreen mode

One detail is deliberate: there is no separate comparator for birth_name. For everyone who never married it is a copy of name, and comparing it twice would count one agreement twice (Fellegi-Sunter assumes independent fields); also_against lets the name reach it instead. The same profile can be written as a class with #[AsLinkProfile('person', index: 'people')] and a build(LinkProfile $profile) method.

A lookup

bin/console fuzzphony:linkage:train person
bin/console fuzzphony:linkage:match person -s name="Bill Smith" -s birth_date=1975-12-03
Enter fullscreen mode Exit fullscreen mode

From PHP, the Linker is a service:

use Fuzzphony\RecordLinkage\Linker;

// made as the current user, like a search; a tenant-scoped index adds ->forTenant($tenantId)
$result = $linker->profile('person')
    ->match(['name' => 'Bill Smith', 'birth_date' => '1975-12-03']);

foreach ($result->candidates as $candidate) {
    echo $candidate->id, ' ', $candidate->verdict->value, ' ', round($candidate->probability, 3), PHP_EOL;
    foreach ($candidate->fields as $field) {
        printf("  %-12s %-16s %+.2f bits\n", $field->name, $field->level, $field->weight);
    }
}
Enter fullscreen mode Exit fullscreen mode

$result->ignored says which probe keys were not used and why, $result->weightsVersion which trained version answered, and the whole result is JsonSerializable for an API or a review screen.

What I measured, and what it does not prove

There is no public data set of messy Hungarian and English people and companies with a known truth, so I wrote a generator. It draws real-looking entities (common names with Zipf weights, valid tax ids with check digits, companies with legal forms) and writes one to four rows per entity, each corrupted independently: typos in 15% of names, accents dropped, nicknames, married forms, swapped name order, day and month swapped, years off by one, missing fields, wrong digits in ids. Every row carries the id of its real entity in a column the index never reads, so precision and recall can be measured exactly. It is fast enough to use (100,000 rows in 6.6 s, 1,000,000 in 31.7 s on a throwaway container) and deterministic per seed.

Candidate retrieval, 100,000 rows (75,000 people, 25,000 companies), 2,000 probes each, warm cache, one lookup at a time:

profile true pairs among the candidates p50 p95 p99
person 99.76% 7.0 ms 30.2 ms 71.1 ms
company 99.26% 4.3 ms 9.0 ms 17.5 ms

No pass fell back to a sequential scan of the sidecar. Recall here means: the true duplicate was among the scored candidates, so the model had a chance to see it. It does not depend on the weights.

Trained against prior weights, 20,000 rows, precision / recall of the predicted pairs:

profile weights P >= 0.50 P >= 0.95
person priors 87.3 / 99.2 96.1 / 98.9
person trained 90.2 / 99.2 96.8 / 99.2
company priors 58.8 / 98.8 87.2 / 98.4
company trained 71.6 / 98.9 90.9 / 98.7

Training gains most where the hand-set priors are weakest. It is not a clean win everywhere: trained precision is below the priors for people at P >= 0.99 (98.3 against 98.7) and for companies at P >= 0.80 (81.3 against 83.1); recall is never lower. Companies are the weak spot: the generator builds company names from small word pools, so many different companies share a name and a city and differ only in ids that are often missing. Training a person profile took 108 s at 20,000 rows, a company profile 26 s.

What this proves: on data shaped like this, the blocking finds almost every true pair, a lookup is fast enough for an interactive form at 100,000 rows, and EM mostly improves on hand-set priors. What it does not prove: anything about your data. The corruptions are the ones I thought of, at rates I chose; real data has its own. The design target is 10 million rows at p95 under 50 ms; I have not measured that, so I do not claim it.

Shipped, coming in 1.1.0, later

Shipped (1.0.2): the search engine, attributes, YAML and builder, trigger/queue/ORM sync, the worker and the doctor, zero-downtime reindex, tenants and granted fields with hidden-field independence, multi-source indexes, fields with several values, facets, synonyms, "did you mean", the search log and analytics, metrics, the 500,000-row demo.

Coming in 1.1.0 (not released yet):

  • Built on the branch: composite ids and watch keys; the production checklist; record linkage lookup with training, versioned weights, the doctor checks and the commands; retraining by the worker (when the doctor would ask for it: no weights, a changed profile, rows drifted by 25%; by default at most once a day, optionally only in a night window).
  • Still being built for the same release: batch deduplication of a whole index into clusters, with a chaining guard (A matches B and B matches C does not pull C into A's cluster when A and C strongly disagree), a review queue, stored human decisions that survive a rerun and a retrain, and a demo page on 100,000 synthetic rows. If one of these slips, the release notes will say so.

Later, not decided: more locale packs, an address comparator at street level, a numeric-proximity comparator, incremental deduplication through the sync (a new row joining its cluster on insert), an example profile that is neither a person nor a company, hybrid lexical and semantic search with pgvector, and a Laravel Scout driver over the same engine.

Who should use it, and who should not

Fuzzphony fits if you run PostgreSQL and want search (and soon matching) without another service: admin panels, back offices, CRMs, shared-schema multi-tenant SaaS, databases you are not allowed to change. Record linkage fits duplicate customers or suppliers, an import that must not create a second copy of a company, or a "have we seen this person before" form, provided a locale pack covers the names (English and Hungarian today).

It does not fit:

  • Analytics-style aggregations over millions of rows. That is a job for a column store or your BI tool.
  • Semantic or vector search ("comfortable shoes for standing all day"). Fuzzphony matches words, not meaning. pgvector is on the ideas list, not in the code.
  • A database other than PostgreSQL. The engine is PostgreSQL only, deliberately.
  • More than a few million documents per index, without measuring first. I have measured to one million.
  • Record linkage you need to be stable today. It is experimental, its configuration may change in a minor release, and its numbers come from synthetic data.

Try it

The demo is one command: https://github.com/er2es/fuzzphony/blob/main/demo/README.md

The library is composer require fuzzphony/fuzzphony; the docs, recipes and benchmarks are in the repository. If it is useful to you, a star helps other people find it. If something breaks, an issue helps me more.

And one specific request: if you have ever deduplicated customers or suppliers, tell me what your messiest duplicates looked like. The record linkage part is still experimental precisely so that feedback like that can change it before 1.1.0 is tagged.

Top comments (0)