Hi folks,
I am holding hierarchical data in a table and often need to calculate the "root" of a hierarchy. Initially, a recursive plpgsql function worked just fine. But performance started to lag when I got to scale.
So, I added a functional index.
create table example (id serial primary key, stuff text, parent_id int);
create index example_root_idx on example (get_root_id(id));
(get_root_id(id) pulls an example row and recurses onto parent_id until it hits a root)
This works fine for speeding up access to the existing data, but breaks for inserting new rows because get_root_id(id) can't find the new row. It looks like the index is getting calculated, and the function called, before the row becomes visible to the function.
Is there a way to set a functional index to be deferred (like for FKs), or calculated on an AFTER INSERT ON basis (like with triggers), or similar?
If not, my backup plan is to precalculate get_root_id via a trigger and store it in a column, but that kind of smells (even worse than my current schema, I know).
Thank you,
Randall