AI-Driven Knowledge Graph Schema Discovery: Concept and Implementation
A knowledge graph structures data into entities (things like people, product, or event) and relationships (how these entities are connected). Instead of isolated tables or documents, a KG forms an interconnected web of knowledge, making it easier to derive insights, answer complex queries, and enhance AI-driven applications. But before building one, we first need to define its schema — a blueprint that outlines what entities, properties, and relationships exist in the graph.
In this blog, we will explore the core concept of knowledge graphs, the role of knowledge graph schemas, and how AI can be leveraged for schema discovery. We will see how can we storage and manage the discovered schema. All this we will understand using a sample use case. Finally, we will discuss the architecture for automating knowledge graph schema discovery. In the next blog, we will focus on building Knowledge graph using the schema we derive here.
Introduction to Knowledge Graph
The core concept of knowledge graph are three things —
- Entity: A distinct object in the domain. Each entity has multiple node instances.
- Property: Attributes that describe an entity. One attribute for each entity acts as the key property which distinguishes the node instances of an entity.
- Relationship: A connection between two entities represented by edge.
Let’s understand using an example. See the below diagram-
In the above diagram we can observe the following :
- There are three nodes with labels — John, Rita and Pen. John → Pen and Rita → Pen are connected by the “Purchased” relationship.
- Here, the nodes with labels John and Rita are instances of PERSON entity. Whereas, the node with label Pen is instance of PRODUCT entity.
- PERSON entity properties:
name,mobile_no,address. PRODUCT entity properties:Product_Name,Cost. Each node of type PERSON entity has its own attribute values for the properties. - In this example, the key property which acts as labels of node instances are
namefor PERSON entity andProduct_Namefor Product entity. The key property value should be unique to distinguish one instance from other. - The “Purchased” relationship (edge) can also have properties, such as Quantity. If John bought 2 pens and Rita bought 3, the edge can store
quantity:2for John andquantity:3for Rita. - PERSON — Purchased →PRODUCT is the domain relationship established which can be used to answer queries like “Who purchased the pen?“.
In the example above, we have a simple knowledge graph with two entities (PERSON and PRODUCT) and one relationship (Purchased).
What is Knowledge Graph Schema?
Schema discovery is the process of identifying entities, properties, and relationships from the data, helping us understand its structure and connections. To load data into a knowledge graph, we not only need to identify entities, properties, and relationships but also determine where to source the data for each property and how to map relationships from the source data. This structured definition forms the schema, which can be then further used for data ingestion into the knowledge graph.
The data used to build knowledge graph can be structured data (Database tables, CSV files) or unstructured data (text, images, videos).
In this blog series, we will focus on building Knowledge Graphs from structured data sources.
Knowledge Graph Schema Discovery
Using the given data and domain expertise, we analyse the data to identify key components for Knowledge Graph construction. Throughout this process, it is crucial to consider the end-use case and domain knowledge to ensure the schema accurately represents meaningful entities, properties, and relationships, enabling business effective and insightful Knowledge Graph.
However, manually performing this analysis can be time-consuming and error-prone, especially for large datasets. This is where AI can automate and streamline schema discovery.
Sample Use case:
Let’s take a simple example to understand more. Below there are three tables maintained in a hospital database :
We have saved all these tables as CSV files. Let’s step by step implement the code :
utils/llm_initializer.py— To initialise and interact with a Large Language Model (LLM) provider. We have used Open AI for this example.
from openai import OpenAI
class LLMInitializer:
# A class to initialize and interact with a Large Language Model (LLM) provider.
def __init__(self):
self.llm_provider = "OpenAI"
self.llm_name = "gpt-4o"
self.client = self.intialize_client()
def intialize_client(self):
# Initializes and returns the client object for the specified LLM provider.
if self.llm_provider == "OpenAI":
return OpenAI()
else:
raise ValueError("LLM provider not supported")
def get_response(self, system_prompt, user_prompt, response_format_pydantic_model):
# Sends a prompt to the LLM and returns the structured response.
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
]
completion = self.client.beta.chat.completions.parse(
model=self.llm_name,
messages=messages,
response_format = response_format_pydantic_model,
temperature=0.2
)
return completion.choices[0].message.parsed
from openai import OpenAI
class LLMInitializer:
# A class to initialize and interact with a Large Language Model (LLM) provider.
def __init__(self):
self.llm_provider = "OpenAI"
self.llm_name = "gpt-4o"
self.client = self.intialize_client()
def intialize_client(self):
# Initializes and returns the client object for the specified LLM provider.
if self.llm_provider == "OpenAI":
return OpenAI()
else:
raise ValueError("LLM provider not supported")
def get_response(self, system_prompt, user_prompt, response_format_pydantic_model):
# Sends a prompt to the LLM and returns the structured response.
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
]
completion = self.client.beta.chat.completions.parse(
model=self.llm_name,
messages=messages,
response_format = response_format_pydantic_model,
temperature=0.2
)
return completion.choices[0].message.parsed
models.py– Defines the Pydantic models for entity and relationship creation configurations.
from pydantic import BaseModel
from typing import List, Optional
class EntityProperty(BaseModel):
property: str
is_key_property: bool
mapping_table: str
mapping_column: str
class Entity(BaseModel):
entity: str
properties: List[EntityProperty]
class EntityConfig(BaseModel):
entities: List[Entity]
class Relationship(BaseModel):
source_entity: str
target_entity: str
relationship: str
source_property: str
target_property: str
source_mapping_table: str
target_mapping_table: str
source_mapping_column: str
target_mapping_column: str
joining_condition: Optional[str]
class RelationshipConfig(BaseModel):
relationships: List[Relationship]
from pydantic import BaseModel
from typing import List, Optional
class EntityProperty(BaseModel):
property: str
is_key_property: bool
mapping_table: str
mapping_column: str
class Entity(BaseModel):
entity: str
properties: List[EntityProperty]
class EntityConfig(BaseModel):
entities: List[Entity]
class Relationship(BaseModel):
source_entity: str
target_entity: str
relationship: str
source_property: str
target_property: str
source_mapping_table: str
target_mapping_table: str
source_mapping_column: str
target_mapping_column: str
joining_condition: Optional[str]
class RelationshipConfig(BaseModel):
relationships: List[Relationship]
utils/table_schema_extractor.py–To retrieve the schema of existing tables from the data source. The implementation can be customised based on the specific database or storage system.
str:
schema_list = []
for file_name in os.listdir(self.data_folder_path):
if file_name.endswith(self.file_format):
table_name = file_name.split(".")[0]
schema_list.append({table_name: self.load_schema(file_name)})
return json.dumps(schema_list)
def load_schema(self, file_name: str) -> dict:
file_path = os.path.join(self.data_folder_path, file_name)
df = pd.read_csv(file_path)
return df.columns.to_list()” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
import os
import pandas as pd
import json
class DataSchemaLoader:
def __init__(self):
self.data_folder_path = "../data"
self.file_format = "csv"
def load_schemas(self) -> str:
schema_list = []
for file_name in os.listdir(self.data_folder_path):
if file_name.endswith(self.file_format):
table_name = file_name.split(".")[0]
schema_list.append({table_name: self.load_schema(file_name)})
return json.dumps(schema_list)
def load_schema(self, file_name: str) -> dict:
file_path = os.path.join(self.data_folder_path, file_name)
df = pd.read_csv(file_path)
return df.columns.to_list()
import os
import pandas as pd
import json
class DataSchemaLoader:
def __init__(self):
self.data_folder_path = "../data"
self.file_format = "csv"
def load_schemas(self) -> str:
schema_list = []
for file_name in os.listdir(self.data_folder_path):
if file_name.endswith(self.file_format):
table_name = file_name.split(".")[0]
schema_list.append({table_name: self.load_schema(file_name)})
return json.dumps(schema_list)
def load_schema(self, file_name: str) -> dict:
file_path = os.path.join(self.data_folder_path, file_name)
df = pd.read_csv(file_path)
return df.columns.to_list()
prompts.py– Contains carefully designed system prompts to guide the LLM in discovering entities and relationships within the data. We can refine them more for better results.
<button data-code="ENTITY_DISCOVERY_PROMPT = """
You are an expert knowledge graph schema designer with deep expertise in the
healthcare domain. You have extensive experience in extracting entities and
their properties from structured data to design efficient and meaningful
knowledge graphs. Your task is to analyze the provided table schemas and
discover key entities along with their relevant properties, ensuring an
optimal structure for knowledge representation to be used in a hospital
chatbot.
Given a set of tables schemas, discover the entities and their properties
that are most relevant for a hospital chatbot.
Instructions:
1. Identify distinct entities from the given table(s).
An entity represents a unique concept (e.g., Product, Customer, Order).
2. Assign relevant properties to each entity that define it.
3. Use the exact column name as the property name (do not rename columns).
4. Each entity must have exactly one key property that uniquely identifies it.
5. An entity can be derived from multiple tables, and a table can contain
multiple entities.
6. Ignore irrelevant columns that do not contribute meaningfully to an
entity's definition.
7. Don't add same property to more than one entity.
Output:
Return the entity creation config which contains the following fields for
each entry:
1. entity
2. property
3. is_key_property
4. source_table
5. source_column
Example:
"""
RELATIONSHIP_DISCOVERT_PROMPT = """
As an experienced data modeler specializing in knowledge graph design,
you have deep expertise in structuring data for hospital systems.
With extensive domain knowledge, you understand the frequently
asked questions and how data should be interconnected for efficient retrieval.
Your task is to identify meaningful relationships between entities
based on the provided table schemas and entity configurations.
You ensure that relationships in the graph database are structured,
relevant, and non-redundant, avoiding generic or unnecessary links.
Given table schemas and entity creation configurations, discover the
relationships between the entities to establish a well-defined knowledge
graph to be used for hospital chatbot.
How to Discover a Relationship?
1. Create a relationship only if there is a meaningful connection according
to the domain.
2. Avoid generic or vague relationships like "RELATED_TO" or "HAS."
3. Ensure that relationships improve query efficiency for the hospital chatbot
by linking entities that users are likely to ask about.
4. Derive relationships from the same table if the key properties of the
entities are present as columns in that table.
5. If key properties of connecting entities exist in different tables, check if a common column can be used for joining and establishing the relationship.
6. Ensure proper relationship direction – e.g., if defining "Placed" between
Customer and Order, Customer should be the source entity, and Order
should be the target entity (not vice versa).
BEWARE OF THE RELATIONSHIP DIRECTION.
7. THE RELATIONSHIPS YOU IDENTIFY SHOULD BE MEANINGUL AND USEFUL FOR A
HOSPITAL CHATBOT. THINK OF WHAT CAN BE THE MOST ASKED QUESTIONS IN A HOSPITAL
AND HOW THE RELATIONSHIPS CAN HELP IN ANSWERING THEM. BUILD RELATIONSHIPS
WHICH ARE FORMED BOTH USING SAME TABLE AND DIFFERENT TABLES.
Output:
Return the relationship creation config which contains the following fields for each entry:
1. Source_Entity
2. Relationship
3. Target_Entity
4. Source_Property
5. Target_Property
6. Source_Table
7. Target_Table
8. Source_Column
9. Target_Column
10. Joining_Condition (if applicable)
Example:
"""” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
ENTITY_DISCOVERY_PROMPT = """
You are an expert knowledge graph schema designer with deep expertise in the
healthcare domain. You have extensive experience in extracting entities and
their properties from structured data to design efficient and meaningful
knowledge graphs. Your task is to analyze the provided table schemas and
discover key entities along with their relevant properties, ensuring an
optimal structure for knowledge representation to be used in a hospital
chatbot.
Given a set of tables schemas, discover the entities and their properties
that are most relevant for a hospital chatbot.
Instructions:
1. Identify distinct entities from the given table(s).
An entity represents a unique concept (e.g., Product, Customer, Order).
2. Assign relevant properties to each entity that define it.
3. Use the exact column name as the property name (do not rename columns).
4. Each entity must have exactly one key property that uniquely identifies it.
5. An entity can be derived from multiple tables, and a table can contain
multiple entities.
6. Ignore irrelevant columns that do not contribute meaningfully to an
entity's definition.
7. Don't add same property to more than one entity.
Output:
Return the entity creation config which contains the following fields for
each entry:
1. entity
2. property
3. is_key_property
4. source_table
5. source_column
Example:
<placeholder to add example>
"""
RELATIONSHIP_DISCOVERT_PROMPT = """
As an experienced data modeler specializing in knowledge graph design,
you have deep expertise in structuring data for hospital systems.
With extensive domain knowledge, you understand the frequently
asked questions and how data should be interconnected for efficient retrieval.
Your task is to identify meaningful relationships between entities
based on the provided table schemas and entity configurations.
You ensure that relationships in the graph database are structured,
relevant, and non-redundant, avoiding generic or unnecessary links.
Given table schemas and entity creation configurations, discover the
relationships between the entities to establish a well-defined knowledge
graph to be used for hospital chatbot.
How to Discover a Relationship?
1. Create a relationship only if there is a meaningful connection according
to the domain.
2. Avoid generic or vague relationships like "RELATED_TO" or "HAS."
3. Ensure that relationships improve query efficiency for the hospital chatbot
by linking entities that users are likely to ask about.
4. Derive relationships from the same table if the key properties of the
entities are present as columns in that table.
5. If key properties of connecting entities exist in different tables, check if a common column can be used for joining and establishing the relationship.
6. Ensure proper relationship direction - e.g., if defining "Placed" between
Customer and Order, Customer should be the source entity, and Order
should be the target entity (not vice versa).
BEWARE OF THE RELATIONSHIP DIRECTION.
7. THE RELATIONSHIPS YOU IDENTIFY SHOULD BE MEANINGUL AND USEFUL FOR A
HOSPITAL CHATBOT. THINK OF WHAT CAN BE THE MOST ASKED QUESTIONS IN A HOSPITAL
AND HOW THE RELATIONSHIPS CAN HELP IN ANSWERING THEM. BUILD RELATIONSHIPS
WHICH ARE FORMED BOTH USING SAME TABLE AND DIFFERENT TABLES.
Output:
Return the relationship creation config which contains the following fields for each entry:
1. Source_Entity
2. Relationship
3. Target_Entity
4. Source_Property
5. Target_Property
6. Source_Table
7. Target_Table
8. Source_Column
9. Target_Column
10. Joining_Condition (if applicable)
Example:
<placeholder to add example>
"""
ENTITY_DISCOVERY_PROMPT = """
You are an expert knowledge graph schema designer with deep expertise in the
healthcare domain. You have extensive experience in extracting entities and
their properties from structured data to design efficient and meaningful
knowledge graphs. Your task is to analyze the provided table schemas and
discover key entities along with their relevant properties, ensuring an
optimal structure for knowledge representation to be used in a hospital
chatbot.
Given a set of tables schemas, discover the entities and their properties
that are most relevant for a hospital chatbot.
Instructions:
1. Identify distinct entities from the given table(s).
An entity represents a unique concept (e.g., Product, Customer, Order).
2. Assign relevant properties to each entity that define it.
3. Use the exact column name as the property name (do not rename columns).
4. Each entity must have exactly one key property that uniquely identifies it.
5. An entity can be derived from multiple tables, and a table can contain
multiple entities.
6. Ignore irrelevant columns that do not contribute meaningfully to an
entity's definition.
7. Don't add same property to more than one entity.
Output:
Return the entity creation config which contains the following fields for
each entry:
1. entity
2. property
3. is_key_property
4. source_table
5. source_column
Example:
<placeholder to add example>
"""
RELATIONSHIP_DISCOVERT_PROMPT = """
As an experienced data modeler specializing in knowledge graph design,
you have deep expertise in structuring data for hospital systems.
With extensive domain knowledge, you understand the frequently
asked questions and how data should be interconnected for efficient retrieval.
Your task is to identify meaningful relationships between entities
based on the provided table schemas and entity configurations.
You ensure that relationships in the graph database are structured,
relevant, and non-redundant, avoiding generic or unnecessary links.
Given table schemas and entity creation configurations, discover the
relationships between the entities to establish a well-defined knowledge
graph to be used for hospital chatbot.
How to Discover a Relationship?
1. Create a relationship only if there is a meaningful connection according
to the domain.
2. Avoid generic or vague relationships like "RELATED_TO" or "HAS."
3. Ensure that relationships improve query efficiency for the hospital chatbot
by linking entities that users are likely to ask about.
4. Derive relationships from the same table if the key properties of the
entities are present as columns in that table.
5. If key properties of connecting entities exist in different tables, check if a common column can be used for joining and establishing the relationship.
6. Ensure proper relationship direction - e.g., if defining "Placed" between
Customer and Order, Customer should be the source entity, and Order
should be the target entity (not vice versa).
BEWARE OF THE RELATIONSHIP DIRECTION.
7. THE RELATIONSHIPS YOU IDENTIFY SHOULD BE MEANINGUL AND USEFUL FOR A
HOSPITAL CHATBOT. THINK OF WHAT CAN BE THE MOST ASKED QUESTIONS IN A HOSPITAL
AND HOW THE RELATIONSHIPS CAN HELP IN ANSWERING THEM. BUILD RELATIONSHIPS
WHICH ARE FORMED BOTH USING SAME TABLE AND DIFFERENT TABLES.
Output:
Return the relationship creation config which contains the following fields for each entry:
1. Source_Entity
2. Relationship
3. Target_Entity
4. Source_Property
5. Target_Property
6. Source_Table
7. Target_Table
8. Source_Column
9. Target_Column
10. Joining_Condition (if applicable)
Example:
<placeholder to add example>
"""
knowledge_graph_schema.py— Uses the prompts to calls the LLM to generate entity and relationship configurations automatically.
EntityConfig:
user_prompt = "The following are the table schemas extracted from the data source: n" + self.table_schema_list + "nPlease provide the entity creation config based on the table schemas."
response = self.llm_intializer.get_response(
system_prompt=ENTITY_DISCOVERY_PROMPT,
user_prompt=user_prompt,
response_format_pydantic_model=EntityConfig
)
return response
def generate_relationship_schema(self,
entity_config : EntityConfig
) -> RelationshipConfig:
entity_config_str = entity_config.model_dump_json()
user_prompt = "The following are the table schemas extracted from the data source: n" + self.table_schema_list + "n. The following are the entity creation configurations: n" + entity_config_str + "nPlease provide the relationship discovery config based on the table schemas and entity creation configurations."
response = self.llm_intializer.get_response(
system_prompt=RELATIONSHIP_DISCOVERT_PROMPT,
user_prompt=user_prompt,
response_format_pydantic_model=RelationshipConfig
)
return response” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
from utils.models import EntityConfig, RelationshipConfig
from utils.llm_initializer import LLMInitializer
from prompts import ENTITY_DISCOVERY_PROMPT, RELATIONSHIP_DISCOVERT_PROMPT
class KnowledgeGraphSchemaCreator:
def __init__(self, table_schema_list : str):
self.table_schema_list = table_schema_list
self.llm_intializer = LLMInitializer()
def generate_entity_config(self) -> EntityConfig:
user_prompt = "The following are the table schemas extracted from the data source: n" + self.table_schema_list + "nPlease provide the entity creation config based on the table schemas."
response = self.llm_intializer.get_response(
system_prompt=ENTITY_DISCOVERY_PROMPT,
user_prompt=user_prompt,
response_format_pydantic_model=EntityConfig
)
return response
def generate_relationship_schema(self,
entity_config : EntityConfig
) -> RelationshipConfig:
entity_config_str = entity_config.model_dump_json()
user_prompt = "The following are the table schemas extracted from the data source: n" + self.table_schema_list + "n. The following are the entity creation configurations: n" + entity_config_str + "nPlease provide the relationship discovery config based on the table schemas and entity creation configurations."
response = self.llm_intializer.get_response(
system_prompt=RELATIONSHIP_DISCOVERT_PROMPT,
user_prompt=user_prompt,
response_format_pydantic_model=RelationshipConfig
)
return response
from utils.models import EntityConfig, RelationshipConfig
from utils.llm_initializer import LLMInitializer
from prompts import ENTITY_DISCOVERY_PROMPT, RELATIONSHIP_DISCOVERT_PROMPT
class KnowledgeGraphSchemaCreator:
def __init__(self, table_schema_list : str):
self.table_schema_list = table_schema_list
self.llm_intializer = LLMInitializer()
def generate_entity_config(self) -> EntityConfig:
user_prompt = "The following are the table schemas extracted from the data source: n" + self.table_schema_list + "nPlease provide the entity creation config based on the table schemas."
response = self.llm_intializer.get_response(
system_prompt=ENTITY_DISCOVERY_PROMPT,
user_prompt=user_prompt,
response_format_pydantic_model=EntityConfig
)
return response
def generate_relationship_schema(self,
entity_config : EntityConfig
) -> RelationshipConfig:
entity_config_str = entity_config.model_dump_json()
user_prompt = "The following are the table schemas extracted from the data source: n" + self.table_schema_list + "n. The following are the entity creation configurations: n" + entity_config_str + "nPlease provide the relationship discovery config based on the table schemas and entity creation configurations."
response = self.llm_intializer.get_response(
system_prompt=RELATIONSHIP_DISCOVERT_PROMPT,
user_prompt=user_prompt,
response_format_pydantic_model=RelationshipConfig
)
return response
main.py– The entry point that orchestrates the process.
from knowledge_graph_schema import KnowledgeGraphSchemaCreator
from utils.table_schema_extractor import DataSchemaLoader
from dotenv import load_dotenv
load_dotenv()
data_schema_loader = DataSchemaLoader()
table_schema_list = data_schema_loader.load_schemas()
knowledge_graph_schema = KnowledgeGraphSchemaCreator(table_schema_list)
entity_config = knowledge_graph_schema.generate_entity_config()
relationship_config = knowledge_graph_schema.generate_relationship_schema(entity_config)
# write some print statements to parse the Pydnantic models...
from knowledge_graph_schema import KnowledgeGraphSchemaCreator
from utils.table_schema_extractor import DataSchemaLoader
from dotenv import load_dotenv
load_dotenv()
data_schema_loader = DataSchemaLoader()
table_schema_list = data_schema_loader.load_schemas()
knowledge_graph_schema = KnowledgeGraphSchemaCreator(table_schema_list)
entity_config = knowledge_graph_schema.generate_entity_config()
relationship_config = knowledge_graph_schema.generate_relationship_schema(entity_config)
# write some print statements to parse the Pydnantic models...
- Create
.envfile to add yourOPENAI_API_KEY. Also, below is therequirements.txtfor this —
openai==1.60.2
python-dotenv==1.0.1
pandas==2.2.3
openai==1.60.2
python-dotenv==1.0.1
pandas==2.2.3
After installing the packages, its time to run and see the results. Open your terminal and run using python main.py . Below is the response returned :
We can see how LLM can help to extract entities, properties and relationships along with their mappings in a meaningful way for the given domain use case. It simplifies complex data modelling tasks, making the process more efficient and accessible. In real world we can have multiple tables, and AI can help us save lot of time and effort in schema discovery.
Storing and Managing Knowledge Graph Schema —
The derived schema can be stored as configuration files (CSV/JSON/YAML) which can be further used for loading data to create knowledge graph. The CSV config files after creation should look like below :
A python script can be written to generate these config files using the entity creation and relationship creation Pydantic models to automate this step.
However, a more powerful approach is to store it as a graph (metagraph) within the knowledge graph itself.
A schema as a graph represents a graph where entities, their properties, and relationships are modelled as connected nodes, making it easier to visualise, query, and evolve the data structure.
Below is the metagraph for the above example created in Neo4j.
In the above metagraph we can observe :
- ENTITY, PROPERTY, and RELATIONSHIP nodes are created. Blue represents entities, orange represents properties, and green represents relationships.
- Each ENTITY node has a
Nameattribute indicating the entity it represents, and similarly, for PROPERTY and RELATIONSHIP nodes which specifies the property name and relationship type they represent. - ENTITY nodes are linked to PROPERTY nodes via
HAS_PROPERTYedges, which store attributes —Is_Key_Property,Source_Table, andSource_Column. - RELATIONSHIP nodes connect ENTITY nodes using
CONNECTS_FROMandCONNECTS_TOedges. TheCONNECTS_FROMedges store attributes —Source_Property,Source_Table,Source_ColumnandCONNECTS_TOedge storeTarget_Property,Target_TableandTarget_Column. The RELATIONSHIP nodes containJoining_Conditionas an attribute if it is derived by joining two tables.
Advantages of storing schema as graph : –
- This allows for better visualisation, making it easier for domain experts to explore and refine the schema.
- Other applications can also query the schema, enabling automated data validation and governance.
- Additionally, storing the schema as a graph ensures all relationships and constraints are preserved, supporting dynamic schema evolution as new entities and properties emerge.
- This approach keeps schema management centralised, scalable, and adaptable.
Let’s write the code for building the same.
We will use Neo4j as the graph database. Install the Neo4j desktop and open Neo4j browser by navigating to localhost:7474 in a web browser. Neo4j itself runs on a separate connection protocol called “Bolt”, which operates on port 7687. When you access Neo4j Browser, it automatically connects to bolt://localhost:7687 after entering your username and password. This Bolt connection allows applications to interact with Neo4j programmatically. Once connected, we can run Cypher queries to create the metagraph.
(p{idx}) "
for idx, prop in enumerate(entity.properties, 1)])};
"""
session.run(entity_query)
for rel in relationship_config.relationships:
relationship_query = f"""
MATCH (s:ENTITY {{Name: '{rel.source_entity}'}}),
(t:ENTITY {{Name: '{rel.target_entity}'}})
MERGE (r:RELATIONSHIP {{Name: '{rel.relationship}',
Joining_Condition: '{rel.joining_condition or ''}'}})
MERGE (r)-[:CONNECTS_FROM {{Source_Property:
'{rel.source_property}', Source_Table:
'{rel.source_mapping_table}', Source_Column:
'{rel.source_mapping_column}'}}]->(s)
MERGE (r)-[:CONNECTS_TO {{Target_Property:
'{rel.target_property}', Target_Table:
'{rel.target_mapping_table}', Target_Column:
'{rel.target_mapping_column}'}}]->(t);
"""
session.run(relationship_query)
# Pass the entity and relationship config to this method
uri = "bolt://localhost:7687"
username = ""
password = ""
database_name = ""
create_metagraph(uri, username, password, database_name,
entity_config, relationship_config)” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
from neo4j import GraphDatabase
from utils.models import EntityConfig, RelationshipConfig
def create_metagraph(uri, username, password, database_name,
entity_config: EntityConfig, relationship_config: RelationshipConfig):
with GraphDatabase.driver(uri, auth=(username, password),
database=database_name
) as driver, driver.session() as session:
for entity in entity_config.entities:
entity_query = f"""
MERGE (e:ENTITY {{Name: '{entity.entity}'}})
{''.join([f"MERGE (p{idx}:PROPERTY {{Name: '{prop.property}'}})
MERGE (e)-[:HAS_PROPERTY {{Is_Key_Property:
{prop.is_key_property}, Source_Table: '{prop.mapping_table}',
Source_Column: '{prop.mapping_column}'}}]->(p{idx}) "
for idx, prop in enumerate(entity.properties, 1)])};
"""
session.run(entity_query)
for rel in relationship_config.relationships:
relationship_query = f"""
MATCH (s:ENTITY {{Name: '{rel.source_entity}'}}),
(t:ENTITY {{Name: '{rel.target_entity}'}})
MERGE (r:RELATIONSHIP {{Name: '{rel.relationship}',
Joining_Condition: '{rel.joining_condition or ''}'}})
MERGE (r)-[:CONNECTS_FROM {{Source_Property:
'{rel.source_property}', Source_Table:
'{rel.source_mapping_table}', Source_Column:
'{rel.source_mapping_column}'}}]->(s)
MERGE (r)-[:CONNECTS_TO {{Target_Property:
'{rel.target_property}', Target_Table:
'{rel.target_mapping_table}', Target_Column:
'{rel.target_mapping_column}'}}]->(t);
"""
session.run(relationship_query)
# Pass the entity and relationship config to this method
uri = "bolt://localhost:7687"
username = ""
password = ""
database_name = ""
create_metagraph(uri, username, password, database_name,
entity_config, relationship_config)
from neo4j import GraphDatabase
from utils.models import EntityConfig, RelationshipConfig
def create_metagraph(uri, username, password, database_name,
entity_config: EntityConfig, relationship_config: RelationshipConfig):
with GraphDatabase.driver(uri, auth=(username, password),
database=database_name
) as driver, driver.session() as session:
for entity in entity_config.entities:
entity_query = f"""
MERGE (e:ENTITY {{Name: '{entity.entity}'}})
{''.join([f"MERGE (p{idx}:PROPERTY {{Name: '{prop.property}'}})
MERGE (e)-[:HAS_PROPERTY {{Is_Key_Property:
{prop.is_key_property}, Source_Table: '{prop.mapping_table}',
Source_Column: '{prop.mapping_column}'}}]->(p{idx}) "
for idx, prop in enumerate(entity.properties, 1)])};
"""
session.run(entity_query)
for rel in relationship_config.relationships:
relationship_query = f"""
MATCH (s:ENTITY {{Name: '{rel.source_entity}'}}),
(t:ENTITY {{Name: '{rel.target_entity}'}})
MERGE (r:RELATIONSHIP {{Name: '{rel.relationship}',
Joining_Condition: '{rel.joining_condition or ''}'}})
MERGE (r)-[:CONNECTS_FROM {{Source_Property:
'{rel.source_property}', Source_Table:
'{rel.source_mapping_table}', Source_Column:
'{rel.source_mapping_column}'}}]->(s)
MERGE (r)-[:CONNECTS_TO {{Target_Property:
'{rel.target_property}', Target_Table:
'{rel.target_mapping_table}', Target_Column:
'{rel.target_mapping_column}'}}]->(t);
"""
session.run(relationship_query)
# Pass the entity and relationship config to this method
uri = "bolt://localhost:7687"
username = ""
password = ""
database_name = ""
create_metagraph(uri, username, password, database_name,
entity_config, relationship_config)
All the above code can be found here — Knowledge Graph Schema Discovery.
Architecture for Knowledge Graph Schema Discovery Module :
Schema discovery is an ongoing process as new tables emerge and existing schemas evolve. Keeping the knowledge graph schema updated is crucial.
To enhance accuracy, LLM-based multi-agent systems can aid schema discovery. However, AI outputs shouldn’t be used directly — domain experts must review and validate them before data ingestion into KG. During discovery, a draft metagraph can be maintained and then finalised after validation.
Below is a sample architecture to automate schema discovery. The process, shown in the diagram, begins with extracting table schemas, followed by AI agents identifying entities and relationships by referencing the existing knowledge graph schema (metagraph). Cypher queries are generated to update the schema graph, with SME (Domain Subject Matter Expert) feedback incorporated for continuous refinement.
Conclusion :
In this blog, we explored the concepts and implementation of knowledge graph schema discovery in detail. I hope you found it insightful! Feel free to share your questions and feedback in the comments.
After discovering the schema, in my next blog we will focus on understanding and building the knowledge graph using PySpark in Neo4j with the sample data. Stay tuned!


