Sub topic 9
Clustering duplicates and picking a preferred URL
This chapter assumes you can already produce a normalized URL, a body-text hash, and a list of near-duplicate pairs with Jaccard scores, and that you know the canonical, redirect, noindex and robots signals. It also assumes you can read and filter a crawl export in pandas or plain Python. Here you will join those pieces. You will turn pairs of matching URLs into clusters, choose one preferred URL per cluster, and check whether the site's own signals agree with your choice.
Why pairs are not enough
Detection steps give you pairs. A hash match says that URL A and URL B have the same text. A shingle comparison says that A and D are 88% similar. A list of pairs is hard to act on, because one product page can produce dozens of them.
A cluster is a set of URLs that you treat as versions of one page. You make one decision per cluster instead of one per pair. The preferred URL is the member you want search engines to index and show. The other members are fixes waiting to happen: redirect them, canonicalize them, or leave them alone.
Building clusters with connected components
Treat each URL as a node and each match as an edge. A cluster is a connected component: a set of nodes you can reach from each other by following edges. The standard tool is union-find, which merges sets as you feed it edges.
Match evidence has different strengths, so decide what counts as an edge:
- Same normalized URL: a strong edge. The variants differ only in protocol, host case, trailing slash, or tracking parameters.
- Same body hash: a strong edge, if you hashed main content after removing boilerplate. A hash of full-page text can match for the wrong reason, such as two empty pages with the same template.
- Jaccard above a threshold: a weaker edge. Pick the threshold by reading samples. A value near 0.85 is a common starting point, but there is no universal number.
Be careful with chaining. If A is similar to B, and B is similar to C, union-find puts A and C in one cluster even when A and C share little text. With strong edges this is harmless. With a weak threshold, one bridging page can merge unrelated groups into a huge cluster. A cluster that is far larger than the rest is a signal to inspect it, and it is usually not a real finding. You can also cluster exact matches first and attach near-duplicate edges only for review.
Choosing the preferred URL
The preferred URL should be the one the site already treats as most important, so that your fix agrees with existing signals and moves little. Score each member on evidence you can read from the crawl. The table lists signals in the order the code below applies them.
| Signal | Prefer | Reason |
|---|---|---|
| Status code | 200 | A redirecting or erroring URL cannot be the final page. |
| noindex | Absent | A noindex page cannot be the indexed version. |
| Canonical votes | Most members point to it | The site has already chosen it in several places. |
| In the XML sitemap | Yes | The site lists it as a page it wants indexed. |
| Query string | None | Clean URLs are easier to maintain and link to. |
| Internal inlinks | Higher count | Links show where the site sends its weight. |
| URL length, then alphabetical | Shorter, then first | A stable tie-breaker so reruns give the same answer. |
Ordering matters. Canonical votes come before inlinks because a page with many links that the site canonicalizes elsewhere is a contradiction to report. It is not a winner. Adjust the order to the site, and always keep a deterministic last tie-breaker so results do not change between runs.
A complete example
This script builds clusters from exact hashes and a list of near-duplicate pairs, then picks a preferred URL for each cluster. It compares each member's declared canonical with that choice. The near_pairs list stands in for the output of the shingle step. The noindex field means a noindex directive was found in the page's meta robots tag or X-Robots-Tag header.
import hashlib
from collections import Counter, defaultdict
class UnionFind:
def __init__(self):
self.parent = {}
def find(self, x):
self.parent.setdefault(x, x)
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra != rb:
self.parent[rb] = ra
def hash_text(text):
cleaned = " ".join(text.lower().split())
return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()
T1 = "Lightweight running shoes for road and trail. Free returns."
T2 = "Lightweight running shoes for road and trail. Free returns on all orders."
T3 = "Waterproof leather boots built for cold weather and long hikes."
pages = [
{"url": "https://example.com/shoes/", "status": 200, "canonical": "https://example.com/shoes/",
"noindex": False, "in_sitemap": True, "inlinks": 120, "body": T1},
{"url": "https://example.com/shoes?color=red", "status": 200, "canonical": "https://example.com/shoes/",
"noindex": False, "in_sitemap": False, "inlinks": 4, "body": T1},
{"url": "https://example.com/shoes?sort=price", "status": 200, "canonical": "https://example.com/shoes?sort=price",
"noindex": False, "in_sitemap": False, "inlinks": 2, "body": T1},
{"url": "https://example.com/running-shoes/", "status": 200, "canonical": "https://example.com/running-shoes/",
"noindex": False, "in_sitemap": True, "inlinks": 15, "body": T2},
{"url": "https://example.com/boots/", "status": 200, "canonical": "https://example.com/boots/",
"noindex": False, "in_sitemap": True, "inlinks": 30, "body": T3},
]
near_pairs = [("https://example.com/shoes/", "https://example.com/running-shoes/", 0.88)]
THRESHOLD = 0.85
by_url = {p["url"]: p for p in pages}
uf = UnionFind()
for url in by_url:
uf.find(url)
hash_groups = defaultdict(list)
for p in pages:
if p["status"] == 200:
hash_groups[hash_text(p["body"])].append(p["url"])
for urls in hash_groups.values():
for other in urls[1:]:
uf.union(urls[0], other)
for a, b, score in near_pairs:
if score >= THRESHOLD:
uf.union(a, b)
clusters = defaultdict(list)
for url in by_url:
clusters[uf.find(url)].append(url)
def preferred_url(members):
votes = Counter(by_url[u]["canonical"] for u in members)
def key(url):
p = by_url[url]
return (
p["status"] != 200,
p["noindex"],
-votes[url],
not p["in_sitemap"],
"?" in url,
-p["inlinks"],
len(url),
url,
)
return min(members, key=key)
for members in clusters.values():
if len(members) < 2:
continue
best = preferred_url(members)
best_hash = hash_text(by_url[best]["body"])
print("preferred:", best)
print("members:", len(members))
for url in sorted(m for m in members if m != best):
p = by_url[url]
kind = "exact" if hash_text(p["body"]) == best_hash else "near"
status = "ok" if p["canonical"] == best else "fix"
print(f" {kind:5} {status:3} {url}")Running it prints:
preferred: https://example.com/shoes/
members: 4
near fix https://example.com/running-shoes/
exact ok https://example.com/shoes?color=red
exact fix https://example.com/shoes?sort=priceThe result has three parts:
/shoes/wins because two of the four members declare it as their canonical, it is in the sitemap, and it has the most inlinks.- The
?color=redURL already points to the preferred page, so no change is needed. - The
?sort=priceURL is an exact duplicate that canonicalizes to itself, so it needs a fix. /running-shoes/is only a near duplicate. A person should read both pages before changing it, because it may be a separate page with its own search demand.
Reading the result
Each cluster falls into one of a few situations:
- All signals already agree. Every member redirects or canonicalizes to the preferred URL. Record it and move on.
- No signals exist. Members declare themselves canonical, as
?sort=pricedoes. This is the most common finding and the usual starting point for a fix. - Signals conflict. Two members canonicalize to different targets, or the canonical target redirects, is noindexed, or is blocked by robots.txt. Search engines treat canonical as a hint, so conflicts mean they may ignore all of it and pick their own version.
- Preferred URL is unhealthy. Your scoring found no member with a 200 status and no noindex. Do not choose a URL for the cluster until someone fixes that.
Edge cases
- Hash matches on empty or error text. Soft 404 pages, empty search results and "loading" shells share one hash. Exclude pages below a minimum word count from hash edges, or you will cluster thousands of unrelated URLs.
- Same text, different intent. Two pages for the same product in different countries can differ only by price and shipping text. They are legitimately separate if the site uses language or region markup. Check for hreflang before treating them as duplicates.
- Paginated and faceted URLs. Page 2 of a category is not a duplicate of page 1 even when boilerplate dominates the text. Cluster on main content, and keep parameter URLs in their own review group.
- Redirecting URLs. They have no body of their own. Resolve each redirect chain to its final URL first, then cluster using that final URL.
- Cross-host clusters. Staging,
wwwand non-wwwhosts can all appear in one crawl. Make sure the preferred URL is on the production host, and exclude hosts that should not be indexed.
Handing clusters to the next step
For each cluster, record the preferred URL, the member count, the match type for each member (exact or near), and whether each member's signals agree. The next chapters use these columns. Thin-page triage works on pages that are not in a cluster, and prioritization ranks clusters by the traffic and links they involve. Remediation chooses between redirect, canonical, noindex and consolidation for each cluster, based on the match type and the conflicts you found.
Exercise
A cluster has three URLs. URL X has 200 inlinks, is in the sitemap and canonicalizes to Y. URL Y has 40 inlinks, is in the sitemap and canonicalizes to itself. URL Z has 5 inlinks, is not in the sitemap and canonicalizes to Y. Using the order in this chapter, which URL is preferred, and what should you report about X?
Show answer
Y is preferred. Y receives two canonical votes (its own and Z's) and X receives none, and canonical votes are scored before inlinks. Report X as a conflict: the page has the most inlinks and sitemap listing but declares Y as its canonical. Either X's links and sitemap entry should move to Y, or the canonical is wrong and X should be preferred. Someone must decide, and the site's signals do not settle it.
Exercise
Your clustering run produces one cluster of 4,000 URLs, while all other clusters have fewer than 10 members. Give two likely causes and one check for each.
Show answer
First, hash matches on empty or boilerplate-only text, such as soft 404s or empty result pages. Check the word count and a sample of body text for the cluster's hash groups, and exclude pages under a minimum length. Second, chaining through near-duplicate edges at a low threshold, where a few bridging pages join unrelated groups. Check the Jaccard scores of the edges that connect sub-groups, and raise the threshold or attach near-duplicate edges only for review.