Build a cannibalization detector: query mapping, deconfliction rules, and rewrites.
- User
Build a cannibalization detector: query mapping, deconfliction rules, and rewrites.
Assistant
Build a cannibalization detector: query mapping, deconfliction rules, and rewrites.
The user wants a "cannibalization detector" with three components: query mapping, deconfliction rules, and rewrites. "Keyword cannibalization" in SEO occurs when multiple pages on the same website rank for the same (or very similar) keywords, causing them to compete against each other. This can dilute ranking potential and confuse search engines about which page is the "canonical" or most relevant source.
Here is the plan:
Define the Structure: I need to build a system or a conceptual framework (code snippets + logic) that performs these three tasks.
Component 1: Query Mapping (The Detection Phase)
requests, BeautifulSoup, or an NLP library like spacy or RakeNLP) to extract key phrases.{Page_URL: {Target_Keywords: [...]}}.Component 2: Deconfliction Rules (The Decision Phase)
hreflang tags.Component 3: Rewrites (The Resolution Phase)
Coding the Tool (Python Prototype)
Structuring the Response
pandas and sklearn (TF-IDF) to show how to calculate overlap.Refining the Code:
sklearn.feature_extraction.text.TfidfVectorizer and cosine_similarity. This is a standard way to measure text similarity, which serves as a proxy for query mapping overlap in a simple script.CannibalizationDetector.Refining the Rules:
Refining the Rewrites:
Review against User Prompt:
Final Polish: Ensure the tone is technical but practical. (Self-correction: Don't just give code; explain the strategy behind the code, as SEO often requires human judgment on "intent").
(Self-Correction during drafting code): Real SEO tools use search console API data to see which keywords actually drive traffic to which URLs. Since I don't have access to the user's GSC, I must simulate this by analyzing on-page text (Title/Content) as a proxy for "targeted queries." I will make this distinction clear.
Let's build the output. This guide outlines how to build a Keyword Cannibalization Detector. This system analyzes a dataset of URLs and their associated keywords/metadata to identify conflicts, apply resolution logic, and generate resolution strategies.
We will break this down into three layers:
Here is a complete, runnable prototype.
First, we need data. In a real scenario, this comes from Google Search Console or an SEO crawler (Screaming Frog/Semrush).
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from itertools import combinations
# --- 1. DATA SIMULATION ---
# Imagine these are pages on your site and their primary target queries
data = [
{'url': '/pages/running-shoes', 'title': 'Best Running Shoes 2024', 'h1': 'Top Rated Running Gear', 'target_keyword': 'running shoes'},
{'url': '/pages/best-sneakers', 'title': 'Best Sneakers for Jogging', 'h1': 'Jogging Footwear Guide', 'target_keyword': 'best sneakers'}, # High overlap with running shoes
{'url': '/pages/running-shoe-care', 'title': 'How to Clean Running Shoes', 'h1': 'Shoe Maintenance', 'target_keyword': 'running shoe care'}, # Specific intent
{'url': '/pages/marathon-training', 'title': 'Marathon Training Guide', 'h1': 'How to Train for a Marathon', 'target_keyword': 'marathon training'},
{'url': '/blog/running-tips', 'title': '10 Tips for Runners', 'h1': 'Running Advice', 'target_keyword': 'running tips'},
{'url': '/product/nike-air-zoom', 'title': 'Nike Air Zoom Pegasus', 'h1': 'Buy Nike Air Zoom', 'target_keyword': 'nike air zoom'}, # Transactional
]
df = pd.DataFrame(data)
# Helper: Determine intent heuristically (Transactional vs Informational)
def classify_intent(keyword):
transactional_words = ['buy', 'price', 'discount', 'order', 'shop']
if any(word in keyword for word in transactional_words):
return 'Transactional'
return 'Informational'
df['intent'] = df['target_keyword'].apply(classify_intent)
print("Initial Data:\n", df[['url', 'target_keyword', 'intent']], "\n")
We use TF-IDF (Term Frequency-Inverse Document Frequency) to convert the text content (Title + H1 + Keyword) into vectors. We then calculate the Cosine Similarity between every page. If the score is high (e.g., > 0.6), they are potentially cannibalizing.
# --- 2. QUERY MAPPING ---
def detect_cannibalization(df, threshold=0.4):
# Combine text fields for vectorization
df['corpus'] = df['title'] + " " + df['h1'] + " " + df['target_keyword']
# Vectorize
tfidf = TfidfVectorizer(stop_words='english')
tfidf_matrix = tfidf.fit_transform(df['corpus'])
# Compute Similarity Matrix
cos_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)
# Find pairs exceeding threshold
conflicts = []
# Iterate through upper triangle of matrix to avoid duplicates and self-comparison
rows, cols = np.triu_indices(len(df), k=1)
for i, j in zip(rows, cols):
score = cos_sim[i, j]
if score > threshold:
conflicts.append({
'Page A': df.iloc[i]['url'],
'Page B': df.iloc[j]['url'],
'Keyword A': df.iloc[i]['target_keyword'],
'Keyword B': df.iloc[j]['target_keyword'],
'Intent A': df.iloc[i]['intent'],
'Intent B': df.iloc[j]['intent'],
'Similarity': round(score, 3)
})
return pd.DataFrame(conflicts)
conflict_df = detect_cannibalization(df)
print("Potential Conflicts Found:\n", conflict_df, "\n")
Just because pages look similar doesn't mean they are cannibalizing. We need a logic engine to decide if action is needed.
Logic Rules:
# --- 3. DECONFLICTION RULES ---
def apply_resolution_rules(conflicts):
resolutions = []
for _, row in conflicts.iterrows():
action = "MONITOR" # Default
reason = "Low similarity or distinct topics"
# Rule 1: Cross-Intent (Funnel)
if row['Intent A'] != row['Intent B']:
action = "KEEP_BOTH"
reason = "Intent Mismatch: One is Info, one is Transactional."
# Rule 2: Same Intent
elif row['Intent A'] == row['Intent B']:
# Heuristic: Check if keywords are lexically close
kw_a = set(row['Keyword A'].split())
kw_b = set(row['Keyword B'].split())
overlap = kw_a & kw_b
if len(overlap) > 0 and row['Similarity'] > 0.5:
action = "MERGE_OR_CANONICAL"
reason = "Same Intent & Semantic Overlap: Consolidate to create one strong page."
else:
action = "DIFFERENTIATE"
reason = "Same Intent but different topics. Sharpen content focus."
resolutions.append({
'Page A': row['Page A'],
'Page B': row['Page B'],
'Similarity': row['Similarity'],
'Action': action,
'Reason': reason
})
return pd.DataFrame(resolutions)
resolution_df = apply_resolution_rules(conflict_df)
print("Resolution Plan:\n", resolution_df[['Page A', 'Page B', 'Action', 'Reason']], "\n")
Once the system identifies a MERGE_OR_CANONICAL or DIFFERENTIATE action, you generate the "Rewrite" instructions.
# --- 4. REWRITES & OUTPUT ---
def generate_rewrites(res_df, original_df):
for _, row in res_df.iterrows():
if row['Action'] == 'MERGE_OR_CANONICAL':
print(f"--- ACTION REQUIRED: MERGE ---")
print(f"Conflict between {row['Page A']} and {row['Page B']}")
print(f"Reason: {row['Reason']}")
# Heuristic: Pick the one with the shorter URL or higher authority (simulated here)
# In reality, check backlinks/traffic.
survivor = row['Page A']
victim = row['Page B']
print(f"SUGGESTION: 301 Redirect {victim} -> {survivor}")
print(f"REWRITE TASK: Update content on {survivor} to include keywords from {victim}.")
print("-" * 30)
elif row['Action'] == 'DIFFERENTIATE':
print(f"--- ACTION REQUIRED: DIFFERENTIATE ---")
print(f"Conflict between {row['Page A']} and {row['Page B']}")
print(f"REWRITE TASK: Modify H1/Title on {row['Page B']} to target long-tail variation.")
print("-" * 30)
generate_rewrites(resolution_df, df)
When your detector runs, it will classify conflicts into three buckets. Here is how to handle the "Rewrites" for each:
To refine the "Query Mapping," you can extract N-grams (2-word phrases) to see exactly what is overlapping.
from collections import Counter
import re
def extract_top_ngrams(texts, n=2, top_k=5):
all_ngrams = []
stop_words = set(['for', 'and', 'the', 'a', 'in', 'of', 'to'])
for text in texts:
text = text.lower()
text = re.sub(r'[^\w\s]', '', text)
words = [w for w in text.split() if w not in stop_words]
for i in range(len(words)-n+1):
all_ngrams.append(" ".join(words[i:i+n]))
return Counter(all_ngrams).most_common(top_k)
# Example usage on conflicting pages
if not conflict_df.empty:
page_a_text = df[df['url'] == conflict_df.iloc[0]['Page A']]['corpus'].values[0]
page_b_text = df[df['url'] == conflict_df.iloc[0]['Page B']]['corpus'].values[0]
print("Overlap Analysis:")
print("Page A N-grams:", extract_top_ngrams([page_a_text]))
print("Page B N-grams:", extract_top_ngrams([page_b_text]))