2015-11-12 71 views
1

我在一張桌子上有2.2米的線條几何圖形(道路),在另一張桌子上有1500線的幾何圖形(海岸線)。兩個表都有一個空間索引。 我需要找到距離海岸一定距離內的道路端點,並將點幾何結構與距離一起存儲。 當前的解決方案看起來不夠有效,並且需要很多小時才能在非常快的機器上完成;Postgresql:在距離海岸的距離內找到道路端點

使用ST_STARTPOINT,ST_ENDPOINT和ST_DWITHIN創建包含距離內道路幾何圖形的起點和終點的TEMP TABLE。 爲臨時表中的兩個幾何列創建空間索引。

執行兩個INSERT INTO操作,一個用於啓動點,另一個用於端點; 選擇幾何圖形和距離,使用從點到海岸線的ST_DISTANCE和WHERE ST_DWITHIN僅考慮所選距離內的點。

代碼如下幾行內容:

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; 

所有的意見和建議表示歡迎:-)

+0

嘗試在索引中添加'USING gist'? http://www.postgresql.org/docs/9.3/interactive/sql-createindex.html – joop

+0

我嘗試了一些測試數據的代碼,但沒有性能問題。你有非常複雜的幾何形狀嗎? (有許多頂點)。也許你能提供你的數據樣本嗎? –

+0

我已經明確地使用了gist,但這並沒有影響性能 - 臨時表的創建似乎佔用了大部分處理時間。 – BobJohnson

回答

0

您需要有效地利用索引。看起來最快的計劃是爲每條海岸找到距離它的所有道路。分開進行兩次複查意味着你失去了最近的海岸線與道路的連接,並且需要一次又一次地重新找到這對。

您需要使用EXPLAIN檢查您的執行計劃才能在海岸線表上執行Seq掃描並在路表上執行GiST索引掃描。

select road.* 
from coastline_table coast, roadline_table road 
where 
    ST_DWithin(coast.geom, road.geom, 100) -- indexed query  
    and -- non-indexed recheck 
    (
     ST_DWithin(ST_StartPoint(road.geom), coast.geom, 100) 
     or ST_DWithin(ST_EndPoint(road.geom), coast.geom, 100) 
    );