dedupe

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package dedupe decides which records are the same thing and which disagree.

Both questions start from the same comparison, so they live together. When two records agree they merge, and the merge keeps the records it was made from. When they disagree the disagreement is a Conflict: a value the caller can read, rank and settle. Nothing is dropped for being unresolvable — an unsettled Conflict is a result, not an error.

Work that is quadratic in the input takes a context and can be cancelled; linear work does not, so the common calls stay short.

Index

Constants

This section is empty.

Variables

View Source
var Apart = Disjoint{
	"person":       {"organization", "organisation", "company", "institution", "location", "place"},
	"organization": {"person", "location", "place"},
	"organisation": {"person", "location", "place"},
	"company":      {"person", "location", "place"},
	"institution":  {"person"},
	"location":     {"person", "organization", "organisation", "company"},
	"place":        {"person", "organization", "organisation", "company"},
}

Apart is the default exclusion table: a thing is not both a person and an organisation, and not both a place and either.

View Source
var Dates = []string{
	"founded", "founded_year", "established", "created",
	"timestamp", "date", "start", "end", "start_date", "end_date",
}

Dates are the properties read as points in time when Times is given none.

View Source
var Default = Opt{Like: 0.7, Score: 0.6}

Default asks a pair to look 0.7 alike and to end 0.6 sure. It is strict enough that what it returns is worth merging without review.

View Source
var ErrEmpty = errors.New("no entities")

ErrEmpty reports a merge with nothing to merge.

View Source
var ErrOption = errors.New("bad option")

ErrOption reports an option outside its allowed range.

Functions

func Alike

func Alike(a, b semantic.Triple, c Canon, m Metric) float64

Alike scores two assertions on 0 to 1. Assertions about different subjects are not about the same thing and score 0. Otherwise the predicate carries most of the weight and the object the rest, because two documents that agree on the object while naming the relation differently are usually saying one thing, and two that agree on the relation while naming different objects are usually not.

func Claims

func Claims(es []Entity, prop string) map[string][]Claim

Claims returns every value stated for prop, with the document that stated it, keyed by the thing it was stated about. It is the record of who said what, which is what a disagreement is settled from.

func Cosine

func Cosine(a, b []float32) float64

Cosine scores two vectors on 0 to 1: the cosine of the angle between them, mapped from -1..1 so it composes with the string scores. Vectors of different lengths, and vectors of length zero, score 0.

func Hash

func Hash(s string) uint64

Hash is the SimHash of a text: 64 bits over its words, in which two texts sharing most of their words differ in few bit positions. Unlike a digest it is meant to be compared, not looked up — Near is the comparison.

It costs one pass over the text and 8 bytes to keep, which is what makes it worth having: a million texts can be held in memory and compared without their words.

func Near

func Near(a, b uint64) float64

Near scores two SimHashes on 0 to 1: one minus the share of the 64 bits they differ in. Identical texts score 1; unrelated texts score near 0.5, which is where half the bits differ by chance — Near is a screen, not a verdict, and the pairs it lets through are still compared properly.

func Repeats

func Repeats(ctx context.Context, ts []semantic.Triple, c Canon, like float64, m Metric) ([][2]int, error)

Repeats reports the assertions in ts that say the same thing as another, as index pairs into ts, lower index first. A pair is reported when it scores at least like.

Indices rather than triples, because the caller knows what each index meant and a copy of the triple would lose that.

func Text

func Text(a, b string, m Metric) float64

Text scores how alike two strings are, on 0 to 1. An empty string scores 0 against anything, equal strings score 1, and the metric decides the rest. The zero Metric is Jaro.

func Unique

func Unique(ts []semantic.Triple, c Canon) []semantic.Triple

Unique returns ts with repeated assertions removed, keeping the first spelling of each. Two triples repeat when they fold to the same canonical key, so "works at" and "WORKS_AT" under a synonym table are one claim.

The kept triple's score is raised to the best any repetition carried: the same claim found twice is better evidence than the same claim found once.

Types

type Canon

type Canon struct {
	Synonyms map[string]string
	Fold     bool
}

Canon folds a triple to the form comparisons are made on: the predicate mapped through a synonym table, and, when Fold is set, the predicate and object reduced to their words — lower case, single spaces, underscores and hyphens read as spaces, so works_at and "Works At" are one relation. The zero value folds nothing but case in the predicate.

func (Canon) Key

func (c Canon) Key(t semantic.Triple) [3]string

Key returns the triple as it is compared: subject, canonical predicate, canonical object.

type Claim

type Claim struct {
	Value any
	From  Source
}

Claim is one value as one document stated it. Values and their sources are held together because every way of settling a disagreement needs both: what was said and who said it.

type Clash

type Clash struct {
	Prop   string
	Values []any
	Took   any
	How    Keep
}

Clash is one property two records gave different values, and the value the merge took.

type Conflict

type Conflict struct {
	ID      string
	Kind    Kind
	Subject string // the thing, or the subject of the relation, disagreed about
	Prop    string
	Values  []Claim
	Score   float64 // confidence the disagreement is real
	Level   Level
	Advice  string
}

Conflict is one disagreement, whole. It carries every value asserted, the document behind each, how sure the disagreement is real and how much it matters. It is a value the caller reads, ranks and settles — never an error, because refusing to return an assertion is how a graph loses what a document said.

func Conflicts

func Conflicts(es []Entity, w Watch) []Conflict

Conflicts runs every check Watch asks for and returns what they found, in one list. Each check names its conflicts differently, so a value and a date disagreeing about the same property are two findings, not one repeated.

func Edges

func Edges(ts []semantic.Triple, c Canon, many map[string]bool) []Conflict

Edges reports subjects given more than one object for one relation. A predicate named in many may hold several objects and is not checked; with no such table every predicate is read as admitting one object, which is the strict reading and the one to start from.

func Excludes

func Excludes(es []Entity, d Disjoint) []Conflict

Excludes reports entities their documents call two kinds that cannot both hold. Given no table it uses Apart. One conflict is reported per entity: the first excluded pair found is enough to say the classification is wrong.

func Limits

func Limits(es []Entity, lim map[string]Limit) []Conflict

Limits reports values outside the range declared for their property. This is the one disagreement a single document can hold on its own: it is at odds with what the property means, not with another document.

func Overlaps

func Overlaps(es []Entity, from, to string) []Conflict

Overlaps reports the entities whose documents give spans that run over one another without agreeing. Two documents that date a fact to separate spans may both be right — the fact held twice. Two that date it to spans sharing a day cannot: one of them is wrong about when.

func Times

func Times(es []Entity, props ...string) []Conflict

Times reports the entities whose documents date them differently. Values are compared by the year they name, so "founded 1998" and 1998 agree while 1998 and 2004 do not. Given no properties it reads Dates.

func Types

func Types(es []Entity) []Conflict

Types reports the entities their documents call different kinds. Any two kinds disagree here; whether they can both be true is what Excludes asks.

func Values

func Values(es []Entity, prop string) []Conflict

Values reports the entities whose documents give prop different values. One document stating a value is not a disagreement, so an entity described only once is never reported.

type Disjoint

type Disjoint map[string][]string

Disjoint names the kinds that cannot both describe one thing, each kind against the kinds it excludes. Keys and values are compared folded.

type Entity

type Entity struct {
	ID     string
	Name   string
	Kind   string // what it is: Person, Company, Place
	Props  map[string]any
	Edges  []semantic.Triple
	Vector []float32
	Score  float64 // confidence in this record; 0 means unstated
	From   Source  // the document it came from
	Meta   map[string]any
}

Entity is one record about one thing, as a single source stated it. The same thing described by two documents is two Entity values sharing an ID and differing somewhere else — which is what a Conflict is made of.

func Loose

func Loose(es []Entity, gs []Group) []Entity

Loose returns the records no group claimed, in the order they were given. They are not leftovers: a record that matched nothing is a record about something only one document mentions.

func (Entity) Value

func (e Entity) Value(prop string) (any, bool)

Value returns the property named by prop. Props are searched first, then the named fields, so "name" and "kind" read as properties even though they have their own place on the struct.

type Group

type Group struct {
	Of    []Entity
	Like  map[[2]string]float64 // likeness of each pair that built the group
	Head  Entity
	Score float64
}

Group is a set of records found to describe one thing, and how sure that finding is. Head is the record carrying the most, which is the one to show when only one can be shown.

func Groups

func Groups(ps []Pair) []Group

Groups joins pairs that share a record into one group each. A pairs with B and B with C makes one group of three, because sameness is transitive even when the evidence for it is not.

func (Group) Tight

func (g Group) Tight() float64

Tight is the mean likeness of the pairs that built the group: how closely its records actually resemble one another, as against how sure Groups is that they are one thing.

type Keep

type Keep string

Keep says which of several records about one thing survives a merge, and which value wins where two of them disagree.

const (
	// First keeps the record given first.
	First Keep = "first"
	// Last keeps the record given last.
	Last Keep = "last"
	// Fullest keeps the record carrying the most properties and edges.
	Fullest Keep = "fullest"
	// Surest keeps the record with the highest confidence.
	Surest Keep = "surest"
	// All keeps every value: a property two records disagree on becomes the
	// list of what each said, and nothing is chosen between them.
	All Keep = "all"
)

type Kind

type Kind string

Kind says what sort of disagreement a Conflict is.

const (
	// Value is two documents giving one property different values.
	Value Kind = "value"
	// Type is two documents calling one thing different kinds.
	Type Kind = "type"
	// Edge is one subject given more than one object for a relation that
	// admits only one.
	Edge Kind = "edge"
	// Time is dates that cannot both hold.
	Time Kind = "time"
	// Logic is kinds that exclude one another: a person is not a company.
	Logic Kind = "logic"
	// Range is a value outside the bounds declared for its property.
	Range Kind = "range"
)

type Level

type Level string

Level says how much a disagreement matters.

const (
	// Low is a disagreement of spelling: the values name one thing.
	Low Level = "low"
	// Medium is a plain disagreement about a value.
	Medium Level = "medium"
	// High is a disagreement wide enough to change what the value means.
	High Level = "high"
	// Critical is a disagreement about what the thing is, or one that cannot
	// be true at all.
	Critical Level = "critical"
)

type Limit

type Limit struct{ Lo, Hi float64 }

Limit is the range a property's values may take.

type Merged

type Merged struct {
	Entity Entity
	From   []Entity
	Kept   []string
	Keep   Keep
	Clash  []Clash
}

Merged is one merge, and the records it was made from. It is the merged record's provenance: Kept names every record folded in, and Clash names every property they disagreed on and what the merge did about it. A graph that has forgotten this cannot say what it was built from.

func Fuse

func Fuse(ctx context.Context, es []Entity, o Opt, k Keep) ([]Merged, error)

Fuse finds the duplicates in es and merges each group it finds, returning one Merged per group. Records that matched nothing are not in the result; Loose reports them.

func Merge

func Merge(es []Entity, k Keep) (Merged, error)

Merge folds records about one thing into a single record. The survivor is chosen by k; every property the others state and the survivor does not is added; every property they state differently is a Clash, settled by k and recorded either way.

Merge copies what it reads. The records given are left as they were.

type Metric

type Metric string

Metric picks how two strings are compared.

const (
	// Exact scores 1 for strings equal after case and space folding, 0 otherwise.
	Exact Metric = "exact"
	// Edit scores the Levenshtein distance against the longer string.
	Edit Metric = "edit"
	// Jaro scores Jaro-Winkler similarity, with the prefix bonus. It is the default.
	Jaro Metric = "jaro"
	// Gram scores the Jaccard overlap of character bigrams.
	Gram Metric = "gram"
	// Token scores the Jaccard overlap of whole words, which is what to use
	// when word order varies but the words themselves do not.
	Token Metric = "token"
)

type Opt

type Opt struct {
	Like    float64 // minimum likeness for a pair to be made
	Score   float64 // minimum confidence for a pair to be kept
	Floor   float64 // drop pairs less alike than this
	Per     int     // most pairs one record may appear in
	Max     int     // most pairs in the result
	Alike   bool    // rank by likeness rather than by confidence
	Weights Weights
	Metric  Metric
}

Opt tunes a search. The zero value compares everything and keeps everything: it is Find with no opinion. Default carries thresholds that hold up on ordinary text, and is the value to start from.

Like and Score are floors applied while pairs are made. Floor, Per and Max shape what survives afterwards: Floor drops the least alike, Per caps how many pairs any one record may appear in, Max caps the whole result. Zero means "no cap" for Per and Max.

type Pair

type Pair struct {
	A, B  Entity
	Like  float64
	Score float64
	Why   []string
}

Pair is two records judged to be the same thing, with the evidence for the judgement. Like is how alike they look; Score is how sure the judgement is after the evidence in Why is counted.

func Add

func Add(ctx context.Context, fresh, known []Entity, o Opt) ([]Pair, error)

Add compares fresh records against ones already held, and against nothing else. It is what to call when a graph already exists and a document has just arrived: the cost is the product of the two sets, not the square of their sum. Each pair reads fresh first, known second.

func Find

func Find(ctx context.Context, es []Entity, o Opt) ([]Pair, error)

Find returns the pairs of records in es that describe the same thing.

Records are only compared when they share a blocking key, so the cost is far below every pair, and two records whose kinds are stated and differ are never a pair whatever they score — a person and a company that share a name are two things, not one.

type Pick

type Pick struct {
	Of    string // the conflict settled
	Done  bool
	Value any
	By    Rule
	Score float64  // confidence in the choice
	From  []string // documents the choice rests on
	Why   string
}

Pick is what settling a disagreement chose, and why. A Pick that is not Done chose nothing: the disagreement stands, and the caller can see both that it stands and what was weighed.

func Settle

func Settle(cs []Conflict, r Rule, t Trust) []Pick

Settle applies one rule to every conflict, returning one Pick each. Nothing is dropped: a conflict the rule cannot settle comes back unsettled.

type Rule

type Rule string

Rule picks how a disagreement is settled.

const (
	// Vote takes the value the most documents state.
	Vote Rule = "vote"
	// Credible takes the value whose documents are most trusted.
	Credible Rule = "credible"
	// Newest takes the value stated latest, or the one stated last where no
	// document is dated.
	Newest Rule = "newest"
	// Oldest takes the value stated earliest, or the one stated first where no
	// document is dated.
	Oldest Rule = "oldest"
	// Sure takes the value from the document most confident of itself.
	Sure Rule = "sure"
	// Flag settles nothing and says so. An unsettled disagreement is a
	// result: it stays in the graph, visible, until a person decides.
	Flag Rule = "flag"
)

func (Rule) Settle

func (r Rule) Settle(c Conflict, t Trust) Pick

Settle applies one rule to a conflict.

type Score

type Score struct {
	Total float64
	Parts map[string]float64
}

Score is a likeness and the parts it was made of. Parts holds only the evidence that existed, so a pair with no vectors has no "vector" part.

func Likeness

func Likeness(a, b Entity, w Weights, m Metric) Score

Likeness scores how alike two entities are: their names, the values of the properties they share, the edges they have in common and, when both carry one, their vectors. Only the parts that exist are weighed, so missing evidence neither helps nor hurts.

The parts are weighed in a fixed order. Floating-point addition is not associative, so summing them in map order would score the same comparison differently between runs, and a ranking built on those scores would not be reproducible.

type Sketch

type Sketch []uint64

Sketch is a MinHash signature: for each of several independent hashes, the smallest value that hash gives any word of a text. Two sketches of the same width estimate how much their texts' word sets overlap, without either set being kept.

The estimate is unbiased and its standard error is one over the square root of the width: 128 hashes put it within about nine points.

func Sign

func Sign(s string, width int) Sketch

Sign returns the MinHash signature of s over width hashes. A width of zero or less takes 64, which is enough to tell a near-duplicate from a coincidence.

func (Sketch) Like

func (s Sketch) Like(t Sketch) float64

Like estimates the Jaccard overlap of the two texts the sketches were taken from: the share of hash positions where they agree. Sketches of different widths cannot be compared and score 0. Two sketches of empty texts agree everywhere and score 1, as two empty word sets do.

type Source

type Source struct {
	Doc   string    // the document
	Page  int       // page within it; 0 when unpaged
	Span  string    // section or heading within the page
	At    time.Time // when the document stated it; zero when unstated
	Score float64   // the document's own confidence, 0 to 1; 0 means unstated
}

Source is the document a record came from and how far it is to be trusted. Every value in this package carries one, because a claim without the document that made it cannot be ranked against a claim that disagrees.

type Tally

type Tally struct {
	Total int
	Kind  map[Kind]int
	Level map[Level]int
	Doc   map[string]int
	Prop  map[string]int
}

Tally counts a set of conflicts along the four ways a reader asks about them: what kind they are, how much they matter, which documents are involved, and which properties keep disagreeing.

func Count

func Count(cs []Conflict) Tally

Count tallies conflicts. A document is counted once per conflict it appears in, however many of the conflicting values it stated.

type Trust

type Trust map[string]float64

Trust scores documents on how far each is believed. A document it does not name is believed halfway, which is the benefit of the doubt an unrated document gets and the value a nil Trust gives everything.

func (Trust) Of

func (t Trust) Of(doc string) float64

Of returns the credit given to a document.

type Watch

type Watch struct {
	Props  []string // properties to compare; nil compares every one stated
	Times  []string // properties read as dates; nil reads Dates
	Limits map[string]Limit
	Apart  Disjoint
}

Watch says what to compare when looking for disagreement. The zero value compares every property any document states, every kind, and the properties in Dates, against the exclusions in Apart.

type Weights

type Weights struct{ Name, Props, Edges, Vector float64 }

Weights say how much each kind of evidence counts toward likeness. The zero value counts the name most, properties and edges equally after it, and ignores vectors, which is the balance to use where the records carry names worth trusting.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL