Is there a recommended pattern for modeling a graph in a relational database?
My presumption is that you'd have the following three tables:
Graphs
------
GraphID, PK
GraphName
Each record in the Graphs
table represents a single graph you are modeling.
Nodes
-----
NodeID, PK
GraphID, FK
NodeName, string
...
Each record in the Nodes
table represents a node in GraphID
, specifying attributes specific to that node.
Edges
-----
EdgeID, PK
GraphID, FK
FromNodeID, FK
ToNodeID, FK
EdgeName, string
...
Each record in the Edges
table represents an edge in GraphID
, specifying the Nodes
it connects and the attributes of an edge (name, distance, etc.).
What I'm having a hard time wrapping my head around is what if there are different types of nodes, where each type of a node has some attributes in common (say 5 or so), but has many unique attributes (say 10-30)?
For simplicity's sake, imagine there are two types of nodes to capture: A and B. How do I model this? I've seen one option being to have a "general" Nodes
table:
Nodes
-----
NodeID, PK
GraphID, FK
NodeName, string
AnotherSharedAttribute, string
...
And then a detailed table for node type A and node type B:
NodesA
------
NodeID, PK
UniqueToA1, string
UniqueToA2, string
...
NodesB
------
NodeID, PK
UniqueToB1, string
UniqueToB2, string
...
Am I understanding this approach correctly? Because what flummoxes me is how do I query this efficiently? It seems to me that to determine the attributes for a particular node, I have to check all possible node type tables (NodesA
and NodesB
in this case) for a matching NodeID
. This might not be a big deal with just two different types of nodes, but in my project there are ~30 different types of nodes and 5 different types of edges.
Thanks