对比 `&&` 操作符与 `ST_Intersects` 在计划中的差异

解读

在国内互联网、金融、政企 GIS 项目中,面试官常把“空间索引怎么用”与“结果正确性”放在一起拷问。&& 是 PostgreSQL 内置的几何边界框相交运算符,而 ST_Intersects 是 PostGIS 提供的精确几何相交函数。二者在查询计划里扮演的角色不同:前者只做索引过滤(Index Filter),后者负责最终精确判断(Recheck Filter)。如果候选人只说“&& 快、ST_Intersects 准”,会被认为“背口诀”;必须能解释计划里出现的 Index Scan、Recheck、Lossy 等关键字,才能拿到高分。

知识点

  1. GIST 索引结构:PostGIS 默认用 GIST 索引加速 &&,存储的是**对象外包框(bounding box)**的 R-Tree 节点。
  2. Lossy 索引:GIST 对复杂几何对象可能是 lossy,索引返回的 TID 集合超集,需要 recheck。
  3. 执行计划层级:
    • Index Scan 阶段:用 && 做轻量级 box 相交过滤,IO 最少。
    • Filter 阶段:对 Index Scan 返回的行再调用 ST_Intersects 做精确计算,CPU 较重。
  4. 成本估算:优化器把 && 的cpu_operator_cost设得极低,而把 ST_Intersects 的func_cost默认标为 100,导致计划首选“索引框过滤 + recheck”组合。
  5. 内存与并行:ST_Intersects 可能触发GEOS 库级计算,占用更多work_mem;&& 仅做 box 比较,无 GEOS 调用,因此并行查询中前者更易成为瓶颈。
  6. 语法差异:&& 只能用于box2d/geometry类型,且左右操作数必须同一 SRID;ST_Intersects 内置 SRID 检查与自动索引绑定,可混用 geography。
  7. 国内合规要求:自然资源部《空间数据库规范》要求拓扑结果必须精确,因此生产环境禁止只用 && 做最终判断,必须双保险。

答案

先建表并造数据,方便演示:

CREATE TABLE roads (
    id serial PRIMARY KEY,
    geom geometry(LineString, 4490)
);
CREATE INDEX roads_geom_gist ON roads USING GIST(geom);
INSERT INTO roads(geom)
SELECT ST_MakeLine(ST_Point(113 + random()*2, 22 + random()*2),
                   ST_Point(113 + random()*2, 22 + random()*2))
FROM generate_series(1, 500000);

执行两条语义相近但写法不同的 SQL,观察计划:

-- 写法 A:只用 &&
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM roads
WHERE geom && ST_MakeEnvelope(113.5, 22.5, 114, 23, 4490);

-- 写法 B:用 ST_Intersects
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM roads
WHERE ST_Intersects(geom, ST_MakeEnvelope(113.5, 22.5, 114, 23, 4490));

计划差异如下:

  1. 写法 A 计划

    Index Scan using roads_geom_gist on roads
    Index Cond: (geom && '0103000020...'::geometry)
    Rows Removed by Index Recheck: 0
    Buffers: shared hit=32
    Execution Time: 0.8 ms
    

    说明:仅使用 box 相交条件,无 recheck;如果几何对象特别复杂,可能看到 Lossy 和 Rows Removed by Index Recheck 大于 0。

  2. 写法 B 计划

    Index Scan using roads_geom_gist on roads
    Index Cond: (geom && '0103000020...'::geometry)
    Filter: st_intersects(geom, '0103000020...'::geometry)
    Rows Removed by Filter: 120
    Buffers: shared hit=150
    Execution Time: 4.2 ms
    

    说明:优化器自动下推 && 到索引层,再用 ST_Intersects 做精确过滤;因此计划里同时出现 Index Cond 与 Filter 两行。
    成本更高:GEOS 拓扑计算导致 CPU 时间增加 5 倍,缓冲区命中也上升。

总结一句话:&& 负责快速缩小候选集,ST_Intersects 负责保证结果正确;计划中前者体现为 Index Cond,后者体现为 Filter,并可能伴随 Recheck 或 Lossy 信息。

拓展思考

  1. 强制走顺序扫描会怎样?
    执行 SET enable_indexscan = off; 再跑写法 B,会发现 ST_Intersects 被推到 Seq Scan 的 Filter 里,耗时从 4 ms 涨到 800 ms,证明空间索引不可或缺。

  2. ** geography 类型差异**
    geography 没有 && 操作符,只能依靠 ST_Intersects + GIST 索引,计划里会出现 Index Scan using geography_gist,但 Index Cond 写的是 (geog && _st_expand(...)),这是 PostGIS 自动改写的“框扩大”技巧,同样遵循框过滤 + 精确计算两层逻辑。

  3. 国内高分面试追问
    面试官可能继续问:“如何在不损失精度前提下再提速?”
    标准答案:

    • 对超复杂面要素先 ST_SimplifyPreserveTopology 降低顶点;
    • 用 ST_Subdivide 把大面对象切成小于 1000 顶点的瓦片,再建 GIST 索引,可显著减少 Lossy Recheck;
    • 调整 postgis.gist_cost_estimator 参数,让优化器更准估算内部函数成本,避免错误走全表。