cdx-cc-news / sqlite_from_cdxj.py
brian-learns's picture
Create sqlite_from_cdxj.py
3bfd464 verified
Raw
History Blame Contribute Delete
4.2 kB
import sys
import os
import sqlite3
import subprocess
from urllib.parse import urlparse
BATCH_SIZE = 100000 # Insert in chunks of 100k to save RAM
# Embedded schema to make the script standalone[span_1](start_span)[span_1](end_span)
SCHEMA_SQL = """
-- 1. The Payload Table (Standard ROWID table)
-- 'id' becomes a direct alias for the SQLite rowid.
CREATE TABLE payload_data (
id INTEGER PRIMARY KEY,
json_record TEXT
);
-- 2. The Lookup Table (WITHOUT ROWID)
-- Clustered directly by SURT for extremely fast prefix/exact lookups.
CREATE TABLE surt_lookup (
surt TEXT,
capture_time INTEGER,
payload_id INTEGER,
PRIMARY KEY (surt, capture_time)
) WITHOUT ROWID;
"""
if len(sys.argv) < 2:
print("Usage: uv run import_cdx.py <file-or-url>")
sys.exit(1)
source = sys.argv[1]
# --- 1. Parse File Info and Compression ---
parsed_url = urlparse(source)
original_file_name = os.path.basename(parsed_url.path)
# Determine compression based strictly on the parsed path
is_zst = original_file_name.endswith('.zst')
# --- 2. Determine Database Name ---
if is_zst:
base_name = original_file_name[:-4]
else:
base_name = original_file_name
db_name = f"{base_name}.db"
print(f"Input source: {source}")
print(f"Target database: {db_name}")
# --- 3. Initialize Database and Schema ---
if not os.path.exists(db_name):
print(f"Initializing {db_name} with embedded schema...")
init_conn = sqlite3.connect(db_name)
init_conn.executescript(SCHEMA_SQL)
init_conn.close()
# --- 4. Setup Streaming Pipeline (curl/cat -> zstdcat) ---
is_url = source.startswith("http://") or source.startswith("https://")
fetch_process = None
decompress_process = None
if is_url:
fetch_process = subprocess.Popen(["curl", "-sL", source], stdout=subprocess.PIPE)
raw_stream = fetch_process.stdout
else:
raw_stream = open(source, "rb")
if is_zst:
decompress_process = subprocess.Popen(["zstdcat"], stdin=raw_stream, stdout=subprocess.PIPE)
stream = decompress_process.stdout
else:
stream = raw_stream
# --- 5. Process and Insert Data ---
connection = sqlite3.connect(db_name)
cursor = connection.cursor()
cursor.execute("PRAGMA journal_mode = WAL;")
cursor.execute("PRAGMA synchronous = NORMAL;")
cursor.execute("SELECT IFNULL(MAX(id), 0) FROM payload_data")
current_id = cursor.fetchone()[0]
payload_batch = []
lookup_batch = []
# Variables to track the last seen record for deduplication
last_surt = None
last_capture_time = None
cursor.execute("BEGIN TRANSACTION;")
print("Importing data (with duplicate filtering)...")
for line_bytes in stream:
line = line_bytes.decode('utf-8', errors='replace').strip()
if not line:
continue
parts = line.split(' ', 2)
if len(parts) != 3:
continue
surt = parts[0]
try:
capture_time = int(parts[1])
except ValueError:
continue
json_record = parts[2]
# Deduplication check: skip if it matches the previous row's keys
if surt == last_surt and capture_time == last_capture_time:
continue
# Update trackers for the next iteration
last_surt = surt
last_capture_time = capture_time
current_id += 1
payload_batch.append((current_id, json_record))
lookup_batch.append((surt, capture_time, current_id))
if len(payload_batch) >= BATCH_SIZE:
cursor.executemany("INSERT INTO payload_data (id, json_record) VALUES (?, ?)", payload_batch)
cursor.executemany("INSERT INTO surt_lookup (surt, capture_time, payload_id) VALUES (?, ?, ?)", lookup_batch)
payload_batch.clear()
lookup_batch.clear()
print(f"Inserted up to ID {current_id} in {db_name}...")
# Cleanup leftover batch
if payload_batch:
cursor.executemany("INSERT INTO payload_data (id, json_record) VALUES (?, ?)", payload_batch)
cursor.executemany("INSERT INTO surt_lookup (surt, capture_time, payload_id) VALUES (?, ?, ?)", lookup_batch)
connection.commit()
connection.close()
# Close processes and files safely
if decompress_process:
decompress_process.wait()
if fetch_process:
fetch_process.wait()
elif not is_url:
raw_stream.close()
print(f"Import fully complete for {db_name}!")