Sub topic 7
Finding near duplicates with shingles and Jaccard similarity
This chapter assumes you can read a crawl export with pandas, that you have already hashed pages to find exact duplicates, and that you know how boilerplate (navigation, footers, related-product blocks) is separated from main content. If any of that is unfamiliar, review the earlier chapters first.
Why exact hashes are not enough
A content hash changes completely when a single character changes. Two product pages that differ only by the word "red" and "blue" produce unrelated hashes, so the exact-duplicate check reports no match. Near duplicates are pages whose main content overlaps heavily but is not identical. They are common on sites with templated copy, such as product variants, location pages with swapped city names, and press releases republished with a new date.
To find them you need a similarity score, not an equality test. The approach in this chapter has three steps:
- Turn each page's main text into a set of overlapping word phrases, called shingles.
- Compare two sets with the Jaccard similarity score.
- Flag pairs above a threshold and review them by hand.
Shingles
A shingle is a run of k consecutive words from the text. With k = 5, the text "our red running shoes are lightweight" produces two shingles: "our red running shoes are" and "red running shoes are lightweight". Sliding a window one word at a time over the page gives a set of all such phrases.
Shingles keep word order. A plain bag of words would treat "dog bites man" and "man bites dog" as identical, while shingles do not. Because they are phrases, one changed word only affects the k shingles that contain it. The rest of the page still matches.
def shingles(text, k=5):
words = text.lower().split()
if len(words) < k:
return {" ".join(words)} if words else set()
return {" ".join(words[i:i + k]) for i in range(len(words) - k + 1)}
print(sorted(shingles("Our red running shoes are lightweight")))The function handles pages shorter than k words by returning one shingle of the whole text. An empty page returns an empty set.
Jaccard similarity
The Jaccard similarity of two sets is the size of their intersection divided by the size of their union. The result runs from 0 (nothing shared) to 1 (identical sets).
def jaccard(a, b):
if not a and not b:
return 0.0
return len(a & b) / len(a | b)
page_a = "Our red running shoes are lightweight and built for long road runs in all weather"
page_b = "Our blue running shoes are lightweight and built for long road runs in all weather"
print(round(jaccard(shingles(page_a), shingles(page_b)), 2))Each page has 15 words, so 11 shingles. The changed word "red" or "blue" appears in the first 1 shingle only if it is at the start, but here it sits in the second position, so it affects the first two shingles of each page. That leaves 9 shared shingles out of 13 in the union, and the script prints 0.69. One word changed in a 15-word page lowers the score by almost a third. On a page with 500 words the same one-word change barely moves the score. This is why short pages score lower than their visual similarity suggests, and why you should read the score together with the word count.
The empty-set case returns 0.0 on purpose. Two empty pages are not "similar" in any useful sense. They are a missing-content problem and belong to the thin-page analysis.
Choosing k and a threshold
Two settings control the result.
| Setting | Smaller value | Larger value |
|---|---|---|
| k (words per shingle) | More matches, more false positives on common phrases | Fewer matches, one edit disrupts more shingles |
| Threshold | More pairs flagged, more review work | Fewer pairs flagged, near duplicates missed |
For web pages, k between 4 and 7 works well in practice. A common starting threshold is 0.8 for "near duplicate", with a review band from 0.5 to 0.8 for "heavily overlapping". These numbers are starting points. Sample pairs at several score levels, read them, and set the threshold where the pairs stop being the kind you would act on.
Comparing every page in a crawl
Comparing every pair of pages needs n × (n − 1) / 2 comparisons. At 1,000 pages that is about 500,000, which is fine. At 100,000 pages it is about 5 billion, which is not. Reduce the work in two ways.
First, compare only within groups that could plausibly be related. Group by template, by top-level directory, or by similar word count. A product page is rarely a near duplicate of a blog post, so the cross-template comparisons are wasted work.
Second, skip pages that are already exact duplicates. Keep one representative per body hash and compare only those.
The script below does both. It assumes a crawl export with the columns url, status, template, body_text and word_count.
import hashlib
from itertools import combinations
import pandas as pd
def shingles(text, k=5):
words = text.lower().split()
if len(words) < k:
return {" ".join(words)} if words else set()
return {" ".join(words[i:i + k]) for i in range(len(words) - k + 1)}
def jaccard(a, b):
if not a and not b:
return 0.0
return len(a & b) / len(a | b)
def content_hash(text):
cleaned = " ".join(str(text).split()).lower()
return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()
df = pd.read_csv("crawl.csv")
df = df[(df["status"] == 200) & (df["word_count"] >= 50)].copy()
df["body_text"] = df["body_text"].fillna("")
df["body_hash"] = df["body_text"].map(content_hash)
# One representative per exact-duplicate group
reps = df.drop_duplicates("body_hash").copy()
reps["shingle_set"] = reps["body_text"].map(shingles)
THRESHOLD = 0.8
pairs = []
for template, group in reps.groupby("template"):
rows = list(group[["url", "shingle_set"]].itertuples(index=False))
for a, b in combinations(rows, 2):
score = jaccard(a.shingle_set, b.shingle_set)
if score >= THRESHOLD:
pairs.append((a.url, b.url, round(score, 2)))
result = pd.DataFrame(pairs, columns=["url_a", "url_b", "jaccard"])
print(result.sort_values("jaccard", ascending=False).head(20))The filter word_count >= 50 keeps very short pages out of this analysis. Short pages produce unstable scores, as the earlier example showed, and they are better handled as thin pages.
Within each template the pairwise loop is still quadratic. If a single template holds tens of thousands of pages, switch to MinHash with locality-sensitive hashing. Libraries such as datasketch implement this. MinHash approximates Jaccard similarity from a short fixed-size signature per page, and LSH finds candidate pairs without comparing everything. The score you get is an estimate, so verify the flagged pairs with the exact calculation.
Common errors and edge cases
- Boilerplate inflates scores. Covered above. Check that your
body_textcolumn holds main content, not the full rendered page. - Templated text on legitimate pages. Location pages often share a long paragraph and differ in a short local section. A high score is correct here, but the right action depends on whether the local section has value. The score tells you the overlap, not the fix.
- Short pages. One changed word swings the score. Filter by word count or report the shared-shingle count beside the score.
- Containment. Jaccard punishes size differences. If a 100-word page is fully copied inside a 1,000-word page, the score is about 0.1, though every shingle of the short page appears in the long one. To catch this, also compute containment: the intersection size divided by the size of the smaller set.
- Whitespace and case. The function lowercases and splits on whitespace, so those differences are ignored. Punctuation is not removed, so "weather." and "weather" differ. Strip punctuation if your pages vary in it.
- Language. Splitting on whitespace fails for languages written without spaces, such as Chinese and Japanese. Use character shingles instead.
- Rendered content. If the crawl did not render JavaScript, the text may be an empty shell for every page, and all pages look alike. Check word counts first.
def containment(a, b):
smaller = min(len(a), len(b))
if smaller == 0:
return 0.0
return len(a & b) / smallerWhat to do with the results
A flagged pair is a lead, not a verdict. For each pair, open both pages and decide whether a visitor would see them as the same thing. Then connect the pair to the signals you read in the next chapter: canonical tags, redirects, noindex and robots rules. A near-duplicate pair that already canonicalizes to one URL is handled. A pair where both pages are indexable and self-canonical is where you act.
The output of this chapter feeds clustering. Pairs that share a member are merged into groups, and each group gets a preferred URL.
Exercise
Two 12-word pages differ by one word in the middle. With k = 5, each page has 8 shingles. The changed word sits in the middle, so it appears in 5 shingles on each page. What is the Jaccard score, and why is it a poor measure of how similar these pages look to a reader?
Show answer
Each page has 3 shingles that do not contain the changed word, so the intersection is 3. The union is 3 + 5 + 5 = 13. The score is 3 / 13, about 0.23. Short pages are punished because one word change affects up to k shingles, which is a large share of a small set. To a reader the pages look nearly identical, so for short pages you should report the word count with the score or move them to thin-page analysis.
Exercise
A 150-word disclaimer page is copied word for word inside a 1,500-word terms page. Jaccard similarity comes out near 0.1. Which measure would reveal the copy, and what value would it give for the shingle sets?
Show answer
Containment, the intersection size divided by the size of the smaller set. Every shingle of the disclaimer appears in the terms page, so the intersection equals the smaller set and containment is 1.0.