Optimising neighbour query in postgis

28 views Asked by At

I have a table with a bunch of geometries in, about 700.

I'd like to query, given a particular row, its nearest neighbours... it seemed to take a long time!

I created a materialized view to speed this up - the data changes very rarely. However, creating the view just seems to take an unreasonable amount of time - many minutes. I feel I must be doing something wrong. Even though the data changes rarely, I see the problem often, for example when loading a database restore.

Each of the geometries in the wkb_geometry has been simplified - so contains not that many points. (Between 50-4500, reduced using st_simplifypreservetopology from the original 600-50,000)

Here's the code for the view...

drop materialized view if exists pcon_neighbours;

create materialized view pcon_neighbours as
SELECT l.pcon20nm,
       l.pcon20cd,
       neighbour.name     AS neighbour,
       neighbour.code     AS neighbour_code,
       neighbour.distance AS distance
FROM pcon_simplified l
         cross join lateral (
    select n.pcon20nm                        as name,
           n.pcon20cd                        as code,
           l.wkb_geometry <-> n.wkb_geometry as distance
    from pcon_simplified n
    where n.pcon20nm != l.pcon20nm
      and l.wkb_geometry <-> n.wkb_geometry < 0.002
    order by distance
    limit 10
    ) neighbour;

The plan looks like this:

Nested Loop  (cost=0.14..49269.98 rows=6500 width=58)
  ->  Seq Scan on pcon_simplified l  (cost=0.00..263.50 rows=650 width=7990)
  ->  Limit  (cost=0.14..75.19 rows=10 width=33)
        ->  Index Scan using pcon_simplified_wkb_geometry_geom_idx on pcon_simplified n  (cost=0.14..1621.27 rows=216 width=33)
              Order By: (wkb_geometry <-> l.wkb_geometry)
              Filter: (((pcon20nm)::text <> (l.pcon20nm)::text) AND ((l.wkb_geometry <-> wkb_geometry) < '0.002'::double precision))

Thanks for any suggestions.

0

There are 0 answers