【问题标题】:PostgreSQL network address range query optimizePostgreSQL网络地址范围查询优化
【发布时间】:2015-09-17 05:03:23
【问题描述】:

下面是大约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
);

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

【问题讨论】:

  • 索引扫描的预期行和实际行之间存在很大差异。如果您运行analyze ip_loc,这会改变吗?较长的扫描时间可能表明您正遭受索引膨胀的困扰。如果您使用reindex 重建索引,这会改善吗?

标签: database postgresql query-optimization


【解决方案1】:

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】:

    这些范围不重叠?我会尝试 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.1 毫秒内工作。

    记得在填充数据后分析表格。

    【讨论】:

    • 然后试试这个改进的查询。
    • @a_horse_with_no_name:以前的版本没那么快,所以这个评论是合适的
    【解决方案3】:

    仅为 end_ip 添加聚集索引

    【讨论】:

      猜你喜欢
      • 2014-07-24
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 2022-01-12
      相关资源
      最近更新 更多