PostgreSQL网络地址范围查询优化

时间:2015-09-17 05:03:23

标签: database postgresql query-optimization

以下是包含约600万条记录的表格结构:

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
);

有没有办法更快地进行查询?

3 个答案:

答案 0 :(得分:0)

这些范围是不重叠的?我尝试btree索引end_ip并执行:

with candidate as (
  select * from ip_loc
  where end_ip<='38.167.1.53'::inet
  order by end_ip desc
  limit 1
)
select * from candidate
where start_ip<='38.167.1.53'::inet;

在我的计算机上以4M行的0.1ms工作。

请记住在用数据填充后分析表。

答案 1 :(得分:0)

inet类型是复合类型,而不是构造IPv4地址所需的简单32位;它包括一个网络掩码。这使得存储,索引和检索不必要地复杂如果您感兴趣的是实际IP地址(即实际地址的32位,而不是具有网络掩码的地址,例如您将从列出应用程序客户端的Web服务器,并且您不操纵数据库中的IP地址。如果是这种情况,您可以将start_ipend_ip存储为简单整数,并对使用简单整数比较的那些进行操作。 (使用integer[4]数据类型对IPv6地址也可以这样做。)

要记住的一点是the default range constructor behaviour is to include the lower bound and exclude the upper bound所以在您的索引和查询中,不包括实际的end_ip

最后,如果您坚持使用范围类型,则应在索引上添加range_ops operator class以获得最佳效果。

答案 2 :(得分:0)

仅为end_ip添加聚簇索引