對於地理位置儲存,在如今的項目中用的愈來愈多,支持的數據庫也很多,像mangodb,redis-geo,postgreSQL..... 本文對postgreSQL point 類型對地理位置數據插入,索引,附近查詢,進行測試;因爲電腦配置不高,僅僅插入600多萬條數據進行測試,但測試結果爲什麼還不如那位大神上100億測試的數據快。(下面解釋爲)php
create table tbl_point(id serial8, poi point);
alter sequence tbl_point_id_seq cache 10000;
insert into tbl_point(poi) select point(trunc(100000*(0.5-random())), trunc(100000*(0.5-random()))) from generate_series(1,10000);
insert into tbl_point(poi) select point(trunc(100000*(0.5-random())), trunc(100000*(0.5-random()))) from generate_series(1,100000);
insert into tbl_point(poi) select point(trunc(100000*(0.5-random())), trunc(100000*(0.5-random()))) from generate_series(1,1000000);
insert into tbl_point(poi) select point(trunc(100000*(0.5-random())), trunc(100000*(0.5-random()))) from generate_series(1,4000000);
\dt+ tbl_point
create index idx_tbl_point on tbl_point using gist(poi) with (buffering=on); //建立索引 \di+ //查看索引信息
select *,poi <-> point(1000,1000) dist from tbl_point where poi <-> point(1000,1000) < 100 order by poi <-> point(1000,1000) limit 10;
就是換個位置數據繼續查10條。redis
select *,poi <-> point(4000,7000) dist from tbl_point where poi <-> point(4000,7000) < 100 order by poi <-> point(4000,7000) limit 10;
剛纔兩次查詢效率都不錯,都是1毫秒多一點,來看看查50條記錄效果。數據庫
select *,poi <-> point(4000,7000) dist from tbl_point where poi <-> point(4000,7000) < 100 order by poi <-> point(4000,7000) limit 50;
查50條記錄效果幾乎到了不理想的狀態,咱們再把limit去掉,直接查詢所有看看。dom
select *,poi <-> point(4000,7000) dist from tbl_point where poi <-> point(4000,7000) < 100 order by poi <-> point(4000,7000);
發現竟然快了不少不少post
回答上面咱們的疑問:當數據足夠時,咱們只查詢10條時,並無掃描全盤,找到10條就返回,全部都是1ms 左右,那速度是至關的快。 因此,別人600億的數據找10條速度理想就能夠理解了。測試
而當須要返回50條數據時,知足要求的並無那麼多,必然全盤掃描,而且屢次覈對。形成查詢時間達到10條查詢時間的36000多倍。。。。。。。。實乃恐懼。。。code
最後奇怪的事情發生了,我執行所有查詢,不添加 limit 50, 速度又快了不少不少。這個問題我也不是很懂,請各位賜教。blog
原創做者:邵澤明 原文連接:http://blog.4d4k.com/index.php/archives/46/索引