How do you store a trie in a relational database?

若如初见. 提交于 2019-12-04 16:24:12

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/355051/how-do-you-store-a-trie-in-a-relational-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!