Files

574 lines
18 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
OpenAlex full ingestion script.
Discovers all entity directories, resolves data files, and uploads them
to Elasticsearch via the existing upload.py infrastructure. Maintains a
JSON state file so that interrupted runs can be resumed without
re-uploading already-completed files.
Usage:
# Ingest everything from the current directory
python ingest.py
# Ingest from a custom root with a custom ES URL
python ingest.py --root /data/openalex --es-url https://es.example.com:9200
# Resume a previous run (automatic – reads state file)
python ingest.py
# Only ingest specific entities
python ingest.py --entities works authors institutions
# Reset state and start fresh
python ingest.py --reset
# Dry-run: show what would be uploaded
python ingest.py --dry-run
"""
import argparse
import json
import logging
import os
import signal
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
ES_MODULE_DIR = SCRIPT_DIR / "elasticsearch"
sys.path.insert(0, str(ES_MODULE_DIR))
try:
from dotenv import load_dotenv
load_dotenv(SCRIPT_DIR / ".env")
except ImportError:
pass # .env loading is optional
from upload import ( # noqa: E402
apply_transforms,
build_es_client,
collect_input_files,
doc_id,
ensure_index,
read_jsonl,
resolve_index_name,
)
from mappings import INDEX_MAPPINGS # noqa: E402
from elasticsearch.helpers import streaming_bulk # noqa: E402
# All 21 supported entity types and the directory names they map to
ENTITY_DIRS: dict[str, str] = {
"works": "works",
"authors": "authors",
"sources": "sources",
"institutions": "institutions",
"topics": "topics",
"domains": "domains",
"fields": "fields",
"subfields": "subfields",
"sdgs": "sdgs",
"countries": "countries",
"continents": "continents",
"languages": "languages",
"keywords": "keywords",
"publishers": "publishers",
"funders": "funders",
"awards": "awards",
"concepts": "concepts",
"work-types": "work-types",
"source-types": "source-types",
"institution-types": "institution-types",
"licenses": "licenses",
}
STATE_FILE = "ingest_state.json"
log = logging.getLogger("openalex.ingest")
def _setup_logging(log_file: Path) -> None:
"""Configure dual logging: console (INFO) + rotating file (DEBUG)."""
root = logging.getLogger()
root.setLevel(logging.DEBUG)
fmt = logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
console.setFormatter(fmt)
root.addHandler(console)
fh = logging.FileHandler(log_file, encoding="utf-8")
fh.setLevel(logging.DEBUG)
fh.setFormatter(fmt)
root.addHandler(fh)
def _load_state(state_path: Path) -> dict:
if state_path.exists():
with open(state_path, "r", encoding="utf-8") as f:
return json.load(f)
return {"completed_files": {}, "started_at": None, "last_updated": None}
def _save_state(state_path: Path, state: dict) -> None:
state["last_updated"] = datetime.now(timezone.utc).isoformat()
tmp = state_path.with_suffix(".tmp")
with open(tmp, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2)
tmp.replace(state_path)
def _is_file_done(state: dict, entity: str, file_path: str) -> bool:
entry = state.get("completed_files", {}).get(entity, {}).get(file_path)
if entry is None:
return False
# Re-upload files that had errors on a previous run
return entry.get("errors", 0) == 0
def _mark_file_done(
state: dict, entity: str, file_path: str, stats: dict
) -> None:
state.setdefault("completed_files", {}).setdefault(entity, {})
state["completed_files"][entity][file_path] = {
"finished_at": datetime.now(timezone.utc).isoformat(),
**stats,
}
# Index rotation helpers (max-docs-per-shard limit)
def _detect_max_docs_error(info: dict) -> bool:
"""Return True if a bulk-response item failed due to the shard doc-count limit."""
for action_type in ("index", "create", "update", "delete"):
action_info = info.get(action_type, {})
error = action_info.get("error", {})
if isinstance(error, str):
if "Number of documents in the shard cannot exceed" in error:
return True
continue
if (
error.get("type") == "illegal_argument_exception"
and "Number of documents in the shard cannot exceed"
in error.get("reason", "")
):
return True
return False
def _get_active_index(base_index: str, state: dict) -> str:
"""Return the current active index name, accounting for past rotations."""
suffix = state.get("index_suffixes", {}).get(base_index, 1)
if suffix <= 1:
return base_index
return f"{base_index}-{suffix}"
def _rotate_index(
base_index: str, state: dict, es, state_path: Path
) -> str:
"""Create the next numbered index and persist the new suffix in state."""
suffixes = state.setdefault("index_suffixes", {})
current = suffixes.get(base_index, 1)
new_suffix = current + 1
suffixes[base_index] = new_suffix
new_index = f"{base_index}-{new_suffix}"
# Create the new index with the same mapping as the base index
ensure_index(es, new_index, mapping_key=base_index)
_save_state(state_path, state)
return new_index
def _iter_actions(path: Path, index_ref: list[str], base_index: str):
"""Yield bulk actions. *index_ref* is a one-element list so the caller
can switch the target index mid-stream (e.g. on shard-limit rotation).
*base_index* is the canonical name used for transform look-ups."""
for doc in read_jsonl(path):
doc = apply_transforms(doc, base_index)
action = {"_index": index_ref[0], "_source": doc}
_id = doc_id(doc)
if _id:
action["_id"] = _id
yield action
def upload_file(
es,
file_path: Path,
index: str,
batch_size: int,
base_index: str,
state: dict,
state_path: Path,
progress_interval: int = 10_000,
) -> dict:
"""Upload a single file and return stats.
If the target index hits the max-docs-per-shard limit, a new index is
created automatically (e.g. openalex-works → openalex-works-2) and
remaining documents are routed there.
"""
success = 0
failed = 0
max_docs_skipped = 0
t0 = time.monotonic()
index_ref = [index]
rotated = False
for ok, info in streaming_bulk(
es,
_iter_actions(file_path, index_ref, base_index),
chunk_size=batch_size,
raise_on_error=False,
raise_on_exception=False,
max_retries=10,
initial_backoff=2,
max_backoff=120,
):
if ok:
success += 1
else:
if _detect_max_docs_error(info):
max_docs_skipped += 1
if not rotated:
old_index = index_ref[0]
new_index = _rotate_index(
base_index, state, es, state_path
)
index_ref[0] = new_index
rotated = True
log.warning(
"Index '%s' hit max-docs-per-shard limit. "
"Rotated to '%s'. Up to %d docs from the "
"in-flight batch may need re-indexing.",
old_index,
new_index,
batch_size,
)
else:
failed += 1
log.warning("Bulk error: %s", info)
total = success + failed + max_docs_skipped
if total % progress_interval == 0:
elapsed = time.monotonic() - t0
rate = total / elapsed if elapsed > 0 else 0
log.info(
" [%s] %s — %d docs (%.0f docs/s), %d errors",
index_ref[0],
file_path.name,
total,
rate,
failed,
)
elapsed = time.monotonic() - t0
stats = {
"indexed": success,
"errors": failed,
"elapsed_s": round(elapsed, 2),
}
if max_docs_skipped > 0:
stats["max_docs_skipped"] = max_docs_skipped
stats["rotated_to"] = index_ref[0]
return stats
def discover_entities(root: Path, entities: list[str] | None) -> list[tuple[str, list[Path]]]:
"""Return [(entity_name, [file_paths, ...]), ...] for entities with data."""
result = []
targets = entities if entities else list(ENTITY_DIRS.keys())
for entity in targets:
dir_name = ENTITY_DIRS.get(entity)
if not dir_name:
log.warning("Unknown entity '%s' — skipping.", entity)
continue
entity_dir = root / dir_name
if not entity_dir.is_dir():
log.debug("Directory not found for '%s': %s", entity, entity_dir)
continue
files = sorted(
f
for f in entity_dir.rglob("*")
if f.is_file() and f.suffix in (".gz", ".jsonl", ".json")
)
if files:
result.append((entity, files))
else:
log.debug("No data files for '%s' in %s", entity, entity_dir)
return result
_shutdown_requested = False
def _signal_handler(signum, frame):
global _shutdown_requested
if _shutdown_requested:
log.warning("Forced exit.")
sys.exit(1)
_shutdown_requested = True
log.warning(
"Shutdown requested (signal %d). "
"Finishing current file, then saving state…",
signum,
)
def main() -> None:
parser = argparse.ArgumentParser(
description="OpenAlex full ingestion — bulk upload all entities to Elasticsearch",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--root",
type=Path,
default=SCRIPT_DIR,
help="Root directory containing entity subdirectories (default: script dir)",
)
parser.add_argument(
"--es-url",
default=os.environ.get("ES_URL", "http://localhost:9200"),
help="Elasticsearch URL (default: $ES_URL or http://localhost:9200)",
)
parser.add_argument(
"--entities",
nargs="+",
metavar="ENTITY",
help="Only ingest these entities (default: all found)",
)
parser.add_argument(
"--batch-size",
type=int,
default=500,
help="Bulk request batch size (default: 500)",
)
parser.add_argument(
"--state-file",
type=Path,
default=None,
help="Path to state file (default: <root>/ingest_state.json)",
)
parser.add_argument(
"--log-file",
type=Path,
default=None,
help="Path to log file (default: <root>/ingest.log)",
)
parser.add_argument(
"--reset",
action="store_true",
help="Clear state and re-ingest everything",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be uploaded without actually uploading",
)
parser.add_argument(
"--create-indices",
action="store_true",
default=True,
help="Create indices before uploading (default: true)",
)
args = parser.parse_args()
root = args.root.resolve()
state_path = args.state_file or (root / STATE_FILE)
log_path = args.log_file or (root / "ingest.log")
_setup_logging(log_path)
signal.signal(signal.SIGINT, _signal_handler)
signal.signal(signal.SIGTERM, _signal_handler)
log.info("=" * 60)
log.info("OpenAlex Ingestion")
log.info(" Root: %s", root)
log.info(" ES URL: %s", args.es_url)
log.info(" Batch size: %d", args.batch_size)
log.info(" State file: %s", state_path)
log.info(" Log file: %s", log_path)
log.info("=" * 60)
if args.reset and state_path.exists():
state_path.unlink()
log.info("State reset — starting fresh.")
state = _load_state(state_path)
if state["started_at"] is None:
state["started_at"] = datetime.now(timezone.utc).isoformat()
entity_files = discover_entities(root, args.entities)
if not entity_files:
log.error("No entity data found under %s", root)
sys.exit(1)
total_files = sum(len(files) for _, files in entity_files)
total_entities = len(entity_files)
log.info(
"Discovered %d file(s) across %d entity type(s).",
total_files,
total_entities,
)
if args.dry_run:
for entity, files in entity_files:
index = resolve_index_name(entity)
done = sum(
1 for f in files if _is_file_done(state, entity, str(f))
)
log.info(
" %-20s %3d file(s) (%d already done)",
entity,
len(files),
done,
)
log.info("Dry-run complete — nothing uploaded.")
return
es = build_es_client(args.es_url)
if not es.ping():
log.error("Cannot connect to Elasticsearch at %s", args.es_url)
sys.exit(1)
log.info("Connected to Elasticsearch.")
if args.create_indices:
for entity, _ in entity_files:
base_index = resolve_index_name(entity)
index = _get_active_index(base_index, state)
ensure_index(es, index, mapping_key=base_index)
global_start = time.monotonic()
files_done = 0
files_skipped = 0
total_indexed = 0
total_errors = 0
for entity_idx, (entity, files) in enumerate(entity_files, 1):
if _shutdown_requested:
break
base_index = resolve_index_name(entity)
index = _get_active_index(base_index, state)
log.info(
"━━━ [%d/%d] Entity: %s → %s (%d file(s)) ━━━",
entity_idx,
total_entities,
entity,
index,
len(files),
)
for file_idx, fpath in enumerate(files, 1):
if _shutdown_requested:
break
fpath_str = str(fpath)
if _is_file_done(state, entity, fpath_str):
prev = state["completed_files"][entity][fpath_str]
log.info(
" [%d/%d] %s — already done (%d indexed, skipping)",
file_idx,
len(files),
fpath.name,
prev.get("indexed", 0),
)
files_skipped += 1
continue
prev = state.get("completed_files", {}).get(entity, {}).get(fpath_str)
if prev and prev.get("errors", 0) > 0:
log.info(
" [%d/%d] Retrying %s (previous run: %d indexed, %d errors)",
file_idx,
len(files),
fpath.name,
prev.get("indexed", 0),
prev.get("errors", 0),
)
log.info(
" [%d/%d] Uploading %s …",
file_idx,
len(files),
fpath.name,
)
stats = upload_file(
es, fpath, index, args.batch_size,
base_index=base_index,
state=state,
state_path=state_path,
)
# If the index was rotated mid-file, use the new index going forward
if "rotated_to" in stats:
index = stats["rotated_to"]
log.info(
" [%d/%d] %s — %d indexed, %d errors, "
"%d max-doc-limit skipped, rotated to '%s' (%.1fs)",
file_idx,
len(files),
fpath.name,
stats["indexed"],
stats["errors"],
stats.get("max_docs_skipped", 0),
stats["rotated_to"],
stats["elapsed_s"],
)
else:
log.info(
" [%d/%d] %s — %d indexed, %d errors (%.1fs)",
file_idx,
len(files),
fpath.name,
stats["indexed"],
stats["errors"],
stats["elapsed_s"],
)
_mark_file_done(state, entity, fpath_str, stats)
_save_state(state_path, state)
files_done += 1
total_indexed += stats["indexed"]
total_errors += stats["errors"]
elapsed = time.monotonic() - global_start
log.info("=" * 60)
log.info("Ingestion %s", "interrupted" if _shutdown_requested else "complete")
log.info(" Entities processed: %d/%d", entity_idx if entity_files else 0, total_entities)
log.info(" Files uploaded: %d", files_done)
log.info(" Files skipped: %d (already done)", files_skipped)
log.info(" Total indexed: %d", total_indexed)
log.info(" Total errors: %d", total_errors)
log.info(" Wall time: %.1fs", elapsed)
if total_indexed > 0 and elapsed > 0:
log.info(" Throughput: %.0f docs/s", total_indexed / elapsed)
log.info(" State saved to: %s", state_path)
log.info("=" * 60)
_save_state(state_path, state)
if _shutdown_requested:
log.info("Re-run to continue from where it stopped.")
sys.exit(130)
if total_errors > 0:
sys.exit(1)
if __name__ == "__main__":
main()