Question :
I have a table adjacency
, which stores information about connected lines and their angle to each other is build by
CREATE TABLE public.adjacency
(
currentedge integer,
currentgeom geometry(LineString,25832),
sourcenode integer,
targetnode integer,
nextedge integer,
nextgeom geometry(LineString,25832),
degrees double precision
)
Now, I want to select only Lines which have angles in specific intervals
DROP TABLE IF EXISTS restriction;
SELECT DISTINCT '100' as to_cost, a.nextedge as target_id, a.currentedge as via_path
INTO restriction
FROM adjacency a , adjacency b
WHERE (a.sourcenode = b.sourcenode AND (a.degrees < 45.0 OR a.degrees > 315.0))
OR (a.targetnode = b.targetnode AND (a.degrees < 45.0 OR a.degrees > 315.0))
OR (a.targetnode = b.sourcenode AND (a.degrees BETWEEN 46.0 AND 224.0))
AND a.nextedge=b.currentedge
The execution of the last command seems endless. Can anyone explain to me what to change here? My execution plan:
Seq Scan on adjacency a (cost=0.00..2574.30 rows=30630 width=40)
Answer :
One thing that sometimes works is to rewrite a series of OR conditions into a sequence of UNIONs:
CREATE TABLE restriction
AS
SELECT '100' as to_cost, a.nextedge as target_id, a.currentedge as via_path
FROM adjacency a
JOIN adjacency b ON a.nextedge = b.currentedge
WHERE a.sourcenode = b.sourcenode AND (a.degrees < 45.0 OR a.degrees > 315.0)
UNION
SELECT '100' as to_cost, a.nextedge as target_id, a.currentedge as via_path
FROM adjacency a
JOIN adjacency b ON a.nextedge=b.currentedge
WHERE a.targetnode = b.targetnode AND (a.degrees < 45.0 OR a.degrees > 315.0)
UNION
SELECT '100' as to_cost, a.nextedge as target_id, a.currentedge as via_path
FROM adjacency a
JOIN adjacency b ON a.nextedge=b.currentedge
WHERE a.targetnode = b.sourcenode AND (a.degrees BETWEEN 46.0 AND 224.0)
;
You don’t need an additional distinct here, as UNION
will take care of that. I also replace the ancient, outdated implicit join syntax with an explicit JOIN operator.
You can additionally try indexes on:
adjacency (nextedge, sourcenode)
adjacency (currentedge, sourcenode)
adjacency (nextedge, targetnode)
adjacency (currentedge, targetnode)