Building an Entertainment Knowledge Graph from Filmography Text: Ontology Design, Data Cleaning, and Neo4j
This article walks through how to turn scattered filmography text records into a knowledge graph, using fictional actor data. It covers ontology design, field extraction and date normalization, loading data into Neo4j, common queries, and troubleshooting tips. All people, works, and characters mentioned are fictional, and no real personal information is involved.
Introduction: Why Filmography Text Is Hard to Use Directly
In the film and television industry, actor filmographies usually exist as free text. A single bio line may contain a movie title, release year, character name, and director all at once, in inconsistent formats. Humans can read this easily, but programs struggle to answer questions like “Which actors has a given director worked with?” or “In which works does a certain character appear?”
A knowledge graph is a data organization approach well suited to this kind of problem. It breaks data into entities and relationships. Entities include people and works, while relationships describe the connections between them, such as “actor performed in a work” or “director directed a work.” Graph databases can traverse these relationships quickly, making them ideal for multi-hop queries and path analysis.
The goal of this article is to walk you through the entire process: design the ontology first, extract fields from text, clean the data, load it into a graph database, and finally validate the results with queries. The examples use Neo4j 5.x and Python 3.10 or later. You can copy and run the code directly, then adapt it to your own data.
Note that the actor “Lena Ashford,” the director “Marcus Vale,” and the works The Glass Lantern and Harbor Lights in this article are all fictional. Using fictional data avoids any personal information exposure and keeps the examples self-consistent, making it easy to verify the output.
1. Ontology Design and Data Modeling
The ontology defines which entities exist in the graph, what properties each entity has, and which relationships connect them. An entertainment scenario typically requires three entity types and two relationship types.
Entity Types
- Person: Covers both actors and directors. Core properties are
person_id,name, andprofession. Theperson_idis a unique internal identifier used to distinguish different people who share the same name. - Work: Covers movies and TV shows. Core properties are
work_id,title,work_type, andrelease_date.work_typeis eitherMovieorTVShow, andrelease_datemeans the theatrical release date for movies and the first air date for TV shows. Using a unified field name means time-based sorting queries don’t need to distinguish between work types.
Relationship Types
- ACTED_IN: Points from a Person to a Work, indicating that an actor performed in that work. The character name is stored as an edge property
character_name. For TV shows, the episode countepisodesand the year rangeyearsare also stored on this edge. - DIRECTED: Points from a Person to a Work, indicating that a director directed that work.
There is a design trade-off worth explaining here. An earlier approach modeled characters as separate Role nodes, connected to actors via a PLAYED_ROLE relationship. This works well when characters need to be reused across multiple works, or when you need to query characters independently. In this article’s example, a character is only meaningful within a single work, so storing it as a property on the ACTED_IN edge is simpler and avoids the inconsistency of storing the character name in both an edge and a node. If you later need cross-work character analysis, you can split out a Role node then.
With this design, a linear filmography record becomes a network graph. Actors connect to works through ACTED_IN, directors connect to the same works through DIRECTED, and collaborations between two people can be found directly through paths.
2. Data Extraction and Cleaning
1. Prepare the Raw Data
Assume the raw filmography comes from an internal spreadsheet or a scraped structured page, with one performance record per line in this format:
Release date:2009-11-15;Title:The Glass Lantern;Character:Blue Fairy;Director:Marcus Vale
This is semi-structured data: fields are separated by semicolons, and keys are separated from values by colons. Before parsing, confirm that the separators never appear inside values — for example, the colon in a time like 10:30 would break the parsing rule.
2. Parse Key-Value Pairs
The following function splits one line of text into a dictionary:
import redef parse_record(line: str) -> dict[str, str]:pairs = re.findall(r"([^:;]+):([^;]+)", line)return {key.strip(): value.strip() for key, value in pairs}record = parse_record("Release date:2009-11-15;Title:The Glass Lantern;Character:Blue Fairy;Director:Marcus Vale")print(record["Title"]) # The Glass Lantern
3. Normalize Date Formats
Even within the same dataset, dates may be written as 2009-11-15, 2009/11/5, 2009.11.05, and so on. Normalize them to the ISO 8601 YYYY-MM-DD format before loading, otherwise string-based sorting will produce incorrect results.
from datetime import datetimeDATE_FORMATS = ["%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d", "%Y-%m-%d-alt"]def normalize_date(raw: str) -> str | None:raw = raw.strip()for fmt in DATE_FORMATS:try:return datetime.strptime(raw, fmt).date().isoformat()except ValueError:continuereturn None # Return None for unrecognized dates; flag for manual reviewprint(normalize_date("2009/11/5")) # 2009-11-05print(normalize_date("not a date")) # None
strptime accepts both zero-padded and non-padded values, so 2009-9-6 and 2009-09-06 produce the same result.
4. Handle TV Episode Information
TV filmographies often look like “Character Name (episode count, year range)”, for example Nora Hale (4 episodes, 2012-2013). A regular expression can split this into three fields:
EPISODE_PATTERN = re.compile(r"^(?P<role>.+?) \((?P<episodes>\d+) episodes?, (?P<years>\d{4}-\d{4})\)$")match = EPISODE_PATTERN.match("Nora Hale (4 episodes, 2012-2013)")if match:print(match.group("role"), match.group("episodes"), match.group("years"))# Nora Hale 4 2012-2013
After splitting, store the character name in character_name, the episode count in episodes, and the year range in years — all three attached to the ACTED_IN edge.
5. Entity Disambiguation
People sharing the same name are common in the film industry. Matching by name alone can easily merge two different people into one node. The recommended approach is to maintain a person registry that assigns a unique person_id to each individual. During import, look up by person_id first, and only create a new node when no match is found. If external sources provide birth year, official identifiers, or similar information, that can also serve as supporting evidence for disambiguation.
