Build a Knowledge Graph for Legacy Apps
In this article
This guide walks you through building a knowledge graph for a legacy application, turning years of tangled data and implicit relationships into a queryable, interconnected structure. You'll learn a practical, incremental approach that works with existing databases and codebases, without requiring a full rewrite. By the end, you'll have a clear roadmap from identifying key entities to loading and validating your graph.
What You'll Need
- Access to the legacy application's database schema (tables, columns, foreign keys) or API documentation.
- A basic understanding of graph concepts: nodes (entities), edges (relationships), and properties.
- A graph database or triplestore (e.g., Neo4j, Amazon Neptune, or an RDF store like Apache Jena). Choose one that fits your team's skills and infrastructure.
- An ETL (Extract, Transform, Load) tool or scripting language (Python, Java, etc.) to extract data from the legacy system.
- Optional: an ontology or schema definition tool like Protégé if you want to formalize your graph's structure.
Step-by-Step
- Identify core entities and relationships. Start by listing the main nouns in your legacy domain (e.g., Customer, Order, Product). Look at the database tables and foreign keys to see how they relate. For each entity, note the key attributes (e.g., customer ID, order date). Also identify any implicit relationships—for example, a "manager" might be another employee, not a separate table.
- Design a lightweight ontology or schema. Define node labels (types) and edge types. Keep it simple: you can always refine later. For each node type, list the properties you want to include. For edges, define the direction and any properties (e.g., "purchased_on" with a date). Use a standard like RDF if you need interoperability, but a property graph model is often easier for legacy data.
- Map legacy data to your graph model. Create a mapping document that shows how each table column becomes a node property or an edge. For example,
orders.customer_idbecomes an edgeCustomer-[:PLACED]->Order. Handle data types: dates become strings or timestamps, foreign keys become relationships, and lookup tables often become node properties or separate nodes. - Extract data from the legacy system. Write a script or use an ETL tool to pull data in batches. Start with a small subset (e.g., one month of orders) to test your mapping. Ensure you preserve primary keys as unique IDs in the graph to avoid duplicates. If the legacy system has soft-deleted records, decide whether to include them (usually exclude, but keep a flag).
- Transform and clean the data. During extraction, you'll need to clean inconsistencies: trim whitespace, standardize date formats, resolve NULLs (skip or use a placeholder), and handle duplicate records. If two tables reference the same customer with slightly different names, decide on a canonical form. This step is critical—garbage in, garbage out.
- Load data into the graph database. Use the database's bulk import tools (e.g., Neo4j's
neo4j-admin importor CypherLOAD CSV) for efficiency. For RDF stores, use SPARQL INSERT or a bulk loader. Start with nodes first, then edges, to avoid missing references. Set up constraints or indexes on unique IDs to speed up lookups. - Validate the graph. Run sample queries to check that relationships point to existing nodes. Compare counts: the number of orders in the graph should match the legacy database. Use graph algorithms (e.g., degree distribution) to spot anomalies like isolated nodes or overly dense clusters that might indicate mapping errors.
- Iterate and refine. Share the graph with a few developers or analysts to get feedback. They'll likely spot missing relationships or unnecessary properties. Adjust your ontology and re-run the ETL. This is normal—knowledge graphs are living artifacts.
- Document and maintain. Write down the mapping rules, the ontology version, and the extraction date. Set up a regular refresh schedule (daily, weekly) if the legacy data changes. Consider automating the ETL pipeline with a scheduler like cron or Airflow.
Common Mistakes
- Overcomplicating the ontology—creating dozens of node types and edge types that mirror every table, making the graph hard to use.
- Ignoring data quality—not cleaning duplicates or NULLs, leading to confusing query results.
- Forgetting to preserve history—if the legacy system overwrites records, you might lose important temporal relationships.
- Skipping validation—not comparing counts or running test queries, so errors go unnoticed until later.
- Treating the graph as a one-time project—without a refresh plan, the graph quickly becomes stale.
Tips
- Start small: pick a single business process (e.g., customer orders) and build a proof of concept before scaling.
- Involve domain experts early to validate relationships—they know the business rules that aren't in the code.
- Use clear, consistent naming conventions for node labels and edge types (e.g.,
Customernotcust). - Leverage existing foreign keys as a starting point for edges, but also look for relationships in application code (e.g., joins in queries).
- Consider using a graph visualization tool to explore the graph and spot issues visually.
Troubleshooting
Missing nodes or edges after load. Check your ETL logs for errors like null foreign keys. Ensure you load nodes before edges. If using a property graph, verify that the IDs match exactly (watch for type mismatches like string vs. integer).
Queries are slow. Add indexes on properties you filter by, especially unique IDs. For Neo4j, create constraints on id properties. For RDF, consider using a native triplestore that supports efficient joins.
Duplicate nodes. This often happens when the legacy system has multiple records for the same real-world entity. Use a deduplication step based on business keys (e.g., email) or use graph algorithms like connected components to merge duplicates manually.
Data types don't match. For example, dates stored as strings in legacy but you need date comparisons. Use the graph database's date functions during transformation, or store as ISO 8601 strings and parse in queries.
The graph doesn't reflect business logic. You may have missed implicit relationships. Review application code for joins and business rules. For instance, a "parent" relationship might be encoded in a manager_id column—make it an explicit edge.
Frequently Asked Questions
Q: Do I need to migrate the entire legacy database?
A: No. Start with a subset that answers your most important questions. You can expand later.
Q: Can I build a knowledge graph without a graph database?
A: Yes, you can use a relational database with recursive queries, but it's less efficient and harder to maintain. A graph database is recommended for real-world use.
Q: How do I handle legacy data that is inconsistent or duplicated?
A: Clean it during the ETL process. Use business rules to pick canonical values, and keep a log of changes for transparency.
Q: What if my legacy application has no documentation?
A: Reverse-engineer the schema by examining the database and code. Look at ORM mappings or SQL queries to infer relationships.
Q: How often should I refresh the knowledge graph?
A: It depends on how often the legacy data changes. Start with a nightly batch, then adjust based on user needs.
Q: Is it worth using RDF vs. property graph?
A: RDF is better for interoperability and semantic reasoning, while property graphs are simpler and more performant for most applications. Choose based on your team's expertise and use case.