Defer a functional index calculation?

From: Randall Lucas <rlucas(at)tercent(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Defer a functional index calculation?
Date: 2009-03-21 00:37:33
Message-ID: 7d5145af0903201737h4a68bdd4ieddbd7e03cddf8e6@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Amitabh Kant 2009-03-21 04:49:58 Re: PostgreSQL versus MySQL for GPS Data
Previous Message Tom Lane 2009-03-21 00:31:16 Re: SRID conflict, PostgreSQL 8.3