下面是用約600萬記錄的表結構:PostgreSQL的網絡地址範圍的查詢優化
CREATE TABLE "ip_loc" (
"start_ip" inet,
"end_ip" inet,
"iso2" varchar(4),
"state" varchar(100),
"city" varchar(100)
);
CREATE INDEX "index_ip_loc" on ip_loc using gist(iprange(start_ip,end_ip));
這需要約1秒至執行查詢。
EXPLAIN ANALYZE select * from ip_loc where iprange(start_ip,end_ip)@>'180.167.1.25'::inet;
Bitmap Heap Scan on ip_loc (cost=1080.76..49100.68 rows=28948 width=41) (actual time=1039.428..1039.429 rows=1 loops=1)
Recheck Cond: (iprange(start_ip, end_ip) @> '180.167.1.25'::inet)
Heap Blocks: exact=1
-> Bitmap Index Scan on index_ip_loc (cost=0.00..1073.53 rows=28948 width=0) (actual time=1039.411..1039.411 rows=1 loops=1)
Index Cond: (iprange(start_ip, end_ip) @> '180.167.1.25'::inet) Planning time: 0.090 ms Execution time: 1039.466 ms
iprange是一個定製的類型:
CREATE TYPE iprange AS RANGE (
SUBTYPE = inet
);
有沒有辦法做到的查詢速度更快?
索引掃描的期望行和實際行之間存在相當大的差異。如果你運行'analyze ip_loc',這會改變嗎?漫長的掃描時間_might_表示您正在飽受指數膨脹之苦。如果使用'reindex'重建索引,這會改進嗎? –