Sub topic 12
Detecting duplicate and near-duplicate content
This chapter assumes you have read the chapters on URL normalization and the seen set, and that you can read short Python programs. It also assumes you know what a hash function is and what a set of integers is.
Why URL checks are not enough
Normalization and the seen set stop the crawler from fetching the same URL twice. They cannot stop it from fetching different URLs that return the same content. Common causes:
- Mirrors and the same article published under several paths.
- Session IDs, tracking parameters, and sort orders that change the URL but not the page.
- Print views, AMP versions, and
index.htmlaliases. - Pages that share boilerplate (menus, footers, cookie banners) and differ only in a small main section.
Duplicate content wastes storage and index space. It also skews link counts and makes search results repetitive. In a crawl it can feed a crawl trap, because each new URL looks fresh to the seen set. Content deduplication runs after the fetch and before the page is stored or its links are queued.
Exact duplicates with a content hash
The simplest check hashes the page body and keeps the hashes in a set. If the hash is already there, the content is identical.
Hashing raw HTML rarely works, because pages often embed timestamps, ad slots, or CSRF tokens that differ on every request. Hash the cleaned text instead:
- Extract the visible text, ideally the main content region.
- Lowercase it and collapse runs of whitespace.
- Hash the result.
import hashlib
import re
def clean_text(text):
return re.sub(r'\s+', ' ', text.lower()).strip()
def content_hash(text):
return hashlib.sha256(clean_text(text).encode('utf-8')).hexdigest()
seen_hashes = {}
def is_exact_duplicate(url, text):
digest = content_hash(text)
if digest in seen_hashes:
return seen_hashes[digest] # URL of the first copy
seen_hashes[digest] = url
return None
print(is_exact_duplicate('https://a.example/post', 'Hello World')) # None
print(is_exact_duplicate('https://b.example/post', 'hello world')) # https://a.example/postA hash match is strong evidence, but a collision is theoretically possible. With a 256-bit hash that risk is negligible. If you truncate hashes to save memory, count the collision odds before you do.
Near duplicates
Two pages that differ by one changed date have different hashes, yet most people would call them the same page. Near-duplicate detection compares similarity instead of equality. Two ideas do most of the work.
Shingles and Jaccard similarity
A shingle is a run of k consecutive words. A page becomes the set of its shingles. The Jaccard similarity of two sets is the size of their intersection divided by the size of their union. It runs from 0 (nothing shared) to 1 (identical sets).
The weakness is cost. Comparing every new page against every stored page is quadratic, and each page may have thousands of shingles. MinHash compresses each shingle set into a short signature that approximates Jaccard similarity. A simpler option for crawlers is simhash.
Simhash fingerprints
Simhash turns a page into one fixed-size integer, typically 64 bits. Similar pages get fingerprints that differ in only a few bits. The method:
- Split the text into features (words or shingles).
- Hash each feature to 64 bits.
- Keep a counter per bit position. For each feature, add 1 where its hash bit is 1 and subtract 1 where it is 0.
- The final bit is 1 where the counter is positive and 0 otherwise.
Distance is the Hamming distance, the number of differing bits between two fingerprints.
import hashlib
import re
def shingles(text, k=3):
words = re.findall(r'\w+', text.lower())
return [' '.join(words[i:i + k]) for i in range(len(words) - k + 1)]
def simhash(features, bits=64):
counts = [0] * bits
for feature in features:
h = int.from_bytes(hashlib.md5(feature.encode('utf-8')).digest()[:8], 'big')
for i in range(bits):
counts[i] += 1 if (h >> i) & 1 else -1
value = 0
for i, c in enumerate(counts):
if c > 0:
value |= 1 << i
return value
def hamming(a, b):
return bin(a ^ b).count('1')
a = ('The crawler fetches a page, extracts its links, and adds new links to the frontier. '
'Each host gets its own queue so the crawler stays polite and spreads its load. '
'Before storing a page it checks whether the same content was seen under another URL.')
b = a.replace('stays polite', 'remains polite')
c = ('Bread dough needs flour, water, salt, and yeast. Knead it until smooth, let it rise '
'in a warm place, then shape the loaf and bake it until the crust turns golden brown.')
print(hamming(simhash(shingles(a)), simhash(shingles(b)))) # small
print(hamming(simhash(shingles(a)), simhash(shingles(c)))) # near 32 for unrelated textUnrelated pages land near 32 differing bits on average, because each bit is close to a coin flip. Crawlers commonly treat a distance of 3 or less on 64 bits as a near duplicate. Tune the threshold on a sample of your own data.
Finding matches without comparing everything
Computing a fingerprint is cheap. Finding every stored fingerprint within distance 3 of a new one is the hard part. Scanning all fingerprints is linear per page.
The standard trick uses the pigeonhole principle. Split each 64-bit fingerprint into 4 blocks of 16 bits. If two fingerprints differ in at most 3 bits, those bits fall in at most 3 blocks, so at least one block is identical. Build 4 lookup tables, one per block position, keyed by that block's value. For a new fingerprint, look up each of its 4 blocks, collect the candidates, and compute the full Hamming distance only for those. Larger thresholds need more blocks or permuted tables, and memory grows with each table.
Choosing a method
| Method | Catches | Cost | Main risk |
|---|---|---|---|
| Content hash | Identical cleaned text | One set lookup | Misses any small change |
| Shingle Jaccard | Overlapping text | High when comparing all pairs | Slow without sketching |
| MinHash | Overlapping text | Medium, several values per page | Signature size versus accuracy |
| Simhash | Slightly edited pages | Low, one 64-bit value | Tuning the threshold, short pages |
Many crawlers use a content hash first because it is nearly free, then simhash on pages that pass.
Edge cases
- Boilerplate dominates. Menus and footers can make two different articles look alike. Extract the main content before fingerprinting.
- Short pages. A page with 20 words yields few features, so one word changes many bits. Skip near-duplicate checks below a minimum length, or use exact hashing only.
- Soft 404s. Servers that return status 200 with a "not found" message produce many pages with the same text. Exact hashing catches these, and you can use the hash to flag the pattern for a host.
- Dynamic text. Timestamps, view counts, and "related" lists change per request. Strip or ignore them before hashing.
- Encodings. Decode to Unicode and apply normalization before hashing, or the same text in two encodings will differ.
What to record
Store the fingerprint with each page record, together with the URL of the first copy. This lets the indexer choose a canonical URL, lets recrawls detect real changes (a changed hash means new content), and gives you duplicate rates per host. A host where most pages are duplicates is a strong signal of a crawl trap or a misconfigured site, and it can lower that host's page budget.
Exercise
A crawler stores 64-bit simhash fingerprints and treats pages within Hamming distance 3 as near duplicates. Explain why splitting each fingerprint into 4 blocks of 16 bits lets you find candidates with table lookups, and say what you must still do after the lookups.
Show answer
If two fingerprints differ in at most 3 bits, those differing bits can touch at most 3 of the 4 blocks, so at least one block is identical in both. Keep one table per block position, keyed by the block value, and look up all 4 blocks of a new fingerprint to collect candidates. Candidates only share one block, so you must still compute the full 64-bit Hamming distance for each candidate and keep those at distance 3 or less.