Hey all, been running into some performance issues with one of my tables,
and it seems to be centered around index maintenance.

I have a table to store aggregated prices that are derived from sale data
over a configurable period, and a function that runs periodically that
inserts new prices if necessary, or "inactivates" the old record and
inserts new ones.  We use that price in calculations, and store the price
we used for a specific calculation for audit purposes, so the old record
cannot just be updated or deleted. We need a new record every time.

So to do that we have an "active_range" column on the table, and that is
 used to set the periods that each specific price was in use for (important
for audit).

The issue seems to be the exclusion constraint we have on the table to
ensure data consistency... It is ridiculously slow to insert / update.  To
update 200 records, it takes 45 seconds. To update 1500 rows takes about
3.5 min. To build the constraint/index fresh on the table (1,392,085 rows)
it takes about 4 min.

Looking at the schema, is there just a clearly better way to do this? I
know uuid is not supported by GiST indexes yet, so casting to text isn't
great, but necessary (as far as I know...) at the moment.

The table definition looks like so:
CREATE TABLE price_generated
(
  price_generated_id uuid NOT NULL DEFAULT gen_random_uuid(),
  product_id uuid NOT NULL,
  company_id uuid NOT NULL,
  date_range daterange NOT NULL,
  average_price numeric NOT NULL,
  average_price_delivered numeric NOT NULL,
  low_price numeric NOT NULL,
  low_price_delivered numeric NOT NULL,
  high_price numeric NOT NULL,
  high_price_delivered numeric NOT NULL,
  uom_type_id uuid NOT NULL,
  active_range tstzrange NOT NULL DEFAULT tstzrange(now(), NULL::timestamp
with time zone),
  CONSTRAINT price_generated_pkey PRIMARY KEY (price_generated_id),
  CONSTRAINT price_generated_company_id_fkey FOREIGN KEY (company_id)
      REFERENCES public.company (company_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT price_generated_product_id_fkey FOREIGN KEY (product_id)
      REFERENCES public.product (product_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT price_generated_company_product_date_active_excl EXCLUDE
  USING gist ((company_id::text) WITH =, (product_id::text) WITH =,
date_range WITH &&, active_range WITH &&)
);

CREATE INDEX idx_price_generated_prod_comp_date
  ON price_generated
  USING btree
  (product_id, company_id, date_range);

Reply via email to