arrays - how to optimise intersect on heroku -
i have postgresql query, check length of intersection of 2 arrays. simplified version of query like:
select array_length(users.array & array[1,2,3,4]) users;
it part of larger query, not important here. works fine on local database, on heroku, intarray extension not whitelisted.
i found simple function intersect arrays, compared &
operator rather slow.
create or replace function array_intersect(anyarray, anyarray) returns anyarray $$ select array( select * unnest( $1 ) unnest = any( $2 ) ); $$ language sql;
on 2000 records of table using &
operator takes 50ms
, using function above takes 150ms
. compare many records can , function doesn't scale '&' operator.
is there way faster or add intarray heroku?
guess depend on rest of query, , how optimized need be.
my first attempt create cte of insecting lengths using unnest
, intersect
... fetch values cte within main expression needed... along lines of:
with merged ( select * unnest(array[1,2,3]) intersect select * unnest(array[1]) ) select count(*) length merged;
if inappropriate have tried function (as did), since interested in length have made function return (to avoid needless conversion array , back):
create or replace function array_count_intersects(anyarray, anyarray) returns bigint $$ select count(*) ( select * unnest($1) unnest = any($2) ) merg; $$ language sql; select array_count_intersects(array[1,2,3], array[1]);
if still not enough, @ creating intermediate table store/cache lengths of intersecting arrays updated via triggers when data changes, use intermediate table lengths need in main query without need perform unions @ all.
Comments
Post a Comment