I have 2.2M line geometries (roads) in one table and 1500 line geometries (coast lines) in another. Both tables have a spatial index. I need to find the endpoints of roads which are within a certain distance from the coast and store the point geometry along with the distance. Current solution, which seems ineffecient, and takes many many hours to complete on a very fast machine;
CREATE TEMP TABLE with start and end points of the road geometries within distance, using ST_STARTPOINT, ST_ENDPOINT and ST_DWITHIN. CREATE SPATIAL INDEXES for both geometry columns in the temp table.
Do two INSERT INTO operations, one for startpoints and one for endpoints; SELECT geometry and distance, using ST_DISTANCE from point to coastline and a WHERE ST_DWITHIN to only consider points within the chosen distance.
Code looks something along these lines:
create temp table roadpoints_temp as select st_startpoint(road.geom) as geomstart, st_endpoint(road.geom) as geomend from
coastline_table coast, roadline_table road where st_dwithin(road.geom, coast.geom, 100);
create index on roadpoints_temp (geomstart);
create index on roadpoints_temp (geomend);
create table roadcoast_points as select roadpoints_temp.geomstart as geom, round(cast(st_distance(roadpoints_temp.geomstart,kyst.geom) as numeric),2) as dist
from roadpoints_temp, coastline_table coast where st_dwithin(roadpoints_temp.geomstart, coast.geom, 100);
insert into roadcoast_points select roadpoints_temp.geomend as geom, round(cast(st_distance(roadpoints_temp.geomend,kyst.geom) as numeric),2) as dist
from roadpoints_temp, coastline_table coast where st_dwithin(roadpoints_temp.geomend, coast.geom, 100);
drop table roadpoints_temp;
All comments and suggestions welcome :-)
USING gist
for the indexes? postgresql.org/docs/9.3/interactive/sql-createindex.html – joop