Representing Graphs in Document Databases
In this lesson, you will learn how to represent hierarchical or interconnected data structures within a document database using the Adjacency List pattern.
While document databases are designed for self-contained objects, real-world data often features complex relationships. When we need to model a graph—such as an organizational chart or a social network—we can map the nodes and edges into documents by storing a node's relationships directly within its own schema.
The Adjacency List Pattern
In an adjacency list model, every "node" in your graph is a document. To represent the "edges" (or connections) between nodes, you store an array of references to related nodes.
Imagine we are modeling a simple organizational structure where employees report to a manager:
{
"_id": "emp_101",
"name": "Alice",
"role": "CEO",
"reports": []
},
{
"_id": "emp_102",
"name": "Bob",
"role": "Manager",
"reports": ["emp_103", "emp_104"]
},
{
"_id": "emp_103",
"name": "Charlie",
"role": "Developer",
"reports": []
}
In this example, the reports array serves as our adjacency list. By storing the _id of the subordinate documents, we effectively draw the edges of our graph.
Why Use Adjacency Lists?
- Efficiency: You can retrieve a node and its direct neighbors in a single read operation, which is much faster than performing multiple joins or recursive lookups.
- Flexibility: Since document databases are schema-flexible, you can easily add metadata to the "edge" (the relationship itself) by turning the simple array of strings into an array of objects:
"reports": [{"id": "emp_103", "type": "direct_report"}]. - Simplicity: This pattern maps intuitively to application-level code, where you might already be working with object references.
However, keep in mind that as the depth of your graph increases, traversing the entire structure may require multiple round-trips to the database. If you find your application performing excessive recursive queries, you may eventually need to consider specialized graph databases, but for shallow or direct relationships, the adjacency list is a powerful tool in your document modeling toolkit.
Key Takeaway: The Adjacency List pattern represents graph structures in document databases by storing direct node-to-node references within an array, enabling efficient local traversal of connections.