AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Bulk Downloading and Parsing S2ORC with the Semantic Scholar Datasets API: An Industrial NLP Blueprint

Daniel Kräher · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

If you are training domain-specific language models like SciBERT or BioGPT, constructing dense scientific citation graphs, or fine-tuning retrieval-augmented generation (RAG) pipelines on scholarly literature, you will quickly hit a wall if you rely on the standard Semantic Scholar Academic Graph REST API. We see teams make this mistake repeatedly: they write pagination loops against /graph/v1/paper/search, encounter strict per-second rate limits (typically 1 to 10 requests per second even with approved partner API keys), and watch their ingestion pipelines stretch into months while dodging HTTP 429 errors and transient connection resets.

At 365Finds, our stance is unequivocal: the Academic Graph REST API is built for interactive user interfaces and targeted single-entity lookups, not for bulk corpus extraction. For multi-gigabyte or terabyte-scale academic data pipelines, you must bypass the REST query layer entirely and use the official Semantic Scholar Datasets API (https://api.semanticscholar.org/datasets/v1).

The Datasets API serves snapshot releases of the full Semantic Scholar Academic Graph (S2AG) and the Semantic Scholar Open Research Corpus (S2ORC) as partitioned, gzip-compressed JSONL files hosted on Amazon Web Services (AWS) S3. Instead of crawling records one by one, your data engineering pipeline fetches cryptographic manifests, signs partition batches, and streams multi-gigabit downloads directly into local storage, Parquet lakes, or memory buffers.

Here is how data scientists and natural language processing (NLP) engineers can design, build, and optimize an industrial-grade ingestion and parsing pipeline using the Semantic Scholar Datasets API.


Academic Graph REST API vs. Datasets API: Architectural Comparison

Understanding the structural separation between the two interfaces determines whether your data engineering project succeeds or stalls:

DimensionAcademic Graph REST API (/graph/v1)Datasets API (/datasets/v1)
Primary Design GoalInteractive lookups; live web applications; author disambiguationBulk data ingestion; foundation model pretraining; offline graph analytics
Ingestion Throughput1–10 records/second (throttled by rate limit)50–500+ MB/second (limited only by network bandwidth and S3 egress)
Data Delivery FormatSingle JSON payload per HTTP requestPartitioned, gzip-compressed JSONL files (.jsonl.gz)
Storage ArchitectureDynamically queried Elasticsearch/DynamoDB backendsDistributed object storage on AWS S3 via pre-signed URLs
Full-Text AvailabilitySnippets and abstract metadataFull parsed body text, inline citation spans, bibliographies via S2ORC
Snapshot SynchronizationLive, mutable graph stateImmutable release date stamps (YYYY-MM-DD) with deterministic diffs

Trying to fetch 10 million academic papers via the REST API at 5 requests per second requires more than 23 days of non-stop crawling, assuming zero failures. With the Datasets API, streaming 10 million records across partitioned S3 files takes under two hours on a standard cloud compute instance.


Anatomy of an S2AG Snapshot Release and S2ORC

Semantic Scholar publishes periodic snapshot releases identified by date strings in the format YYYY-MM-DD (for example, 2024-11-01). Each release comprises multiple distinct, independently partitioned datasets linked by a shared primary key: corpusid (integer) or paper_id.

Key datasets available within each release include:

  1. papers: Core bibliographic metadata, including title, publication year, venue, DOI, arXiv ID, journal, s2FieldsOfStudy (machine-classified academic disciplines), and open access licensing status.
  2. abstracts: Extracted paper abstracts paired with corpusid.
  3. s2orc: The Semantic Scholar Open Research Corpus. This dataset contains structured full-text body paragraphs extracted from open-access PDFs, including section headings (Introduction, Methods, Results), inline citation spans (cite_spans), figure/table references (ref_spans), and bibliography entries (bib_entries).
  4. citations: Directed edge lists of citations connecting citingcorpusid to citedcorpusid, annotated with citation contexts and intent classifications (methodology, background, result).
  5. authors: Disambiguated researcher profiles, publication counts, and H-index metadata.
  6. embeddings-specter_v2: Pre-computed 768-dimensional document vectors generated by the SPECTER2 model for scientific document representation.

Step 1: Querying the Release Manifest and Resolving S3 URLs

The Datasets API workflow begins by retrieving the manifest of the target snapshot. You can request the latest available snapshot or inspect specific historical releases.

import os
import requests

API_KEY = os.getenv("S2_API_KEY")
HEADERS = {"x-api-key": API_KEY} if API_KEY else {}
BASE_URL = "https://api.semanticscholar.org/datasets/v1"

# 1. Fetch available releases
releases_resp = requests.get(f"{BASE_URL}/release", headers=HEADERS)
releases_resp.raise_for_status()
all_releases = releases_resp.json()
latest_release_id = all_releases[-1]
print(f"Targeting Release ID: {latest_release_id}")

# 2. Inspect available datasets within the release
release_meta_resp = requests.get(f"{BASE_URL}/release/{latest_release_id}", headers=HEADERS)
release_meta = release_meta_resp.json()

for ds in release_meta["datasets"]:
    print(f"Dataset: {ds['name']} | {ds['description']}")

To access the actual data files, query the dataset-specific endpoint. The API does not stream large binaries directly through its web servers; instead, it returns an array of temporary, pre-signed AWS S3 URLs pointing to partitioned .jsonl.gz archives:

# 3. Retrieve pre-signed S3 download links for S2ORC and Papers
s2orc_manifest = requests.get(
    f"{BASE_URL}/release/{latest_release_id}/dataset/s2orc", 
    headers=HEADERS
).json()

s2orc_files = s2orc_manifest.get("files", [])
print(f"S2ORC dataset partitioned into {len(s2orc_files)} chunks.")

[!IMPORTANT] The S3 URLs returned by the Datasets API are pre-signed with short expiration windows (typically valid for several hours). Do not save URLs to static text files for batch processing days later; fetch the manifest programmatically at the start of your download job.


Step 2: High-Throughput Parallel Downloading and Streaming

Each partition in the files list is an independently compressed GZIP file containing newline-delimited JSON (.jsonl.gz). Attempting to decompress the entire dataset to disk before processing will exhaust local storage arrays; an uncompressed S2ORC release can exceed several terabytes.

At 365Finds, we strongly recommend a streaming extract-transform-load (ETL) pipeline. Your ingestion workers stream bytes directly over HTTP, decompress on the fly in memory, filter records against specific criteria, and write clean records into local Parquet files or LanceDB vector tables.

Here is an industrial-grade worker implementation using Python's requests streaming capabilities, gzip, and concurrent.futures:

import gzip
import io
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests

def process_s2orc_partition(s3_url: str, output_path: str, target_fields: set):
    """
    Streams a single S2ORC partition from S3, decompresses in memory,
    filters text paragraphs, and writes filtered JSONL lines to disk.
    """
    matched_count = 0
    with requests.get(s3_url, stream=True) as response:
        response.raise_for_status()
        # Stream raw gzip response directly into an in-memory decompression stream
        with gzip.GzipFile(fileobj=response.raw) as gz_stream:
            with open(output_path, "w", encoding="utf-8") as out_f:
                for line in gz_stream:
                    if not line.strip():
                        continue
                    record = json.loads(line.decode("utf-8"))
                    
                    # S2ORC schema contains 'paper_id' (or 'corpusid') and 'body_text'
                    body_text = record.get("body_text", [])
                    if not body_text:
                        continue
                    
                    # Extract section headings and full text blocks
                    structured_sections = []
                    for block in body_text:
                        section_name = block.get("section", "").strip()
                        paragraph_text = block.get("text", "").strip()
                        if paragraph_text:
                            structured_sections.append({
                                "section": section_name,
                                "text": paragraph_text,
                                "cite_count": len(block.get("cite_spans", []))
                            })
                    
                    if structured_sections:
                        clean_doc = {
                            "corpusid": record.get("corpusid") or record.get("paper_id"),
                            "sections": structured_sections,
                            "bib_entries_count": len(record.get("bib_entries", {}))
                        }
                        out_f.write(json.dumps(clean_doc, ensure_ascii=False) + "\n")
                        matched_count += 1
                        
    return matched_count

def parallel_download_pipeline(file_urls: list, output_dir: str, max_workers: int = 8):
    os.makedirs(output_dir, exist_ok=True)
    futures = {}
    
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        for idx, url in enumerate(file_urls):
            part_file = os.path.join(output_dir, f"s2orc_part_{idx:04d}.jsonl")
            future = executor.submit(process_s2orc_partition, url, part_file, set())
            futures[future] = idx
            
        for future in as_completed(futures):
            part_idx = futures[future]
            try:
                count = future.result()
                print(f"[Done] Partition {part_idx:04d}: Extracted {count} structured documents.")
            except Exception as exc:
                print(f"[Failed] Partition {part_idx:04d} raised: {exc}")

Step 3: Domain Filtering and Open Access License Verification

For teams pretraining specialized language models (such as legal, biomedical, or computer science LLMs), downloading the entire corpus is wasteful. Furthermore, commercial foundation model developers must adhere strictly to intellectual property constraints.

The papers dataset provides two critical fields for this step:

  1. s2FieldsOfStudy: Array of category objects indicating discipline classifications (such as "Medicine", "Computer Science", "Biology").
  2. isOpenAccess & openAccessPdf: Metadata indicating whether the document is publicly accessible and specifying license designations (such as cc-by, cc-by-nc, arxiv, or pmc).

The Two-Stage Join Architecture

Because papers (metadata) and s2orc (full body text) are partitioned into separate files on S3, you should never attempt a distributed cross-partition shuffle over the network without a local primary index.

365Finds recommends a two-stage filter and hash-join strategy:

flowchart TD
    A["Download 'papers' Partitions (Metadata)"] --> B["Filter by Discipline (e.g. Computer Science) and License (CC-BY)"]
    B --> C["Export Allowed 'corpusid' Set (Bloom Filter or RocksDB/DuckDB Key Index)"]
    D["Stream 's2orc' Partitions (Full Text)"] --> E{"Check 'corpusid' against Key Index"}
    E -- "Match" --> F["Decompress and Clean Body Paragraphs"]
    E -- "Miss" --> G["Discard Record (Zero Storage Overhead)"]
    F --> H["Sink to Local Parquet Lake / Training Buckets"]
  1. Phase 1 (Metadata Indexing): Stream the papers dataset partitions. Filter on s2FieldsOfStudy matching your domain and verify that openAccessPdf contains a commercially viable license. Store the resulting corpusid values in a high-speed local key-value store (such as RocksDB, DuckDB, or an in-memory integer hash set).
  2. Phase 2 (Targeted Body Extraction): Stream the s2orc partitions. For every incoming JSONL line, parse only the top-level corpusid. If the ID exists in your Phase 1 index, decompress and parse the full body_text. If it is absent, immediately discard the record.

This design reduces disk I/O and vector embedding costs by 80% to 95%, depending on the breadth of your domain filter.


Step 4: Incremental Updates via the Diffs API

Academic literature evolves continuously: new preprints arrive daily, errata are issued, and retractions occur. Semantic Scholar does not require you to re-download the multi-terabyte corpus each month. The Datasets API provides a dedicated incremental diff endpoint:

GET /datasets/v1/diffs/{start_release_id}/to/{end_release_id}/{dataset_name}

The response returns an ordered chain of updates and deletions broken down into individual release hops:

{
  "dataset": "papers",
  "start_release": "2024-10-01",
  "end_release": "2024-11-01",
  "diffs": [
    {
      "from_release": "2024-10-01",
      "to_release": "2024-10-08",
      "update_files": ["https://ai2-s2ag.s3.amazonaws.com/..."],
      "delete_files": ["https://ai2-s2ag.s3.amazonaws.com/..."]
    }
  ]
}

Implementing Incremental Synchronization

To maintain a synchronized offline document store or vector database:


Infrastructure Considerations and Cost Trade-Offs

Deploying this pipeline in production requires balancing network egress, compute instance selection, and storage costs:

  1. AWS EC2 Co-Location: Semantic Scholar's S3 buckets are hosted in the us-west-2 AWS region. If you spin up your extraction and parsing cluster on an EC2 instance in us-west-2, your network latency drops to sub-millisecond ranges and you maximize download throughput over AWS's internal network spine.
  2. Storage Formatting: Do not store parsed S2ORC text as raw JSONL files. Convert cleaned sections into partitioned Apache Parquet format with Snappy or ZSTD compression. Parquet's columnar layout enables vectorized readers (via PyArrow or Polars) to query specific metadata columns without reading full-text body strings into memory.
  3. Memory Allocation: Always use line-by-line generators or GzipFile streaming over raw HTTP sockets. Loading an entire decompressed partition into a Python list will trigger out-of-memory (OOM) kernel panics.

365Finds views the Semantic Scholar Datasets API as the definitive bridge between raw academic literature and modern scientific foundation models. By replacing fragile REST crawlers with manifest-driven S3 parallel streaming, filtering via two-stage hash joins, and maintaining parity using incremental diffs, NLP engineering teams turn months of unstable scraping into hours of deterministic data ingestion.


References