Build a search appearance anomaly detector: sitelinks/snippets losses and cause triage.
- User
Build a search appearance anomaly detector: sitelinks/snippets losses and cause triage.
Assistant
Build a search appearance anomaly detector: sitelinks/snippets losses and cause triage.
The user wants an "Anomaly Detector" specifically for "Search Appearance" metrics in Google Search Console (GSC). The key focus is on "sitelinks" and "snippets" (likely referring to rich results, featured snippets, or just general snippet visibility) losses. The output should include a "cause triage" – meaning, when a loss is detected, the system should suggest why it happened.
1. Scope and Strategy:
2. Component Breakdown: I need to build a conceptual tool or a script. Since I cannot host a live app, I will provide a robust Python script that acts as the engine for this detector.
3. Detailed Logic - Anomaly Detection:
4. Detailed Logic - Triage (The "Why"): This is the "smart" part. How do we infer the cause programmatically?
5. Developing the Python Solution:
google-auth-oauthlib, google-api-python-client, pandas, numpy.6. Structuring the Response:
Refining the Triage Logic (Self-Correction during drafting):
searchAppearance contains 'AMP' or 'Rich Result', and it drops, it's often structured data. If it's 'Featured Snippet', it's content competition.Code Structure:
GSCAnomalyDetector class.fetch_data(): API call.detect_anomalies(): Rolling stats.triage_cause(): Heuristic logic based on the type of appearance and concurrent metric drops.generate_report(): Output.Triage Rules to implement in code:
Let's write the response following this structure. I will prioritize a Python implementation using the Search Console API.
Check: Is the user asking for a GUI or a script? "Build a..." usually implies the logic/tool. A script is the most useful artifact I can provide.
Refinement on "Search Appearance" dimensions in GSC:
GSC API allows grouping by searchAppearance.
Values: AMP_BLUE_LINK, RICHCARD, FEATURED_SNIPPET, SITELINKS_DEEP_LINK, etc.
Final Plan:
(Self-Correction on Code): Ensure I handle the GSC API limits (row limits, date ranges). Use a 16-day window (15 for training, 1 for test) to keep it fast.
Let's build the Triage Logic carefully.
If SITELINKS_DEEP_LINK impressions drop > 50%:
date recent?web (standard organic) impressions drop? -> If No, probably Google UI testing. If Yes, Site-wide issue.This requires fetching both the specific appearance data AND the general web data for comparison. I will include that in the logic.
Let's go. This is a complete blueprint and Python implementation for a Search Appearance Anomaly Detector. This tool monitors specific Google Search enhancements (Sitelinks, Featured Snippets, Reviews, etc.), identifies sudden traffic losses, and programmatically suggests a root cause.
You will need google-auth-oauthlib, google-api-python-client, and pandas.
When the script detects a drop, it performs a "Differential Diagnosis" to categorize the cause.
SITELINKS_DEEP_LINK impressions drop > 30% overnight.web (general) traffic drop?
FEATURED_SNIPPET impressions drop to 0.RICHCARD or REVIEWS impressions drop.import pandas as pd
import numpy as np
from google.oauth2 import service_account
from googleapiclient.discovery import build
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings("ignore")
class SearchAppearanceAnomalyDetector:
"""
Detects anomalies in Google Search Appearances (Sitelinks, Snippets, etc.)
and triages potential causes.
"""
def __init__(self, credentials_path, site_url):
self.credentials = service_account.Credentials.from_service_account_file(
credentials_path,
scopes=['https://www.googleapis.com/auth/webmasters.readonly']
)
self.service = build('searchconsole', 'v1', credentials=self.credentials)
self.site_url = site_url
self.appearances = [
'SITELINKS_SEARCH_BOX',
'SITELINKS_DEEP_LINK',
'FEATURED_SNIPPET',
'RICHCARD',
'REVIEWS',
'THUMBNAIL'
]
def _query_gsc(self, dimensions, search_type='web', filters=None):
"""Helper to query GSC API."""
end_date = datetime.now().date() - timedelta(days=2) # Data delay
start_date = end_date - timedelta(days=60) # 60 days history
request = {
'startDate': start_date.strftime('%Y-%m-%d'),
'endDate': end_date.strftime('%Y-%m-%d'),
'dimensions': dimensions,
'type': search_type,
'rowLimit': 5000
}
if filters:
request['dimensionFilterGroups'] = [{'filters': filters}]
response = self.service.searchanalytics().query(
siteUrl=self.site_url, body=request
).execute()
if 'rows' not in response:
return pd.DataFrame()
data = response['rows']
df = pd.DataFrame(data)
# Extract dimension keys
for i, dim in enumerate(dimensions):
df[dim] = df['keys'].apply(lambda x: x[i])
df = df.drop(columns=['keys'])
return df
def fetch_appearance_data(self):
"""
Fetches traffic segmented by Search Appearance.
Note: GSC API requires specific dimension combinations.
"""
print("Fetching Search Appearance data...")
df_list = []
for appearance in self.appearances:
# We filter by the appearance type
g_filter = [{
'dimension': 'searchAppearance',
'operator': 'equals',
'expression': appearance
}]
# Query by date to see trends over time
df = self._query_gsc(dimensions=['date'], filters=[{'filters': g_filter}])
if not df.empty:
df['appearance_type'] = appearance
df_list.append(df)
if not df_list:
raise ValueError("No Search Appearance data found for this property.")
full_df = pd.concat(df_list)
full_df['date'] = pd.to_datetime(full_df['date'])
full_df = full_df.sort_values('date')
return full_df
def detect_anomalies(self, df, target_col='impressions', window=14, threshold=2.5):
"""
Detects anomalies using Z-Score on Rolling Difference.
"""
anomalies = []
for app_type in df['appearance_type'].unique():
subset = df[df['appearance_type'] == app_type].copy()
# Calculate daily change
subset['diff'] = subset[target_col].diff()
# Calculate rolling stats (excluding today to prevent leakage)
rolling_mean = subset['diff'].rolling(window=window).mean().shift(1)
rolling_std = subset['diff'].rolling(window=window).std().shift(1)
# Z-Score calculation
subset['z_score'] = (subset['diff'] - rolling_mean) / rolling_std
# Identify significant drops (Negative Z-Score indicates drop)
# We check if impressions dropped significantly below the norm
drops = subset[(subset['z_score'] < -threshold) & (subset['diff'] < 0)]
for _, row in drops.iterrows():
anomalies.append({
'date': row['date'],
'appearance_type': row['appearance_type'],
'lost_volume': abs(int(row['diff'])),
'severity_z': abs(row['z_score'])
})
return pd.DataFrame(anomalies)
def triage_cause(self, anomaly_df):
"""
Analyzes anomalies to determine root cause.
"""
if anomaly_df.empty:
return "No anomalies detected."
reports = []
# Fetch global web traffic for the same dates to check correlation
global_traffic = self._query_gsc(dimensions=['date'])
global_traffic['date'] = pd.to_datetime(global_traffic['date'])
for _, row in anomaly_df.iterrows():
cause = "Undetermined"
reasoning = ""
# Get global traffic for that specific day
day_data = global_traffic[global_traffic['date'] == row['date']]
if not day_data.empty:
global_clicks = day_data['clicks'].values[0]
# Logic: If Sitelinks drop but Global Traffic is stable, it's specific to UI/Sitelinks
# If BOTH drop, it's likely a sitewide technical issue or penalty.
# Simple logic for demo:
if global_clicks < (global_traffic['clicks'].rolling(7).mean().shift(1).values[-1] * 0.8):
cause = "Sitewide Traffic Drop"
reasoning = "Global site traffic also dropped. Investigate technical outages or algorithmic penalties."
else:
# Appearance Specific Logic
if 'SITELINK' in row['appearance_type']:
cause = "Brand Authority / Navigation Change"
reasoning = "Sitelinks rely on clear site architecture and internal linking. A drop without site-wide loss suggests Google's understanding of your nav changed, or a competitor ranked for your brand term."
elif 'SNIPPET' in row['appearance_type']:
cause = "Content De-optimization or Competitor Win"
reasoning = "Featured snippets are volatile. You likely lost the position zero to a competitor with better formatting or direct answers."
elif 'RICH_RESULT' in row['appearance_type']:
cause = "Structured Data Error"
reasoning = "Rich results rely on Schema. Check Google Rich Results Test for errors or manual actions."
reports.append({
'Date': row['date'],
'Appearance Lost': row['appearance_type'],
'Estimated Loss': row['lost_volume'],
'Probable Cause': cause,
'Triage Steps': reasoning
})
return pd.DataFrame(reports)
# --- Usage Logic ---
if __name__ == "__main__":
# Configuration
KEY_PATH = 'path/to/service-account.json'
SITE_URL = 'sc-domain:example.com'
try:
detector = SearchAppearanceAnomalyDetector(KEY_PATH, SITE_URL)
# 1. Get Data
data = detector.fetch_appearance_data()
# 2. Find Anomalies
anomalies = detector.detect_anomalies(data)
# 3. Triage
if not anomalies.empty:
report = detector.triage_cause(anomalies)
print("--- Anomaly Triage Report ---")
print(report.to_string())
else:
print("System Normal: No significant search appearance losses detected.")
except Exception as e:
print(f"Error: {e}")