I have a prefix trie. What is the recommended schema for representing this structure in a relational database? I need substring matching to remain efficient.
How about the Materialized Path design?
CREATE TABLE trie (
path VARCHAR(<maxdepth>) PRIMARY KEY,
...other attributes of a tree node...
);
To store a word like "stackoverflow":
INSERT INTO trie (path) VALUES
('s'), ('st'), ('sta'), ('stac'), ('stack'),
('stacko'), ('stackov'), ('stackove'), ('stackover'),
('stackover'), ('stackoverf'), ('stackoverflo'),
('stackoverflow');
The materialized path in the tree is the prefixed sequence of characters itself. This also forms the primary key. The size of the varchar column is the maximum depth of trie you want to store.
I can't think of anything more simple and straightforward than that, and it preserves efficient string storage and searching.
SELECT path FROM trie WHERE path='st'
. If this returns a non-empty set, then "st" is in the Trie. I don't know what you're talking about on the second point. –
Gap =
? –
Perni LIKE
. –
Gap The above accepted answer to use the materialized path is awesome, but I think the table needs 2 more columns to be complete:
CREATE TABLE trie (
path VARCHAR(<maxdepth>) PRIMARY KEY,
**node_id NUMBER,**
**parent_node_id NUMBER,**
...other attributes of a tree node...
);
The parent_node_id is a foreign key reference to the same table "trie", and references column "node_id". So suppose you search for the prefix "stack", if you have two matching suffix paths "overflow" and "underflow", you can find both of these child nodes using the query:
SELECT * FROM trie WHERE parent_node_id =
(select node_id from trie where path='stack')
This will give us all the child nodes of a matching path and maintains the relations between the nodes.
Does any of your entities have a relationship with any other? If not, that is, not relational, a hash table with a serialization would do it.
© 2022 - 2024 — McMap. All rights reserved.