Structured Entity Modeling and Retrieval for Character Data: From Text to Knowledge Graph

    This article presents a practical approach to converting unstructured natural-language descriptions of fictional characters into structured, queryable entity data. It covers entity recognition and field extraction using rule-based and model-based methods, a three-layer entity-relationship-attribute data model, entity deduplication and alignment, retrieval API design, and data quality governance. The methodology is illustrated with film and character examples and can be generalized to other domains such as products, organizations, and locations.

    Structured Entity Modeling and Retrieval for Character Data: From Text to Knowledge Graph

    1. Background: From Unstructured Descriptions to Structured Knowledge

    Internet content platforms contain vast amounts of entity information described in natural language. For example, a wiki-style page might describe a fictional character as follows: “Character X is a character from the film Y released in 1994, played by Actor Z. The film was written and directed by Director W, and also starred Actors A and B.” Such text is human-readable, but it poses three typical problems for machines:

    1. Ambiguous semantic boundaries: Character names, work titles, person names, and years are mixed in the same sentence, making it difficult for a program to extract each field’s value.
    2. Implied relationships: The relationships between character and work, work and actor, and actor and character are not explicitly expressed, making it impossible to directly support queries like “find all characters played by a given actor.”
    3. Redundancy and duplication: The same fact often appears multiple times in an entry (e.g., the character name is repeated in the title, body text, and character introduction), leading to inconsistencies during storage and updates.

    The common approach to solving these problems is: decompose natural-language entries into structured entity-attribute-relationship triples and manage them with a unified data model. This is a classic topic in knowledge base and entity data management.

    2. Entity Recognition and Field Extraction

    The first step in modeling is to define entity types. Taking film-related entries as an example, the following core entity types can be abstracted:

    • Character: A fictional person, with attributes such as name and appearance in a work.
    • Work: A film or series, with attributes such as release year, director, and genre.
    • Person: An actor or director, with attributes such as name and profession.

    The goal of field extraction is to map facts in text to predefined slots. Two common approaches are used in practice:

    2.1 Rule- and Template-Based Extraction

    This is suitable for sources with relatively fixed formats. For example, for sentences like “X is a character in the 1994 film Y, played by A,” a template can be written:

    1. import re
    2. pattern = r"(?P<char>\S+?)是(?P<year>\d{4})年电影《(?P<work>.+?)》中的角色,由(?P<actor>.+?)饰演"
    3. text = "某角色是1994年电影《某作品》中的角色,由某演员饰演"
    4. m = re.search(pattern, text)
    5. if m:
    6. record = m.groupdict()
    7. print(record)
    8. # {'char': '某角色', 'year': '1994', 'work': '某作品', 'actor': '某演员'}

    The advantage of rule-based methods is precision and interpretability; the disadvantage is sensitivity to sentence variations and limited coverage.

    2.2 Model-Based NER and Relation Extraction

    For texts with varied sentence structures, pre-trained language models are typically used for sequence labeling to identify entity spans such as person names, work titles, and time expressions. Then a relation classification model determines the semantic relationships between entities (e.g., “plays”, “directs”, “appears in”). This approach offers better generalization but requires labeled corpora and training resources. In engineering practice, a hybrid strategy is often adopted: high-frequency, fixed-format sources go through the rule-based pipeline, while long-tail texts go through the model-based pipeline. Finally, a unified confidence strategy merges the results.

    3. Data Model Design: Entity–Relationship–Attribute Three-Layer Structure

    After extraction, the storage model needs to be designed. A widely adopted solution is the three-layer structure of “entity – relationship – attribute”:

    1. Character entity:
    2. id: char_001
    3. name: Character X
    4. type: Character
    5. Work entity:
    6. id: work_001
    7. name: Work Y
    8. type: Film
    9. release_year: 1994
    10. Relations:
    11. (char_001) --[appears_in]--> (work_001)
    12. (person_001) --[plays]--> (char_001)
    13. (person_002) --[directs]--> (work_001)

    This design brings several significant benefits:

    1. Eliminates redundancy: The release year of a work is stored only once; character entries reference it via relationships, avoiding inconsistencies caused by multiple copies.
    2. Supports multi-dimensional queries: You can query “works for a character” or the reverse “all characters played by an actor”. Query patterns are determined by relationship direction, no extra denormalized tables needed.
    3. Easy to extend: Adding new entity types (e.g., “production company”, “award”) only requires extending the schema definition without breaking existing data.

    Regarding storage selection, graph storage is suitable for relationship-intensive scenarios, while relational databases with join tables are feasible for field-filtering and paginated list scenarios. Neither approach is inherently superior; the choice depends on query patterns and team expertise. For elastic hosting, common cloud databases and cloud-native middleware can support such workloads.

    4. Deduplication and Entity Alignment

    The same character or work may appear under different names (original, translated, abbreviation, etc.) across different sources. Without entity alignment, the knowledge base will contain many duplicate nodes for the same entity. The general processing pipeline includes:

    • Normalization: Unify case, remove whitespace, convert traditional to simplified Chinese, and standardize punctuation.
    • Candidate recall: Use edit distance, phonetic similarity, or vector similarity of names to find potentially duplicate entities.
    • Feature-based decision: Compute a matching confidence based on name similarity and attribute consistency (e.g., release year and director).
    • Manual review fallback: Samples with confidence in the gray zone enter a human review queue to avoid irreversible errors from incorrect merging.
    1. def similarity(a: dict, b: dict) -> float:
    2. score = 0.0
    3. if a["name"].strip() == b["name"].strip():
    4. score += 0.6
    5. if a.get("year") == b.get("year"):
    6. score += 0.3
    7. if a.get("director") == b.get("director"):
    8. score += 0.1
    9. return score # >= 0.8 auto-merge, 0.5~0.8 manual review

    5. Retrieval and API Design

    Once the knowledge base is built, it needs to be exposed for retrieval. A recommended API layering is:

    1. Exact lookup API: Retrieve details by entity ID or unique name for entry page rendering.
    2. Filter API: Combine filters on type, year, relationship, etc., for list and aggregation pages.
    3. Full-text search API: Build an inverted index on names and descriptions to support fuzzy search, typically using a general-purpose search engine service.
    4. Relationship traversal API: Support graph traversals such as “all characters in a work” or “all works of a person”.

    For performance, high-frequency entity detail lookups should use a cache layer. Full-text search and structured storage should be synchronized asynchronously via a message queue to ensure eventual consistency. Logging, monitoring, and alerting on slow queries and sync delays form a complete observability loop.

    6. Data Quality Assurance

    The long-term value of a knowledge base depends on data quality. The following mechanisms are recommended:

    • Ingestion validation: Check field types, value ranges, and required fields; reject invalid data.
    • Consistency checks: Periodically scan for dangling relationships (e.g., a character pointing to a non-existent work) and automatically repair or alert.
    • Version management: Keep a history of field changes to support rollback and audit.
    • Source traceability: Record the source and extraction confidence for each fact to facilitate issue localization and trustworthiness display.

    7. Conclusion

    Transforming natural-language entries into structured knowledge is essentially a five-step engineering pipeline: extraction – modeling – alignment – retrieval – governance. This article uses character entities as an example to present a complete path: first, extract fields using rule-based and model-based methods; second, organize storage with the entity-relationship-attribute model; third, eliminate duplicates via entity alignment; and finally, provide layered APIs and quality mechanisms to ensure usability and trustworthiness. This methodology is not limited to the film domain; it applies equally to structured management of other entity types such as products, organizations, and locations, and serves as a common foundation for building high-quality industry knowledge bases.