Skip to content

Commit

Permalink
Speeding up intersection splits query
Browse files Browse the repository at this point in the history
  • Loading branch information
kiambogo committed Jun 27, 2017
1 parent bc4a4a9 commit 43e7afe
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 18 deletions.
21 changes: 3 additions & 18 deletions api/app/db/dao/PostgresMapDao.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package db.dao

import javax.inject.{Inject, Singleton}

import com.vividsolutions.jts.geom.{ Geometry, LineString, Coordinate }
import com.trifectalabs.roadquality.v0.models.{ Point, MapRoute }
import com.trifectalabs.polyline.{ Polyline, LatLng }
Expand Down Expand Up @@ -109,22 +107,9 @@ class PostgresMapDao @Inject() (protected val dbConfigProvider: DatabaseConfigPr
}

override def intersectionsSplitsFromSegment(segment_polyline: String): Future[Seq[Geometry]] = {
val sql = sql"""
WITH
polyline AS (SELECT ST_LineFromEncodedPolyline(${segment_polyline})),
intersections AS (SELECT the_geom as intersection FROM ways_vertices_pgr
WHERE ST_DWithin(the_geom, (SELECT * FROM polyline), 5, false))
SELECT (st_dump(
st_split(
st_snap(
(SELECT * FROM polyline),
(SELECT st_collect(array_agg(intersection::geometry)) FROM intersections),
0.00008
),
(SELECT st_collect(array_agg(intersection::geometry)) FROM intersections)
)
)).geom;
""".as[Geometry]
// Segment snap buffer = 0.00008
// Nearby vertices limit = 10000
val sql = sql"""SELECT * FROM intersection_splits_from_segment(${segment_polyline}, 0.00008, 10000)""".as[Geometry]
dbMetrics.timer("intersectionSplitsFromSegment").timeFuture { db.run(sql) }
}

Expand Down
29 changes: 29 additions & 0 deletions api/conf/evolutions/default/10.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Migrate intersection splits from segment to evolutions

# --- !Ups
CREATE OR REPLACE FUNCTION intersection_splits_from_segment(polyline text, snap_distance float, buffer integer)
RETURNS TABLE (intersections geometry) AS $$
BEGIN
RETURN QUERY
WITH
polyline AS (SELECT ST_LineFromEncodedPolyline(polyline)),
nearby_verices AS (SELECT the_geom FROM ways_vertices_pgr ORDER BY the_geom <-> (SELECT * FROM polyline) LIMIT buffer),
intersections AS (SELECT the_geom as intersection FROM nearby_verices WHERE ST_DWithin(the_geom, (SELECT * FROM polyline), 5, false))
SELECT (st_dump(
ST_Split(
ST_Snap(
(SELECT * FROM polyline),
(SELECT ST_Collect(array_agg(intersection::geometry)) FROM intersections),
snap_distance
),
(SELECT ST_Collect(array_agg(intersection::geometry)) FROM intersections)
)
)).geom;;
END;;
$$ LANGUAGE plpgsql;


# --- !Downs

DROP FUNCTION IF EXISTS intersection_splits_from_segment(segment text, snap_distance float, buffer integer);

0 comments on commit 43e7afe

Please sign in to comment.