我一直在玩 ltree,这是一个 PostgreSQL contrib 模块,看看它是否适合线程化 cmets。您在表中创建一个列来存储路径并在其上创建一个 ltree 索引。然后您可以执行如下查询:
ltreetest=# select path from test where path ~ '*.Astronomy.*';
path
-----------------------------------------------
Top.Science.Astronomy
Top.Science.Astronomy.Astrophysics
Top.Science.Astronomy.Cosmology
Top.Collections.Pictures.Astronomy
Top.Collections.Pictures.Astronomy.Stars
Top.Collections.Pictures.Astronomy.Galaxies
Top.Collections.Pictures.Astronomy.Astronauts
我还没有充分使用它来确定它在插入、更新或删除等方面的表现如何。我假设删除看起来像:
DELETE FROM test WHERE path ~ '*.Astronomy.*';
我在想,一个线程化的评论表可能看起来像:
CREATE SEQUENCE comment_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 78616
CACHE 1;
CREATE TABLE comments (
comment_id int PRIMARY KEY,
path ltree,
comment text
);
CREATE INDEX comments_path_idx ON comments USING gist (path);
插入会粗略(未经测试)看起来像:
CREATE FUNCTION busted_add_comment(text the_comment, int parent_comment_id) RETURNS void AS
$BODY$
DECLARE
INT _new_comment_id; -- our new comment_id
TEXT _parent_path; -- the parent path
BEGIN
_new_comment_id := nextval('comment_id_seq'::regclass);
SELECT path INTO _parent_path FROM comments WHERE comment_id = parent_comment_id;
-- this is probably busted SQL, but you get the idea... this comment's path looks like
-- the.parent.path.US
--
-- eg (if parent_comment_id was 5 and our new comment_id is 43):
-- 3.5.43
INSERT INTO comments (comment_id, comment, path) VALUES (_new_comment_id, the_comment, CONCAT(_parent_path, '.', _new_comment_id));
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
什么的。基本上,路径只是由所有主键组成的层次结构。