Sub topic 5
Collecting Data on a Schedule and Keeping History
This chapter assumes you can read basic Python and SQL, have a Search Console property you can query, and know what the metrics from the earlier chapters mean. The goal is a small job that runs every day, stores what Search Console reports in a table you own, and never loses history.
Why you have to collect the data yourself
Search Console shows about 16 months of data. After that, older days drop off and cannot be recovered. Year-over-year comparison needs 13 months or more, and a trend you only started saving last month tells you nothing about last year's season.
Rank trackers are different. They report only what they checked, when they checked it. If you don't save each check, you can't reconstruct it.
So the rule is to save every pull before the source discards it, and to save it in a form that is safe to re-run.
Decide what to pull
The most useful grain for Search Console is one row per date, query, page, device and country. Coarser grains lose information that you can't get back. Finer rollups are easy to compute later with GROUP BY.
Three details shape the job:
- Data arrives late. Search Console data is usually final after about two to three days. Recent days can change.
- Row limits. One API request returns at most 25,000 rows. You page through results with
startRow. - Anonymized queries. Rows for rare queries are dropped when you request the
querydimension. Totals for a date alone are higher than the sum of the query rows.
For that last reason, run a second, cheaper pull with only the date dimension and store it as a totals table. You will use it later to reconcile the numbers.
| Source | What to store | Retention and risk |
|---|---|---|
| Search Console API | Daily rows at date, query, page, device, country | About 16 months, then lost |
| Search Console, date-only pull | Daily totals | Same window; used for reconciliation |
| Rank tracker export | One row per check, with timestamp, location and device | Depends on plan; exports may be limited |
| GA4 | Organic sessions by landing page and date | Raw data export to BigQuery starts only from the day you link it |
The collection flow
The job re-pulls a trailing window, not only yesterday. That handles late-arriving data and missed runs with the same code.
Pulling one day with pagination
This function returns every row for a single day. It uses the paging loop from the Search Console Search Analytics method. service is an authorized client, for example built with googleapiclient.discovery.build("searchconsole", "v1", credentials=creds).
import sqlite3
from datetime import date, timedelta
SITE = "sc-domain:example.com"
SCHEMA = """
CREATE TABLE IF NOT EXISTS gsc_daily (
date TEXT NOT NULL,
query TEXT NOT NULL,
page TEXT NOT NULL,
device TEXT NOT NULL,
country TEXT NOT NULL,
clicks INTEGER NOT NULL,
impressions INTEGER NOT NULL,
ctr REAL,
position REAL,
PRIMARY KEY (date, query, page, device, country)
)
"""
UPSERT = """
INSERT INTO gsc_daily
(date, query, page, device, country, clicks, impressions, ctr, position)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (date, query, page, device, country) DO UPDATE SET
clicks = excluded.clicks,
impressions = excluded.impressions,
ctr = excluded.ctr,
position = excluded.position
"""
def fetch_day(service, day, search_type="web"):
"""Return all rows for one day, following startRow until the API runs out."""
out = []
start_row = 0
while True:
body = {
"startDate": day.isoformat(),
"endDate": day.isoformat(),
"dimensions": ["date", "query", "page", "device", "country"],
"searchType": search_type,
"dataState": "final",
"rowLimit": 25000,
"startRow": start_row,
}
response = service.searchanalytics().query(siteUrl=SITE, body=body).execute()
rows = response.get("rows", [])
if not rows:
break
for row in rows:
d, query, page, device, country = row["keys"]
out.append((
d, query, page, device, country,
int(row["clicks"]), int(row["impressions"]),
row["ctr"], row["position"],
))
start_row += len(rows)
return out
def run(service, db_path="gsc.db", lookback_days=7, lag_days=3):
"""Re-pull a trailing window ending lag_days ago and upsert it."""
conn = sqlite3.connect(db_path)
conn.execute(SCHEMA)
newest = date.today() - timedelta(days=lag_days)
for offset in range(lookback_days):
day = newest - timedelta(days=offset)
rows = fetch_day(service, day)
with conn: # one transaction per day
conn.executemany(UPSERT, rows)
print(f"{day}: {len(rows)} rows")
conn.close()Several choices here matter:
- The primary key matches the grain. A re-run replaces a row. It never duplicates one.
dataStateisfinal. You only store settled numbers. Usingallwould include fresh, still-changing data, and the next run's upsert would correct it. Choose one and stay with it.- One transaction per day. If a request fails halfway through a day, the earlier days stay committed and that day is untouched.
- Zero rows never deletes anything. An empty response is not treated as proof that old rows should go.
Keep the store simple at first. SQLite is fine for one site. Move to PostgreSQL or BigQuery when several people or dashboards need to query it at once. The ON CONFLICT upsert works the same way in PostgreSQL.
Backfilling the first run
On day one, loop over the full window the API allows, up to about 16 months back. Do it in per-day requests, as above. A high-traffic site can produce hundreds of thousands of rows per day at this grain, so expect the first run to take a while and to hit quota limits. Add a pause or retry with backoff on quota errors, and resume from the last stored date.
Scheduling the job
Any scheduler works. A cron entry is enough to start:
# Run every day at 06:15 UTC and keep a log
15 6 * * * /usr/bin/python3 /opt/seo/collect_gsc.py >> /var/log/seo_collect.log 2>&1Managed schedulers (GitHub Actions on a schedule, Cloud Scheduler, Airflow) add retries, alerts and secret storage. Whichever you use:
- Keep credentials in the scheduler's secret store or environment, not in the script.
- Give the service account read-only access to the property.
- Make every run safe to repeat. This is the main reason for the upsert and the trailing window.
Checks that catch silent failure
A job that exits cleanly can still store bad data. After each run, verify:
- Row count. Compare each day's row count with the median of the previous 14 days. A drop of more than half deserves a look.
- Click reconciliation. Sum clicks from the query-level table for a day and compare with the date-only totals pull. The query-level sum should be lower, because of anonymized queries, but the ratio should stay stable. A sudden change in the ratio points to a pull problem or a real shift in long-tail queries.
- No gaps. Query for dates missing from the last 30 days and fill them on the next run.
- Freshness. Alert if the newest stored date is more than five days old.
-- Find missing days in the last 30 days (SQLite)
WITH RECURSIVE days(d) AS (
SELECT date('now', '-30 day')
UNION ALL
SELECT date(d, '+1 day') FROM days WHERE d < date('now', '-3 day')
)
SELECT d AS missing_day
FROM days
WHERE d NOT IN (SELECT DISTINCT date FROM gsc_daily)
ORDER BY d;Keeping rank tracker and analytics history
Treat rank tracker data as an append-only log. Store one row per keyword, check time, location, device and result, and never update old rows. Keep the exact settings used for each check. If you later change the tracked location or device, the new series is not comparable with the old one, and without the settings you can't tell.
For GA4, link the BigQuery export early. It does not backfill, so the history starts the day you turn it on. Search Console also offers a bulk export to BigQuery with the same limitation. Using it alongside your API job gives you a second copy to compare against.
Common mistakes
- Pulling only yesterday. Late corrections are lost and one failed run leaves a permanent gap.
- Overwriting a whole table each run. One bad pull can erase good history. Upsert by key instead.
- Storing only aggregates. You can roll detail up, but you can't split a rollup back apart.
- Mixing
finalandalldata without recording which one each row came from. - Backing up nothing. Copy the database file or export to cloud storage on a schedule. History is the one thing you can't regenerate.
Exercise
Your job re-pulls the last 7 days and upserts them. A teammate proposes changing it to pull only the one newest day, "to save quota". Give two reasons this is risky, and one way to save quota without those risks.
Show answer
First, recent days can still be corrected after they are first reported, and a single-day pull never revisits them. Second, if one run fails or the scheduler is down, that day is never filled in, which leaves a permanent gap. To save quota, keep the trailing window but shorten it (for example to 4 days), or first check which dates are missing or have a low row count and re-pull only those. The upsert keyed on date, query, page, device and country keeps every approach safe to repeat.