Storing tree-structured data in a database is a very common requirement, typically such as the Forum system's section relationship. In the traditional relational database, a variety of solutions have been created.
In this paper, the storage tree structure data is used as the requirement, and several design patterns are described, which use relational database and document database as storage. A. Relational database design Pattern 1
ID |
name |
parent_id |
1 |
A |
Null |
2 |
B |
1 |
3 |
C |
1 |
4 |
D |
2 |
The above diagram represents one of the traditional design methods, which is to store each node of the tree structure as a row in the relational database, and each node holds a pointer to its parent node.
Advantage : The structure is simple and easy to understand, insert modification operation is very simple
Disadvantage : If you want to get all the child nodes of a node, it will be a disgusting thing.
B. Relational database design pattern 2
ID |
name |
parent_id |
Left |
Right |
1 |
A |
Null |
1 |
8 |
2 |
B |
1 |
2 |
5 |
3 |
C |
1 |
6 |
7 |
4 |
D |
2 |
3 |
4 |
The above figure, based on Mode 1, has two more columns, left and right, which are equivalent to the btree, which stores both the maximum and the minimum values of the right and left branch nodes.
Advantages : To find a node of the child node is very easy, only need to do a range of query on the line (such as Node B nodes, only need to query ID >=2 && id<=5)
disadvantage : Because the tree structure exists here, adding or modifying existing junction points may have a ripple effect, the operation is too complex
C. Document-type database design pattern 1
The entire tree structure is stored as a document, the document structure is both tree-like structure, concise and understandable.
Advantages : Concise and easy to understand
disadvantage : The document will become larger, the changes to all nodes are concentrated in this document, concurrent Operations Limited D. Document Database design mode 2
Save all the child nodes of each node
Advantages : Simple structure, easy to find the sub nodes
disadvantage : Finding a parent node can be tricky.
E. Document-type database design Pattern 3
Taking full advantage of the document storage schema-less, the above C scheme is used to store a large tree-shaped document, and the other information of each node is stored separately.
Advantages : Easy to operate, the operation of the structure can directly manipulate the large tree-shaped documents, the operation of the data only need to operate a single data
disadvantage : Changes to all nodes are concentrated in this document, and concurrent operations are restricted