Defer a functional index calculation? - Mailing list pgsql-general

From Randall Lucas
Subject Defer a functional index calculation?
Date
Msg-id 7d5145af0903201737h4a68bdd4ieddbd7e03cddf8e6@mail.gmail.com
Whole thread Raw
Responses Re: Defer a functional index calculation?  (Sergey Burladyan <eshkinkot@gmail.com>)
Re: Defer a functional index calculation?  (Sam Mason <sam@samason.me.uk>)
List pgsql-general
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

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: SRID conflict, PostgreSQL 8.3
Next
From: Amitabh Kant
Date:
Subject: Re: PostgreSQL versus MySQL for GPS Data