Building a Movie and TV Knowledge Graph: Metadata Extraction and Modeling Practices
Extracting and structuring movie and TV metadata into a knowledge graph enables efficient complex queries and intelligent recommendations. This article details a practical path for modeling hierarchical data, defining entities and relationships, cleaning unstructured text, and implementing graph queries and cloud-native operations, providing a concrete blueprint for data engineers and developers.
With the rapid development of the streaming and digital content industry, massive amounts of movie and TV metadata have accumulated on the internet. When users search for “TV series starring a specific actor,” the results often include multiple series, seasons, and specific episodes, typically existing as plain text or semi-structured encyclopedia entries. The lack of unified field standards and incomplete relationship data leads to low retrieval efficiency, making complex associative queries and intelligent recommendations difficult. Using TV series participation data as an example, this article explains how to extract entities and relationships, construct a knowledge graph, and provides directly executable methods for modeling, cleaning, and querying.
1. Hierarchical Structure and Modeling of TV Data
A multi-season anthology series typically includes metadata such as series name, season number, premiere date, completion status, episode duration, episode title, director, writer, and cast. While relational databases can store these fields, querying “which episodes a specific writer wrote in the seasons where a specific actor appeared” requires multiple JOINs, complicating both the schema and query statements. Graph models treat entities as nodes and relationships as edges, allowing such queries to expand directly along paths, making them more suitable for this network structure.
1.1 Entity Definition
- Person: Actors, directors, writers, etc. Attributes include
person_id, name, nationality, and an alias list. - Series: A collection of a complete work. Attributes include
series_id, title, and genre (e.g., drama, anthology). - Season: A sub-collection under a series. Attributes include
season_id,season_number, premiere date, and completion status. - Episode: A specific episode under a season. Attributes include
episode_id,episode_number, premiere date, standalone story title, and duration.
1.2 Relationship Definition
- ACTED_IN: Person points to Season or Episode.
- DIRECTED: Person points to Season or Episode.
- WROTE: Person points to Episode.
- HAS_SEASON: Series points to Season.
- HAS_EPISODE: Season points to Episode.
1.3 Graph Model Constraints
The following rules must be written into data validation to avoid ambiguous query results.
- Unique Keys:
Person.person_id,Series.series_id,Season.season_id, andEpisode.episode_idmust all be unique. Theseason_idis generated by concatenatingseries_idand the season number (e.g.,series_001_S05) to ensure no duplicate seasons within a series. Theepisode_idis similarly generated by concatenatingseason_idand the episode number. - Ownership Constraints: Each Season must have exactly one incoming
HAS_SEASONedge; each Episode must have exactly one incomingHAS_EPISODEedge. - Direction Constraints: The start node of
ACTED_IN,DIRECTED, andWROTEmust be a Person. The end node ofWROTEcan only be an Episode. - Backfill Rules: Episode-level cast records are saved only as raw facts and do not automatically generate season-level
ACTED_INedges. If business logic requires season-level results, a derived task should generate the edges withderived=trueandsource="episode"properties. Season-level records directly from source data are markedderived=false. This prevents mistakenly inferring that “an actor participated in an entire season” from “an actor appeared in a specific episode.”
2. Data Extraction and Cleaning: How to Do It?
Data quality determines the usability of the graph. The extraction process is divided into three steps, each requiring defined inputs and outputs while retaining traceable source information.
2.1 Unstructured Text Parsing
The input is a single encyclopedia entry or text segment, with fields including source_id, raw_text, source_url, and fetched_at. The output is a set of candidate records, each containing field_name, value, text position (start and end character indices), and confidence.
Names, titles, season numbers, and episode numbers are extracted using a Named Entity Recognition (NER) model. The model name, version, and training data source should be recorded in the pipeline configuration for reproducibility. Numerical attributes like time and duration are extracted using regular expressions, such as “premiered on November 14, 1951,” “58 episodes in total,” or “about 60 minutes per episode.” Relational sentences like “A certain actor starred in Season 5…” are parsed using dependency syntax to identify predicates and objects to determine the relationship type.
2.2 Entity Alignment and Disambiguation: How to Do It?
The same actor may have multiple translated names, such as a full name, an abbreviation, and an original English name. An entity dictionary must be established so that each person corresponds to only one person_id, with all variations stored in an alias table.
Matching occurs in two steps. First, rule-based matching aligns entities if they are identical after normalization or match an alias. Second, string similarity is calculated and scored in combination with contextual features (same series, same season).
The following thresholds are starting points and need to be calibrated with manually annotated samples. If the comprehensive score is 0.92 or higher, auto-merge is triggered. Scores between 0.80 and 0.92 go to a manual review queue. Scores below 0.80 are treated as new entities.
Expressions like “Season 1,” “Season 3,” or “Season 5” can only be bound to a specific series if the series title or series_id appears in the text. Records that cannot be bound enter the review queue and are not directly written to the graph.
2.3 Attribute Standardization
Time is uniformly converted to ISO 8601 format, such as 1951-11-14T00:00:00Z. If only the year and month are available, the original precision is retained and marked with a precision field. Status is standardized into three enum values: ENDED, ONGOING, UNKNOWN. Null values are kept as null, not replaced with 0 or empty strings.
The following code is a simplified example; helper functions need to be implemented based on actual data sources.
ALLOWED_STATUS = {"ENDED", "ONGOING", "UNKNOWN"}def parse_and_clean(record: dict) -> dict:"""Input: {"source_id": str, "raw_text": str}Output: Standardized record. Uncertain fields are None, and written to review_items."""raw_text = record["raw_text"]review = []premiere = extract_date_with_regex(raw_text) # Returns ("1951-11-14", "day") or Noneif premiere is None:premiere_iso = Nonereview.append("premiere_date_missing")else:premiere_iso = convert_to_iso8601(premiere[0], precision=premiere[1])# Status keywords are only taken from the entry infobox, not the full text, to avoid misjudgment by historical descriptionsstatus_field = extract_infobox_field(raw_text, "status")if status_field == "ended":status = "ENDED"elif status_field == "ongoing":status = "ONGOING"else:status = "UNKNOWN"review.append("status_unknown")actor_ids = []for mention in extract_entities(raw_text, role="actor"):match = align_to_knowledge_base(mention) # Returns (person_id, score)if match.score >= 0.92:actor_ids.append(match.person_id)else:review.append(f"actor_needs_review:{mention}")return {"source_id": record["source_id"],"premiere_date": premiere_iso,"status": status,"actor_ids": actor_ids,"review_items": review,}
2.4 Common Errors and Handling Strategies
| Issue | Typical Manifestation | Handling Strategy | Rollback Method |
|---|---|---|---|
| Multilingual mixing | Chinese and English translated names side by side | Split by language, store English original name in alias table | Retain original text position, re-extract by source_id |
| Aliases | Abbreviations, old translations | Alias table maps many-to-one to person_id |
Delete incorrect mapping and re-align |
| Inconsistent time formats | “November 1951”, “1951.11.14” | Store according to precision field |
Save original string |
| Missing season or episode | Only series name, no season number | Write null and enter review queue |
Do not create season node |
| Duplicate entries | Same show appears in multiple entries | Deduplicate by series_id and source_id, keep latest fetched_at |
Revoke entire batch import by batch_id |
Each import must generate a batch_id. In case of issues, rolling back by batch is more reliable than modifying records one by one.
3. Graph Storage and Retrieval: How to Choose and Query?
Graph databases are suitable for highly interconnected data with deep query paths. It traverses along node adjacency relationships, and the overhead of multi-hop queries depends primarily on the number of neighbors near the starting point. In relational databases, intermediate results can expand rapidly during multi-table JOINs. The actual gap between the two should be tested with your own data, rather than relying on generic benchmarks.
When selecting a database, compare the following dimensions: query patterns (multi-hop traversal vs. aggregate statistics), data scale, consistency and backup capabilities, team skills, and operational costs. If the primary goal is generating full-table statistical reports, a relational database or columnar storage might be more appropriate.
Query Goal: Given an actor and a writer, list every series and season the actor appeared in, and list the episodes the writer wrote in those seasons.
The following Cypher places the writer condition inside the pattern match rather than in a WHERE clause. Placing the filter condition on an OPTIONAL MATCH would change the semantics when there are no matching results.
MATCH (actor:Person {person_id: $actorId})-[:ACTED_IN]->(season:Season)MATCH (series:Series)-[:HAS_SEASON]->(season)OPTIONAL MATCH (writer:Person {person_id: $writerId})-[:WROTE]->(ep:Episode)<-[:HAS_EPISODE]-(season)RETURN series.title AS series_title,season.season_number AS season_number,season.premiere_date AS premiere_date,collect(ep.title) AS episodesORDER BY series_title, season_numberSKIP $skip LIMIT $limit
Input parameters are actorId, writerId, skip, and limit, all passed as parameters without string concatenation to prevent injection. If the writer did not write any episodes in those seasons, the corresponding season will still be returned with an empty episodes list.
Example output (fictional data):
| series_title | season_number | premiere_date | episodes |
|---|---|---|---|
| Example Series A | 5 | 2020-03-01 | [“Episode 12: A Story”] |
Before going live, perform two checks. First, use PROFILE to confirm the query utilizes the index for the unique constraint without a full database scan. Second, set a transaction timeout in the driver layer (e.g., 5 seconds) and paginate the result set, limiting each page to 50 records.
4. Cloud-Native Architecture and Operations
The complete solution is divided into four layers, each requiring corresponding monitoring and recovery mechanisms.
4.1 Data Ingestion and Storage Layer
Raw encyclopedia entries and user behavior logs are ingested via message queues. Large files like posters and trailers are stored in object storage, while the graph database only saves file addresses and hash values. Object storage should have lifecycle rules configured, such as transitioning original files to infrequent access storage after 90 days. Cost estimation is calculated based on storage volume, request counts, and outbound traffic, with prices subject to the cloud provider’s latest pricing.
4.2 Data Processing Layer
Cleaning tasks run in containers and auto-scale based on queue backlog length. Each batch writes a batch_id to support batch-level rollbacks.
4.3 Knowledge Graph Service Layer
Cleaned data is imported into a managed graph database. The recommended backup strategy is a daily full backup, with hourly incremental backups if supported, and a recovery drill every quarter. Monitoring metrics and initial alert thresholds are as follows; formal thresholds should be adjusted after accumulating two weeks of baseline data.
| Metric | Description | Initial Alert Threshold |
|---|---|---|
| Query P95 Latency | Time taken for 95% of queries | Exceeds 500ms for 5 consecutive minutes |
| Write QPS | Write requests per second | Drops below 50% of baseline for 10 minutes (indicates import task anomaly) |
| Error Rate | Proportion of failed requests to total requests | Exceeds 1% for 5 minutes |
| Replication Lag | Time read replica falls behind primary | Exceeds 10 seconds (when read replicas are enabled) |
4.4 Application Service Layer
A unified query API provides full-text search, multi-hop graph queries, and graph-embedding-based recommendations for similar actors and series. The API features timeout, pagination, and rate limiting per caller. Recommendation results must record the generation time and model version for traceability and comparison.
5. Conclusion and Applicability Boundaries
Organizing TV participation text into a knowledge graph makes relationships between actors, seasons, episodes, and writers queryable. The keys are three things: clear entity and relationship definitions, verifiable unique keys and ownership constraints, and a cleaning process that retains source and batch information.
Applicability boundaries are as follows. Graph solutions offer significant benefits when the data scale is within tens of millions of nodes, queries are primarily multi-hop relationships, and real-time requirements are not stringent. If the requirement is only to generate statistical reports by field, a relational database is simpler. The team needs graph querying and data governance capabilities, and maintenance costs should be factored into the decision.
Regarding copyright and compliance: scraping and reusing encyclopedia entries and TV information must comply with the source site’s terms of service and copyright regulations. Every record should retain source_url and fetched_at for traceability and takedown handling. Cast and crew information involves personal data, and its use should comply with relevant personal information protection regulations, retaining only fields necessary for the business.
