Dataset Viewer
The dataset viewer is not available for this dataset.
The JWT signature verification failed. Check the signing key and the algorithm.
Error code:   JWTInvalidSignature
Exception:    InvalidSignatureError
Message:      Signature verification failed
Traceback:    Traceback (most recent call last):
                File "/src/libs/libapi/src/libapi/jwt_token.py", line 286, in validate_jwt
                  decoded = jwt.decode(
                      jwt=token,
                  ...<2 lines>...
                      options=options,
                  )
                File "/usr/local/lib/python3.14/site-packages/jwt/api_jwt.py", line 368, in decode
                  decoded = self.decode_complete(
                      jwt,
                  ...<8 lines>...
                      leeway=leeway,
                  )
                File "/usr/local/lib/python3.14/site-packages/jwt/api_jwt.py", line 265, in decode_complete
                  decoded = self._jws.decode_complete(
                      jwt,
                  ...<3 lines>...
                      detached_payload=detached_payload,
                  )
                File "/usr/local/lib/python3.14/site-packages/jwt/api_jws.py", line 270, in decode_complete
                  self._verify_signature(
                  ~~~~~~~~~~~~~~~~~~~~~~^
                      signing_input,
                      ^^^^^^^^^^^^^^
                  ...<4 lines>...
                      options=merged_options,
                      ^^^^^^^^^^^^^^^^^^^^^^^
                  )
                  ^
                File "/usr/local/lib/python3.14/site-packages/jwt/api_jws.py", line 417, in _verify_signature
                  raise InvalidSignatureError("Signature verification failed")
              jwt.exceptions.InvalidSignatureError: Signature verification failed

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

United Nations Digital Library (UNDL) Comprehensive Master Dataset

UN Digital Library

1. Executive Summary

Welcome to the United Nations Digital Library (UNDL) Comprehensive Master Dataset repository. This dataset represents a monumental effort to harvest, normalize, enrich, and democratize access to the vast archives of the United Nations. By leveraging advanced web harvesting techniques, robust state management, and modern big-data formats, this repository provides researchers, data scientists, political analysts, and historians with an unprecedented tool for analyzing global diplomacy.

The United Nations Digital Library is the central repository for UN documents, voting data, speeches, and public domain maps. It includes materials from the General Assembly, the Security Council, the Economic and Social Council, the Trusteeship Council, and the UN Secretariat. Historically, accessing this data at scale required navigating fragmented search interfaces or dealing with complex, nested XML schemas delivered via legacy protocols.

This repository solves these challenges by providing a fully processed, machine-learning-ready Parquet dataset. The data pipeline—consisting of a highly fault-tolerant OAI-PMH harvester (un_digital_library_harvester.py) and a sophisticated enrichment engine (jsonl_to_parquet.py)—transforms raw institutional metadata into a pristine, structured format.

Whether your goal is to train multilingual large language models (LLMs), conduct longitudinal studies on geopolitical shifts, build graph neural networks mapping diplomatic relationships, or simply run ad-hoc SQL queries on historical resolutions, this dataset provides the foundational infrastructure required for rigorous, data-driven analysis of international relations.

1.1 The Importance of the United Nations Archives

The United Nations was founded in 1945 following the devastation of the Second World War, with one central mission: the maintenance of international peace and security. Over the subsequent decades, the UN has expanded its mandate to encompass sustainable development, human rights, humanitarian assistance, and the upholding of international law. Every debate, every resolution, every treaty, and every report generated in pursuit of these goals is documented.

These documents are not merely bureaucratic records; they are the primary source material for the modern history of global governance. They contain the rhetorical strategies of superpowers during the Cold War, the foundational texts of decolonization, the evolution of international climate policy, and the shifting alliances of the 21st century.

However, the sheer volume and complexity of these records present a formidable barrier to entry. Documents are published in the six official languages of the UN (Arabic, Chinese, English, French, Russian, and Spanish). They are categorized using arcane document symbols. They refer to entities and geopolitical concepts that change over time (e.g., Zaire becoming the Democratic Republic of the Congo, or the shifting membership of the Security Council).

By providing this dataset, we aim to lower the barrier to entry for computational social science. NLP researchers can now easily access aligned multilingual corpora. Political scientists can apply topic modeling to decades of General Assembly debates. Legal scholars can trace the evolution of human rights norms across thousands of committee reports.

2. Data Acquisition: The OAI-PMH Harvester Pipeline

The data contained in this repository is not a static dump; it is the product of a sophisticated, custom-built harvesting pipeline designed to interact with the UN Digital Library's Open Archives Initiative Protocol for Metadata Harvesting (OAI-PMH) endpoint. The script un_digital_library_harvester.py is an enterprise-grade ETL (Extract, Transform, Load) tool built to handle the realities of scraping a large, rate-limited institutional repository.

2.1 The OAI-PMH Protocol Mechanics

The OAI-PMH protocol is a widely adopted standard for interoperability among digital libraries. It operates over HTTP and serves XML-formatted metadata. The harvester utilizes several key "verbs" defined by the protocol:

  1. Identify: The pipeline begins by querying the repository's identity, confirming the base URL, administration email, and the earliest datestamp of available records.
  2. ListMetadataFormats: The UN Digital Library supports multiple metadata formats. Our harvester is capable of processing oai_dc (Dublin Core), marcxml (Machine-Readable Cataloging), and oai_openaire (OpenAIRE/DataCite). Dublin Core provides a solid baseline of title, creator, subject, and date, while MARCXML provides exhaustive bibliographic depth.
  3. ListSets: The repository organizes records into sets (e.g., voting records, speeches, resolutions). The harvester can be configured to target specific sets or harvest the entire library.
  4. ListRecords: This is the core verb used for data extraction. The harvester requests records in chunks. Because the dataset contains hundreds of thousands of records, the server cannot return them all at once. Instead, it returns a partial list along with a resumptionToken.

2.2 Resumability and State Management

Harvesting a dataset of this magnitude can take days, and network interruptions are inevitable. The UNHarvester class implements a robust state management system. Every time a batch of records is successfully processed, the harvester serializes its current state to a harvest_state.json file.

This state file tracks:

  • The current resumptionToken
  • The metadata_prefix being used
  • Optional from_date and until_date parameters for incremental updates
  • The cursor position (number of records processed)
  • The complete_list_size (total expected records)
  • The total harvested_count

If the process is terminated—whether due to a power failure, a user interrupt (SIGINT), or a fatal server error—the user can simply restart the script with the --resume flag. The harvester will deserialize the state file, present the correct resumption token to the OAI-PMH endpoint, and continue exactly where it left off without duplicating data or missing records.

2.3 Network Resilience and Exponential Backoff

Institutional servers often implement strict rate limiting and may temporarily fail under heavy load. The OAIClient class is built to be a good netizen while ensuring maximum reliability.

  • Rate Limiting: A configurable delay (defaulting to 3.0 seconds) is strictly enforced between every HTTP request. This prevents overwhelming the UN servers.
  • Exponential Backoff: When the server returns HTTP status codes indicative of overload (e.g., 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout), the client does not crash. Instead, it catches the error, logs a warning, and waits. The wait time starts at a configurable backoff (default 5.0 seconds) and doubles with every subsequent failure on the same request (10s, 20s, 40s...).
  • Retry Logic: If a request fails entirely (e.g., connection reset), the client will retry up to a specified number of times (default 5) before escalating the failure to a fatal OAIError.

2.4 XML Parsing and Namespace Resolution

OAI-PMH responses are complex XML documents utilizing multiple namespaces. The client utilizes Python's xml.etree.ElementTree to parse the responses safely. It dynamically handles namespaces such as:

  • http://www.openarchives.org/OAI/2.0/
  • http://www.openarchives.org/OAI/2.0/oai_dc/
  • http://purl.org/dc/elements/1.1/
  • http://www.loc.gov/MARC21/slim

The _parse_metadata method flattens this nested XML into a clean, normalized Python dictionary, stripping out namespace prefixes and handling edge cases where fields might be repeated or absent.

2.5 PDF and Export Link Extraction

Beyond metadata, researchers often need the full text. The harvester actively scans the parsed identifiers for URLs terminating in .pdf or URLs pointing to the digitallibrary.un.org/record/... landing pages. It maintains a separate stream of these high-value links, saving them to pdf_links.jsonl. This allows downstream processes to easily spawn asynchronous downloaders (like wget or aria2) to fetch the raw PDF documents for OCR and full-text indexing.

3. Data Enrichment & Transformation

The raw JSONL output of the harvester, while well-structured, is optimized for storage rather than analysis. Metadata fields often contain pipe-delimited strings, implicit relationships, and idiosyncratic date formats.

The jsonl_to_parquet.py script acts as the semantic enrichment layer, transforming the raw JSONL into highly optimized Parquet shards.

3.1 Structural Normalization and Parquet Conversion

The script utilizes pandas and pyarrow to convert the dynamic JSON schema into a strict, columnar Parquet format. Parquet was chosen because it provides:

  • High Compression: Using the zstd algorithm, the dataset size on disk is drastically reduced.
  • Columnar Efficiency: Analytics queries that only touch a few columns (e.g., counting resolutions by year) execute orders of magnitude faster because they don't need to load the full text of the records into memory.
  • Type Safety: Dates are cast to integers, booleans are enforced, and arrays are treated as native list structures rather than comma-separated strings.
  • Sharding: The output is split into manageable chunks (default 1000 records per shard). This allows for distributed processing using frameworks like Apache Spark or Dask.

3.2 UN Body Resolution and Classification

UN documents are tracked using a complex symbol system. The enrichment pipeline includes a deterministic parser (extract_un_body) that maps these symbols to the principal organs of the United Nations:

  • A/: Indicates the General Assembly, the main deliberative organ representing all member states.
  • S/: Indicates the Security Council, responsible for international peace and security.
  • E/: Indicates the Economic and Social Council (ECOSOC).
  • T/: Indicates the Trusteeship Council (largely inactive since 1994, but historically vital).
  • ST/: Indicates the UN Secretariat.

By extracting this feature, researchers can instantly filter the dataset to compare the output of the Security Council versus the General Assembly over time.

3.3 Document Hierarchy and Lineage

Many UN documents are not standalone entities; they are revisions, addendums, or corrigendums to parent documents. The extract_parent_symbol function uses regular expressions (^(.*?)(?:/(?:Add|Rev|Corr)\.)) to strip away these suffixes. For example, if a document symbol is A/75/1/Add.1, the script identifies it as an addendum and extracts the parent symbol A/75/1. This enables the construction of complex document dependency graphs.

3.4 Temporal Enrichment

Dates in library metadata can be notoriously messy. The pipeline includes a robust regex-based temporal parser:

  • Exact dates (YYYY-MM-DD) are parsed, and the year is extracted.
  • Month-only dates (YYYY-MM) are parsed.
  • Year-only dates (YYYY) are supported. The script outputs both the raw event_date and a normalized integer year, alongside a date_precision flag (exact, month-only, year-only). This ensures that time-series analyses are statistically sound and don't make false assumptions about the precision of the underlying data.

3.5 Geopolitical Entity Extraction (Member States)

One of the most powerful features of the enrichment pipeline is the automatic detection of member states. The script maintains a comprehensive, hardcoded set of the 193 UN Member States (plus historically significant entities like Yugoslavia).

During processing, the script scans both the title and the subjects array. If a country name (e.g., "France", "Sudan", "Democratic Republic of the Congo") is detected, it is appended to the countries_mentioned list column. This turns a simple metadata dump into a high-value relational dataset. You can instantly query for all Security Council resolutions mentioning "Afghanistan" between 2000 and 2020.

3.6 Language Mapping

Documents are tagged with ISO 639-2 three-letter language codes (e.g., eng, fre, ara). The pipeline utilizes a LANGUAGE_MAP dictionary to convert these cryptic codes into human-readable strings ("English", "French", "Arabic"). It also filters out malformed or unexpected codes using a strict regex ([a-z]{3}).

3.7 Programmatic Export URLs

For researchers who need to cross-reference the data with citation managers, the script dynamically reconstructs the UN Digital Library's export API endpoints. Based on the record_id, it generates a JSON object (export_formats_json) containing direct links to download the record in BibTeX, EndNote, RefWorks, RIS, and DublinCore formats.

4. Parquet Schema Definition

The resulting Parquet shards adhere strictly to the following schema. Understanding this schema is crucial for writing efficient analytical queries.

Column Name Data Type Description Example
record_id Int64 The unique integer identifier assigned by the UN Digital Library system. Extracted from the OAI identifier. 3849102
doc_symbol String The official UN document symbol. This is the primary alphanumeric key used globally to reference the text. S/RES/2585(2021)
un_body String The principal UN organ responsible for the document, derived from the doc_symbol prefix. Security Council
is_resolution Boolean Flag indicating if the document is a formal resolution (contains /RES/ in the symbol). true
is_addendum Boolean Flag indicating if the document is an addendum, revision, or corrigendum. false
parent_record_symbol String If is_addendum is true, this contains the doc_symbol of the original parent document. A/75/250
title String The primary title of the document. Usually provided in English, but may vary depending on the original metadata. Resolution adopted by the General Assembly on 2 March 2022
event_date String The raw date string as provided by the metadata. 2022-03-02
year Int64 The extracted 4-digit year of the document, optimized for fast time-series aggregation. 2022
date_precision String The precision level of the event_date. Values: exact, month-only, year-only, or null. exact
subjects List[String] An array of topical keywords and subjects assigned by UN librarians. ["PEACEKEEPING OPERATIONS", "MALI", "HUMAN RIGHTS"]
primary_topic String The first subject in the subjects array. Useful for quick categorization. PEACEKEEPING OPERATIONS
countries_mentioned List[String] An array of UN member states explicitly mentioned in the title or subjects. ["Mali", "France"]
languages List[String] An array of human-readable languages in which the document is available. ["English", "French", "Arabic", "Russian", "Spanish", "Chinese"]
record_url String The direct HTTP URL to the document's landing page on the UN Digital Library website. https://digitallibrary.un.org/record/3849102
pdf_url String The direct HTTP URL to download the full PDF text (if available). https://digitallibrary.un.org/record/3849102/files/S_RES_2585-EN.pdf
has_pdf Boolean Flag indicating whether a direct PDF link was found in the metadata. true
export_formats_json String A JSON-encoded dictionary of URLs for exporting the citation (BibTeX, RIS, etc.). {"bibtex": "..."}
oai_datestamp String The internal system timestamp indicating when the metadata record was last modified on the OAI server. 2024-01-15T08:32:11Z

5. Extensive Breakdown of UN Document Symbols

Understanding the alphanumeric codes that the UN uses to classify its documents is critical for filtering this dataset effectively. The doc_symbol field is the Rosetta Stone of this entire corpus.

The standard format is generally: [Organ]/[Session or Year]/[Document Number]

5.1 Main Organ Prefixes

  • A/ - General Assembly: The central deliberative and policymaking organ. Documents with this prefix reflect the debates and resolutions of all UN member states.
  • S/ - Security Council: The organ responsible for the maintenance of international peace and security. Documents here are often binding under international law (unlike General Assembly resolutions, which are mostly advisory).
  • E/ - Economic and Social Council: Documents pertaining to global economic, social, and environmental issues.
  • T/ - Trusteeship Council: Documents from the council that supervised the administration of trust territories (mostly historical data pre-1994).
  • ST/ - Secretariat: Administrative and executive documents from the Secretary-General and UN staff.

5.2 Suffixes and Sub-bodies

Following the main organ prefix, you will frequently encounter sub-body prefixes:

  • /C.1/ to /C.6/ - Main Committees of the General Assembly (e.g., A/C.1/ is the Disarmament and International Security Committee).
  • /CN. - Commissions (e.g., E/CN.4/ was the Commission on Human Rights).
  • /CONF. - United Nations Conferences (e.g., A/CONF.226/ for the World Conference on Disaster Risk Reduction).
  • /WG. - Working Groups.

5.3 Nature of the Document

The symbol also denotes the exact type of document:

  • /RES/ - Resolution: A formal expression of opinion or will by a UN organ. These are the most critical documents in the dataset for political science research.
  • /PRST/ - Presidential Statement (primarily in the Security Council): A statement made by the President of the Security Council on behalf of the Council.
  • /DEC/ - Decision: Formal actions that are not resolutions, often procedural.
  • /L. - Limited Distribution: Draft documents and draft resolutions before they are finalized.
  • /PV. - Verbatim Record (Procès-verbal): The exact, word-for-word transcript of a meeting or debate.
  • /SR. - Summary Record: A summarized version of a meeting's proceedings.

5.4 Modifications and Edits

Our enrichment pipeline parses these suffixes specifically into the is_addendum and parent_record_symbol fields:

  • /Add. - Addendum: Addition of text to the main document.
  • /Amend. - Amendment: Alteration, by decision of the competent authority, of a portion of an adopted document.
  • /Corr. - Corrigendum: Correction of errors, not affecting the substance of the text.
  • /Rev. - Revision: A new version of a document, replacing texts issued previously.

Knowing this structure allows you to query the dataset with incredible precision. If you want to analyze draft resolutions in the First Committee of the General Assembly, you would search for symbols matching the pattern A/C.1/%/L.%.

6. Comprehensive Usage Guides & Code Examples

This dataset is designed to be highly interoperable with the modern Python data science ecosystem. Below are extensive, production-ready examples demonstrating how to leverage the data across various frameworks.

6.1 Using HuggingFace datasets

The datasets library from HuggingFace is the standard for NLP workflows. It leverages memory-mapping, meaning you can load the entire dataset on a laptop with limited RAM.

from datasets import load_dataset
import pandas as pd

# Load the parquet files directly from the directory
print("Loading UN dataset...")
dataset = load_dataset("parquet", data_files="un_parquet/shard_*.parquet", split="train")

print(f"Loaded {len(dataset)} records.")

# Filter for all Security Council Resolutions in 2023
sc_res_2023 = dataset.filter(
    lambda x: x["un_body"] == "Security Council" 
    and x["is_resolution"] == True 
    and x["year"] == 2023
)

print(f"Found {len(sc_res_2023)} Security Council resolutions in 2023.")

# Print the titles and mentioned countries
for i in range(min(5, len(sc_res_2023))):
    print("-" * 50)
    print(f"Symbol: {sc_res_2023['doc_symbol'][i]}")
    print(f"Title:  {sc_res_2023['title'][i]}")
    print(f"Countries: {sc_res_2023['countries_mentioned'][i]}")

6.2 Ultra-Fast SQL Analytics with DuckDB

DuckDB is an in-process SQL OLAP database management system. It is uniquely optimized for querying Parquet files directly without requiring a separate server or heavy ingestion process.

import duckdb

# Connect to an in-memory DuckDB instance
con = duckdb.connect(database=':memory:')

# Query the combined parquet file to find the most mentioned countries in the General Assembly
query = """
SELECT 
    country,
    COUNT(*) as mention_count
FROM (
    -- Unnest the countries_mentioned array
    SELECT 
        unnest(countries_mentioned) as country
    FROM 'un_parquet/combined.parquet'
    WHERE un_body = 'General Assembly'
      AND year >= 2000
)
GROUP BY country
ORDER BY mention_count DESC
LIMIT 10;
"""

print("Executing analytical query...")
results = con.execute(query).df()
print("\nTop 10 Most Mentioned Countries in the General Assembly (2000-Present):")
print(results.to_markdown(index=False))

# Complex Query: Tracking the shifting focus of ECOSOC over decades
trend_query = """
SELECT 
    FLOOR(year/10)*10 as decade,
    primary_topic,
    COUNT(*) as topic_count
FROM 'un_parquet/combined.parquet'
WHERE un_body = 'Economic and Social Council'
  AND primary_topic IS NOT NULL
  AND year >= 1970
GROUP BY decade, primary_topic
QUALIFY ROW_NUMBER() OVER(PARTITION BY decade ORDER BY topic_count DESC) <= 3
ORDER BY decade ASC, topic_count DESC;
"""

print("\nTop 3 ECOSOC Topics per Decade:")
trend_results = con.execute(trend_query).df()
print(trend_results.to_markdown(index=False))

6.3 Distributed Processing with PySpark

For enterprise-scale feature engineering or machine learning pipelines, PySpark is the framework of choice. The partitioned shard structure makes loading into a Spark cluster extremely efficient.

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, explode, count, desc

# Initialize Spark Session
spark = SparkSession.builder \
    .appName("UN_Data_Analytics") \
    .config("spark.sql.parquet.filterPushdown", "true") \
    .getOrCreate()

# Read the directory of parquet shards
df = spark.read.parquet("un_parquet/shard_*.parquet")

print(f"Total rows in Spark DataFrame: {df.count()}")

# Find the most common document types that lack a PDF link
missing_pdfs = df.filter(col("has_pdf") == False) \
                 .groupBy("un_body") \
                 .count() \
                 .orderBy(desc("count"))

print("Missing PDFs by UN Body:")
missing_pdfs.show()

# Perform an explode operation to count subject frequencies across all resolutions
subjects_df = df.filter(col("is_resolution") == True) \
                .select(explode(col("subjects")).alias("subject")) \
                .groupBy("subject") \
                .count() \
                .orderBy(desc("count"))

print("Most frequent subjects across all resolutions:")
subjects_df.show(20, truncate=False)

spark.stop()

6.4 Graph Analysis with NetworkX

Because our pipeline extracts parent_record_symbol, you can build directed acyclic graphs (DAGs) of document lineage. This is particularly useful for studying how drafts evolve into final resolutions.

import networkx as nx
import pyarrow.parquet as pq

print("Loading dataset for graph generation...")
table = pq.read_table("un_parquet/combined.parquet", columns=["doc_symbol", "parent_record_symbol", "is_addendum"])
df = table.to_pandas()

# Filter for documents that have a parent
edges_df = df[df['is_addendum'] == True].dropna(subset=['parent_record_symbol', 'doc_symbol'])

# Create a Directed Graph
G = nx.DiGraph()

# Add edges from parent to child (addendum)
for _, row in edges_df.iterrows():
    G.add_edge(row['parent_record_symbol'], row['doc_symbol'])

print(f"Generated Document Graph with {G.number_of_nodes()} nodes and {G.number_of_edges()} edges.")

# Find documents with the most addendums/revisions (highest out-degree)
degrees = dict(G.out_degree())
sorted_degrees = sorted(degrees.items(), key=lambda item: item[1], reverse=True)

print("\nDocuments with the most revisions/addendums:")
for node, degree in sorted_degrees[:5]:
    print(f" - {node}: {degree} child documents")

7. Deep Dive: Machine Learning & NLP Applications

The richness of this dataset opens up numerous avenues for advanced computational research. The sheer volume of text metadata makes it perfect for modern neural network architectures. Below are detailed discussions of potential applications, ranging from basic text classification to advanced generative AI fine-tuning.

7.1 Multilingual Model Pretraining and Fine-Tuning (LLMs)

The United Nations operates in six official languages. Because documents are often translated into all six, the UN Digital Library acts as one of the highest-quality parallel corpora in existence. While this dataset primarily contains the English metadata and titles, the pdf_url field allows researchers to systematically download the PDFs for specific resolutions, OCR them using tools like Tesseract or AWS Textract, and align the multilingual texts.

This alignment is critical for fine-tuning Large Language Models (LLMs) like Llama-3, Mistral, or GPT-4 architectures on diplomatic, legal, and formal registers across languages. A model fine-tuned on UN resolutions can serve as an expert assistant for drafting international legal frameworks, ensuring consistency and adherence to established diplomatic terminology.

Furthermore, you can use the subjects and title pairs to train sequence-to-sequence models (like T5 or BART) to automatically tag new diplomatic documents with appropriate keywords, effectively automating the job of UN catalogers.

7.2 Training a Custom BERT-based Classifier for Topic Tagging

Consider a scenario where you have newly drafted text and you want to predict which UN primary_topic it belongs to. You can easily fine-tune a pre-trained BERT model using the PyTorch ecosystem and the HuggingFace transformers library on this dataset.

# Conceptual Example for Fine-Tuning BERT
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset
import torch

# 1. Load the data
dataset = load_dataset("parquet", data_files="un_parquet/shard_*.parquet", split="train")

# 2. Filter out records without titles or topics
dataset = dataset.filter(lambda x: x['title'] is not None and x['primary_topic'] is not None)

# 3. Create a label mapping
labels = dataset.unique('primary_topic')
label2id = {label: i for i, label in enumerate(labels)}
id2label = {i: label for label, i in label2id.items()}

# 4. Tokenize
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
def tokenize_function(examples):
    tokens = tokenizer(examples["title"], padding="max_length", truncation=True)
    tokens["labels"] = [label2id[topic] for topic in examples["primary_topic"]]
    return tokens

tokenized_datasets = dataset.map(tokenize_function, batched=True)

# 5. Initialize Model and Trainer
model = AutoModelForSequenceClassification.from_pretrained(
    "bert-base-uncased", num_labels=len(labels), id2label=id2label, label2id=label2id
)

training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets.shuffle(seed=42).select(range(10000)), # Sample for speed
)

# trainer.train() # Execute training

7.3 Topic Modeling and Latent Dirichlet Allocation (LDA)

The subjects and title fields are prime candidates for unsupervised topic modeling techniques such as LDA or modern transformer-based methods like BERTopic.

By chunking the dataset into discrete time periods (e.g., Cold War era, post-9/11 era, COVID-19 pandemic era), researchers can trace the conceptual shifts in global priorities. For example, one could statistically map the decline of terminology related to "decolonization" in the 1960s and 70s, and the corresponding rise of terms related to "sustainable development" and "climate change" in the 1990s and 2000s.

7.4 Zero-Shot Classification and Event Detection

Using transformer models like BART-large-mnli, researchers can classify the raw titles or abstracts into custom categories without needing labeled training data. By feeding the title field into a zero-shot classifier alongside candidate labels like ["Armed Conflict", "Humanitarian Aid", "Economic Sanctions", "Environmental Protection"], one can rapidly categorize historical documents that lack comprehensive subject tags.

Furthermore, analyzing the frequency of documents published within specific weeks can serve as a robust event detection mechanism. Spikes in Security Council activity historically correlate with sudden geopolitical crises, providing a quantitative timeline of global instability.

7.5 Temporal Knowledge Graphs (TKG)

By combining the entity extraction (countries_mentioned), the timestamp (year), and the topic (primary_topic), researchers can construct a Temporal Knowledge Graph. A TKG represents facts as a sequence of interactions over time.

For instance, a node for "Iraq" and a node for "United States" might share an edge labeled "Security Council Intervention" heavily weighted in the years 1991 and 2003. Applying Graph Neural Networks (GNNs) to this TKG can reveal complex, higher-order diplomatic relationships, predict future alliance formations, or identify diplomatic isolation.

8. Quality Assurance, Ethical Considerations, and Limitations

While every effort has been made to ensure the highest quality dataset, users must be aware of the inherent limitations of archival data and the ethical considerations surrounding its use. Machine learning models trained on this data will implicitly inherit these biases.

8.1 Representation and Diplomatic Nuance

The documents produced by the United Nations are inherently political. The language used in resolutions is the result of intense negotiation, compromise, and diplomatic maneuvering. Therefore, the dataset should not be viewed as an objective ground-truth record of historical events, but rather as the official, consensus-driven narrative of the international community.

For example, the dataset will reflect the recognized sovereignty of states at the time a document was published. Terminology surrounding disputed territories or uncrecognized states will conform to UN standards. Researchers analyzing sentiment or entity relationships must account for this institutional filter; the absence of a mention may be just as politically significant as its presence. When using this data to train LLMs, the resulting model will naturally output "diplomatic speak," avoiding direct assigning of blame and preferring passive, institutional phrasing.

8.2 Data Sparsity and Missing Values

The UN Digital Library aggregates records spanning over 75 years. The cataloging standards have evolved significantly during this time.

  • Older Records: Documents from the 1940s to the 1970s may have sparse metadata. They are less likely to have comprehensive subjects arrays and are more likely to have date_precision set to year-only.
  • OCR Artifacts: If you choose to download the PDFs using the pdf_url, be aware that documents prior to the 1990s are usually scanned images. Extracting text from these requires Optical Character Recognition (OCR), which can introduce artifacts and noise, especially in languages with non-Latin scripts (Arabic, Chinese, Russian).
  • Missing PDFs: Not all metadata records have an associated PDF. The has_pdf boolean flag explicitly tracks this. In some cases, the document may be classified, restricted to physical archives, or simply not yet digitized.

8.3 Geopolitical Entity Extraction Limitations

The countries_mentioned column relies on a deterministic keyword matching algorithm based on a predefined set of 193 member states. This approach, while fast and transparent, has limitations:

  • Historical Names: The algorithm currently maps modern names. If a document refers to "Ceylon" instead of "Sri Lanka", or "Burma" instead of "Myanmar", the entity might be missed unless explicitly handled in future updates.
  • Overlapping Names: Simple string matching can occasionally trigger false positives (e.g., mentioning "Niger" might inadvertently be captured when scanning for "Nigeria" if word boundaries are not perfectly enforced). The pipeline attempts to mitigate this, but researchers doing highly sensitive entity tracking should augment this column with state-of-the-art Named Entity Recognition (NER) models like Spacy or Stanford CoreNLP.

8.4 Language Bias and Translation

While the UN has six official languages, English is the dominant working language. Often, metadata and titles are generated primarily in English, with other languages provided subsequently. When analyzing the title field, expect a heavy skew towards English. If precise multilingual analysis is required, you must rely on the underlying PDF documents rather than the metadata titles alone.

9. Glossary and Frequently Asked Questions (FAQ)

9.1 Glossary of Terms

  • OAI-PMH: Open Archives Initiative Protocol for Metadata Harvesting. The standard protocol used to scrape the digital library.
  • MARCXML: A machine-readable format used by libraries to encode bibliographic information. Much more detailed than Dublin Core.
  • Dublin Core (oai_dc): A simplified metadata standard consisting of 15 core elements (Title, Creator, Subject, Description, etc.).
  • Parquet: An open-source, column-oriented data file format designed for efficient data storage and retrieval in big data processing frameworks like Apache Hadoop and Spark.
  • ECOSOC: Economic and Social Council of the United Nations.

9.2 FAQ

Q: Can I use this dataset for commercial purposes? A: The dataset is licensed under CC-BY-4.0. You are generally free to use it for commercial purposes, provided you give appropriate attribution to the authors and the original source (The United Nations Digital Library). However, the underlying UN documents themselves may have specific copyright restrictions depending on their nature, so commercial users should consult UN copyright guidelines regarding the reproduction of full-text documents.

Q: How often is the dataset updated? A: This repository represents a snapshot taken in July 2026. However, the provided harvester scripts allow any user to run incremental updates on their own machines using the --from-date flag.

Q: Why are there multiple Parquet files (shard_0000.parquet, shard_0001.parquet)? A: Large datasets are "sharded" or partitioned to allow distributed computing frameworks like PySpark or Dask to read the data in parallel. Reading 10 small files concurrently across 10 CPU cores is much faster than one CPU core reading one massive file. We also provide combined.parquet for simpler, single-node workflows.

Q: Why doesn't every record have a PDF URL? A: The UN Digital Library contains metadata for many physical objects, older documents that haven't been digitized, or internal communications that are not public. The has_pdf flag is provided so you can easily filter these out.

Q: Can I get the data in CSV format instead? A: While Parquet is highly recommended, you can easily convert the Parquet files to CSV using pandas:

import pandas as pd
df = pd.read_parquet('un_parquet/combined.parquet')
df.to_csv('un_dataset.csv', index=False)

Note that array columns (like subjects and countries_mentioned) will be converted to string representations of lists in the CSV, which are harder to parse later.

10. Maintainability, Contribution, and Future Work

This dataset is designed as a living, extensible repository. The provided scripts are fully capable of performing incremental updates.

10.1 Performing Incremental Updates

To bring the dataset up to date with the latest UN activity, you do not need to re-harvest the entire archive. Use the --from-date argument in the harvester:

# 1. Harvest only records created since January 1, 2027
python un_digital_library_harvester.py \
    --format oai_dc \
    --output ./un_dataset \
    --from-date 2027-01-01

# 2. Run the Parquet converter on the new JSONL file
python jsonl_to_parquet.py \
    --input ./un_dataset/records_oai_dc.jsonl \
    --output ./un_parquet_updates

10.2 Planned Enhancements

Future iterations of this dataset aim to include:

  1. Full-Text Integration: Distributing a subset of the dataset (e.g., all Security Council Resolutions) with the raw extracted text embedded directly into the Parquet files as a full_text column.
  2. Advanced NER Integration: Replacing the deterministic country matching with a fine-tuned RoBERTa model to extract Politicians, Treaties, and Geographic Locations.
  3. Voting Data Alignment: Linking resolution documents directly to the roll-call voting records to analyze which member states supported or opposed specific texts.

10.3 Contributing

We welcome contributions from the data science and political science communities. If you identify parsing errors, missed document symbols, or wish to contribute additional enrichment features (such as sentiment analysis scores), please submit a Pull Request to the code repository containing the data pipeline scripts. Ensure that your code follows PEP-8 standards and includes appropriate unit tests.

11. Authors, Licensing, and Citation

11.1 Licensing

The metadata harvested from the United Nations Digital Library is generally considered to be in the public domain or available for unrestricted use for research purposes. The code scripts (un_digital_library_harvester.py and jsonl_to_parquet.py) and the specific structured Parquet format provided in this repository are released under the Creative Commons Attribution 4.0 International (CC-BY-4.0) license. You are free to share and adapt the material, provided you give appropriate credit.

11.2 Citation Information

If you use this dataset, the harvester pipeline, or the enriched Parquet schemas in your academic research, policy analysis, or machine learning training, please cite it as follows:

@misc{undl_master_dataset_2026,
  author       = {Data Science Team},
  title        = {United Nations Digital Library (UNDL) Comprehensive Master Dataset},
  year         = {2026},
  publisher    = {Hugging Face},
  howpublished = {\url{https://huggingface.co/datasets/un-digital-library-master}},
  note         = {Parquet Enriched Pipeline},
}

11.3 Acknowledgments

We extend our deep gratitude to the librarians, archivists, and engineers at the United Nations who maintain the OAI-PMH infrastructure. Their commitment to transparency and open access to information makes large-scale computational analysis of global governance possible. We also thank the open-source communities behind Python, Pandas, PyArrow, DuckDB, and HuggingFace for providing the tools that make this analysis accessible to everyone.


Generated automatically by the UNDL Harvester Pipeline Analytics Engine.

Downloads last month
154