Write element's ancestry to Postgres table from adjacency list

前端 未结 2 967
我寻月下人不归
我寻月下人不归 2021-01-21 13:34

I want to write a 1 to n-hierarchy that\'s stored as an adjacency list to a table that lists each of an element\'s ancestors. I\'m using a Postgres database (Postgres 10, but th

2条回答
  •  青春惊慌失措
    2021-01-21 14:04

    if the position of the object is not changed in time (i.e. if it was put from the beginning on level 6 it will stay on that level forever) you can introduce some sane id with 7 numbers, showing 7 levels, separated by lets say semicolon(:):

    '1:1:1:1:1:1:1'

    and then introduce some functional indexes, like:

    CREATE INDEX level1_idx ON main_table USING (regexp_split_to_array(id, '\\:')[1])
    CREATE INDEX level2_idx ON main_table USING (regexp_split_to_array(id, '\\:')[2])
    CREATE INDEX level3_idx ON main_table USING (regexp_split_to_array(id, '\\:')[3])
    

    then you can alaways make an efficient query:

    SELECT id, regexp_split_to_array(id, '\\:')[1] as level1, regexp_split_to_array(id, '\\:')[2] as level2, ...
    ORDER BY level1, level2, level3 ...
    

提交回复
热议问题