My quotes crawler collects quotes for a typing game, and the internet repeats itself a lot. A famous line can show up many times: once with curly quotes, once with a typo, once with an extra word or two.
Exact duplicates are easy. Normalize the text (trim, strip quote marks, collapse whitespace, lowercase), hash it with SHA-256, and put a unique index on the hash. Near-duplicates are the hard part, because two texts that differ by one word have completely unrelated SHA-256 hashes. That's the whole point of a cryptographic hash.
What I wanted was the opposite: a hash where similar texts get similar fingerprints.
SimHash
SimHash (from Moses Charikar, and famously used by Google for near-duplicate web pages) does exactly that. For a piece of text:
- Split it into words and hash each word to 64 bits (I use FNV-1a).
- Keep 64 counters. For each word, go through its bits: add 1 to counter i if bit i is set, subtract 1 if it isn't.
- The fingerprint has bit i set wherever counter i ended up positive.
func Simhash(text string) int64 {
var counter [64]int64
h := fnv.New64a()
for _, word := range strings.Fields(text) {
h.Reset()
io.WriteString(h, word)
hash := h.Sum64()
for bit := 0; bit < 64; bit++ {
if (hash>>bit)&1 == 1 {
counter[bit]++
} else {
counter[bit]--
}
}
}
var fingerprint int64
for bit := 0; bit < 64; bit++ {
if counter[bit] > 0 {
fingerprint |= 1 << bit
}
}
return fingerprint
}
Each word votes on every bit. Change one word in a 30-word quote and most counters barely move, so only a few bits flip. Two texts are "near-duplicates" when their fingerprints differ in only a few bits, which you can measure with one XOR and a popcount:
func HammingDistance(a, b int64) int {
return bits.OnesCount64(uint64(a ^ b))
}
My crawler treats anything under 3 bits apart as a duplicate.
The problem: comparing against everything
The database has over 4.3 million quotes. Comparing every new quote against all of them is 4.3 million XORs per insert. That's fast for one quote, but the crawler saves quotes all day, in batches.
You can't put "within 2 bits of X" into a normal index. But there's a neat trick.
Banding, or: the pigeonhole principle
Split the 64-bit fingerprint into 4 bands of 16 bits. Now suppose two fingerprints differ in at most 3 bits. Those 3 differing bits can land in at most 3 of the 4 bands, so at least one band must be identical in both.
So every stored fingerprint goes into four Redis sets, one per band, keyed by that band's 16-bit value. To check a new quote, look up its four bands, take the fingerprints in those four sets as candidates, and run the real Hamming check only on them. Anything that's truly within the threshold is guaranteed to be among the candidates. Nothing slips through. This is locality-sensitive hashing (LSH).
How many candidates? A 16-bit band has 65,536 possible values, so with 4.3 million fingerprints each set holds about 66 on average, and four bands give roughly 260 comparisons instead of 4.3 million. Real fingerprints aren't perfectly uniform, but it's the right order of magnitude.
The trade-offs I ran into
- Bands vs. threshold. To tolerate k differing bits you need at least k + 1 bands. More bands means shorter bands, and shorter bands mean bigger buckets and more candidates. 4 × 16 is a comfortable middle for a threshold of 2–3 bits.
- Short texts are noisy. With five words, one changed word is 20% of the votes, so the fingerprint moves a lot more than it does for a long quote. Similarity on very short texts is shaky in both directions.
- Redis is a cache, not the truth. The fingerprints live in Postgres. On startup the crawler reloads them all into the Redis bands, so Redis can run without persistence and a crash loses nothing.
The thing I liked most about this is that the guarantee comes from pure counting. No machine learning, no tuning a similarity score: if two fingerprints are close enough, the pigeonhole principle says they share a band.
