postgis-spatial-query-optimization
Architect, index, and optimize spatial databases using PostgreSQL and PostGIS. Master geometry vs geography data types, spatial reference systems (SRID 4326 vs 3857), GiST and SP-GiST indexing, spatial joins, K-Nearest Neighbor (KNN) distance queries, and spatial clustering with ST_ClusterDBSCAN. Trigger when designing GIS schemas, optimizing geo-queries, or processing spatial datasets.
- License 许可
- MIT
- 最近更新
- 2026-10-17
- Stars
- ★ 8
- Forks
- 1
01 前言 Front Matter
- name
- postgis-spatial-query-optimization
- metadata
- { "category": "Geospatial and GIS Engineering" }
- description
- Architect, index, and optimize spatial databases using PostgreSQL and PostGIS. Master geometry vs geography data types, spatial reference systems (SRID 4326 vs 3857), GiST and SP-GiST indexing, spatial joins, K-Nearest Neighbor (KNN) distance queries, and spatial clustering with ST_ClusterDBSCAN. Trigger when designing GIS schemas, optimizing geo-queries, or processing spatial datasets.
- compatibility
- PostgreSQL 14+, PostGIS 3.3+
03 SKILL.md 正文
PostGIS Spatial Query Optimization Skill Guide
This skill establishes database modeling standards and query optimization strategies for high-volume geospatial systems using PostgreSQL and the PostGIS extension.
1. Spatial Indexing & Coordinate Systems
[ Coordinate System Reference (SRID) ]
|-- EPSG:4326 (WGS 84): Unprojected Lat/Long in degrees (GPS standard)
|-- EPSG:3857 (Web Mercator): Projected coordinates in meters (Tile rendering)
|
v
[ PostGIS Column Storage ]
|-- GEOMETRY: Flat Euclidean planar calculations (Fast, accurate on local scales)
|-- GEOGRAPHY: Spheroidal great-circle calculations (Accurate globally across poles/equator)
|
v
[ Spatial Indexing (GiST / SP-GiST) ]
+---> R-Tree Bounding Box (BBOX) index eliminates 99%+ of non-intersecting shapes
2. Production SQL Patterns & Optimization
A. Schema Definition with Spatial Indexing
-- Enable PostGIS extensions
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS postgis_topology;
-- High-performance delivery zones table
CREATE TABLE delivery_zones (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
merchant_id UUID NOT NULL,
zone_name VARCHAR(100) NOT NULL,
boundary GEOMETRY(Polygon, 4326) NOT NULL,
created_at TIMESTAMPTZ DEFAULT clock_timestamp()
);
-- Bounding Box R-Tree Index
CREATE INDEX idx_delivery_zones_boundary ON delivery_zones USING GIST (boundary);
-- Driver tracking with Geography for real-world meter accuracy
CREATE TABLE driver_locations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
driver_id UUID NOT NULL,
current_location GEOGRAPHY(Point, 4326) NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX idx_driver_locations_geog ON driver_locations USING GIST (current_location);
B. K-Nearest Neighbor (KNN) Index-Accelerated Query
-- Finds the 5 closest available drivers within 10 km (10,000 meters)
-- PostGIS `<->` operator performs indexed bounding box distance search
WITH target_pickup AS (
SELECT ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)::geography AS pickup_geom
)
SELECT
d.driver_id,
ST_Distance(d.current_location, t.pickup_geom) AS distance_meters
FROM driver_locations d, target_pickup t
WHERE ST_DWithin(d.current_location, t.pickup_geom, 10000) -- Restricts search radius
ORDER BY d.current_location <-> t.pickup_geom
LIMIT 5;
C. Spatial Join with Bounding Box Pre-Filter
-- Check which orders fall inside active merchant delivery zones
SELECT
o.id AS order_id,
z.zone_name,
z.merchant_id
FROM orders o
JOIN delivery_zones z
ON z.boundary && o.delivery_location -- Fast Bounding Box overlap pre-filter
AND ST_Contains(z.boundary, o.delivery_location) -- Exact polygon evaluation
WHERE z.merchant_id = 'c38a264a-251f-4ffb-88a4-0ef6630f9ec9';
3. Performance Best Practices
- Bounding Box Pre-Filtering (
&&): PostGIS functions likeST_IntersectsandST_Containsautomatically use bounding box checks, but when writing custom filters, always leverage&&to engage GiST indexes. - Transformations in Queries: Never run
ST_Transform(column, 3857)in aWHEREclause without a functional index; transform input literals instead:-- FAST: transforms literal, keeps index active WHERE geom && ST_Transform(ST_MakePoint(...), 4326) - Clustering & Vacuuming: Regularly execute
CLUSTER delivery_zones USING idx_delivery_zones_boundaryon read-heavy spatial tables to align on-disk storage with Hilbert curve spatial locality.
04 同仓库更多 Skills
security-audit
Comprehensive security guidance, source code audit, vulnerability assessment, and penetration test review for codebases, APIs, microservices, CLI tools, libraries, and LLM-backed applications. Triggers on requests to audit a codebase, conduct security reviews, find vulnerabilities or flaws, pen-test source code, or when the user asks in Arabic (فحص أمني، تدقيق الكود أمنياً، مراجعة الثغرات، فحص أمان المشروع). Supports Guidance mode (focused review) and Full Audit mode (deterministic 6-phase harness).
malware-analysis-reversing
Production malware analysis workflows, reverse engineering methodologies, isolated sandbox triage, static/dynamic binary analysis, memory forensics, and YARA detection rule authoring.
application-security-pentesting
Production Application Security (AppSec) standards, OWASP Top 10 vulnerability remediation, SAST/DAST pipeline integration, secure code review, threat modeling, and defensive security posture.
oauth2-oidc-security-flows
Implement enterprise OAuth 2.1 and OpenID Connect (OIDC) authorization code flow with Proof Key for Code Exchange (PKCE), state and nonce verification, refresh token rotation, token revocation, and centralized IdP federation (Keycloak, Auth0, Okta). Trigger when building secure authentication, single sign-on (SSO), or third-party delegated authorization.
jwt-session-management-hardening
Harden JWT-based authentication and session lifecycles using asymmetric signing (RS256/EdDSA), JWKS rotation, strict claims validation, Redis-backed sliding window sessions, revocation lists, and secure HttpOnly cookie storage. Trigger when implementing token validation, session revocation, or hardening API authentication.
soc2-compliance-automation
Best practices for implementing SOC 2 Type II compliance controls, continuous evidence collection, infrastructure policy-as-code, and automated security monitoring. Use when automating Trust Services Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy), audit logging, IAM least privilege, or CI/CD security gates.