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

From Sergey Burladyan
Subject Re: Defer a functional index calculation?
Date
Msg-id 87skl6xp7z.fsf@seb.progtech.ru
Whole thread Raw
In response to Defer a functional index calculation?  (Randall Lucas <rlucas@tercent.com>)
List pgsql-general
Randall Lucas <rlucas@tercent.com> writes:

> 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.

Change your get_root_id(id) into get_root_id(example), after this you can start
searching for root not from current id but from it parent_id. Parent is already
exist in table. If parent_id is null - it is root and get_root_id(example) do
not need scan table and will return example.id from it input argument.

--
Sergey Burladyan

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: How to avoid multiple table scan with "NOT IN"
Next
From: Craig Ringer
Date:
Subject: Re: Srf function : missing library on PostgreSQL 8.3.6 on Windows?