-
Notifications
You must be signed in to change notification settings - Fork 1
AQL Geospatial Guide
Navigation: Home > API & Integration > AQL
Phase 6C introduces query optimizer support for geospatial predicates in ThemisDB. This guide explains how to:
- Write optimal spatial queries with automatic index selection
- Use optimizer hints to guide index selection
- Understand cost estimation for spatial operations
- Achieve performance targets with geospatial predicates
FOR doc IN locations
FILTER ST_DISTANCE(doc.location, {lon: 0, lat: 0}) < 100000
RETURN doc
What happens:
- Optimizer detects
ST_DISTANCEpredicate - Checks for available spatial indexes on
doc.location - If R-tree index exists: uses index (β€100Β΅s cost)
- If no index: falls back to full scan (β€50ms cost on 1M points)
FOR doc IN locations
FILTER ST_DISTANCE(doc.location, {lon: 0, lat: 0}) < 100000
USE_INDEX(doc.location, "geo_idx_rtree")
RETURN doc
Hint Types:
| Hint | Syntax | Effect |
|---|---|---|
USE_INDEX |
USE_INDEX(field, "index_name") |
Force use of specific spatial index |
FORCE_SCAN |
FORCE_SCAN(field) |
Disable indexing, use full scan |
INDEX_PRIORITY |
INDEX_PRIORITY(field, 2.0) |
Adjust index selection priority (0.1-10.0) |
DISTANCE_ORDER |
DISTANCE_ORDER(field, "ascending") |
Optimize distance-based ordering |
Use Case: Find points within a distance radius from a location.
FILTER ST_DISTANCE(doc.location, center) < radiusMeters
Performance:
- With R-tree index: β€100Β΅s (1M points)
- Without index: β€50ms (full scan)
- Speedup: 500x with index
Optimization Tips:
- Always define spatial index on location field
- Use reasonable radius (1km-100km typical)
- Combine with other filters for reduction:
FILTER doc.country == "US" AND ST_DISTANCE(...) < 100km
Use Case: Find points inside a polygon/region.
FILTER ST_CONTAINS(doc.location, polygonGeometry)
Performance:
- With R-tree index: β€150Β΅s (bounding box + verification)
- Without index: β€100ms (complex geometry checks)
- Speedup: 600x with index
Polygon Complexity Impact:
- Simple (4 vertices): ~70Β΅s
- Complex (50 vertices): ~120Β΅s
- Very complex (200+ vertices): ~150Β΅s
Optimization Tips:
- Simplify polygons where possible (reduces per-point cost)
- Use bounding box pre-filter if available
- Place ST_CONTAINS before unindexed filters:
FILTER ST_CONTAINS(doc.location, zone) AND doc.verified == true
Use Case: Find geometries overlapping with a query geometry.
FILTER ST_INTERSECTS(doc.boundary, queryGeometry)
Performance:
- With R-tree index: β€200Β΅s (bbox check + refinement)
- Without index: β€200ms (full geometry comparison)
- Speedup: 1000x with index
Optimization Tips:
- R-tree index handles bbox filtering automatically
- Query is decomposed into:
- Bounding box test (fast)
- Refined geometry check (precise)
- Use simpler geometries when possible
| Dataset Size | Index Type | Recommended? |
|---|---|---|
| <1,000 | NONE | Noβfull scan acceptable |
| 1K-10K | Optional | Use if query-heavy workload |
| 10K-1M | REQUIRED | R-tree or Grid |
| >1M | REQUIRED | R-tree recommended |
R-tree Index (Recommended)
- Best for most spatial queries
- Balanced tree structure
- Good for both distance and containment
- Storage: ~10% of data size
CREATE INDEX idx_location_rtree ON locations(location) TYPE SPATIAL
Grid Index
- Best for uniformly distributed data
- Faster for large-area queries
- Lower maintenance overhead
- Storage: ~5% of data size
CREATE INDEX idx_location_grid ON locations(location) TYPE SPATIAL GRID
Quadtree Index
- Adaptive grid-based
- Good for clustered data
- Automatic refinement
- Storage: ~7% of data size
CREATE INDEX idx_location_qtree ON locations(location) TYPE SPATIAL QUADTREE
The optimizer automatically selects the best index:
For each available spatial index:
1. Calculate index efficiency score
2. Estimate query cost with that index
3. Consider data distribution
4. Apply cost adjustments from hints
Select index with best score
Fall back to full scan if no good option
Factors Considered:
- Index type vs. predicate (R-tree β distance, Grid β uniform)
- Data distribution (clustered, skewed, uniform)
- Index statistics (hit rate, size, maintenance)
- Hints from query (if provided)
// Unoptimized (let optimizer decide)
FOR doc IN locations
FILTER ST_DISTANCE(doc.location, {lon: 0, lat: 0}) < 50000
RETURN doc
// Cost: ~50Β΅s with index, ~25ms without
// Optimizer will auto-select index
// Optimal: indexed predicate first
FOR doc IN locations
FILTER ST_CONTAINS(doc.location, zone)
AND doc.verified == true
AND doc.priority > 5
RETURN doc
// Rewritten to:
// 1. ST_CONTAINS (indexed, filters 80%)
// 2. doc.verified (unindexed, filters 50% of remaining)
// 3. doc.priority (unindexed, filters 30% of remaining)
FOR doc IN locations
FILTER ST_DISTANCE(doc.location, center) < 100000
SORT BY ST_DISTANCE(doc.location, center) ASC
LIMIT 10
RETURN doc
// Optimization: R-tree nearest-neighbor scan
// Result is pre-sorted by distance
// Cost: ~80Β΅s for both filter + sort
FOR zone IN zones
FOR doc IN locations
FILTER ST_CONTAINS(zone.polygon, doc.location)
RETURN {zone: zone._key, count: LENGTH(doc)}
// Optimization stages:
// 1. Create spatial histogram for locations
// 2. Estimate points per zone using histogram
// 3. Predicate pushdown: filter zones before join
// 4. Select R-tree index for contains predicate
// Cost: ~120Β΅s per zone check
FOR doc IN locations
// Use specific index (override auto-selection)
FILTER ST_DISTANCE(doc.location, center) < 50000
USE_INDEX(doc.location, "geo_idx_grid")
// Adjust priority if multiple spatial indexes
FILTER ST_CONTAINS(doc.location, zone)
INDEX_PRIORITY(doc.location, 1.5)
RETURN doc
// Explicitly request full scan (for testing/debugging)
// FILTER ST_DISTANCE(doc.location, center) < 50000
// FORCE_SCAN(doc.location)
| Operation | With Index | Without Index | Speedup |
|---|---|---|---|
| ST_DISTANCE (r=10km) | 50Β΅s | 25ms | 500x |
| ST_DISTANCE (r=100km) | 60Β΅s | 25ms | 400x |
| ST_CONTAINS (simple) | 70Β΅s | 50ms | 700x |
| ST_CONTAINS (complex) | 120Β΅s | 80ms | 600x |
| ST_INTERSECTS | 90Β΅s | 100ms | 1000x |
- Distance queries: β₯800 queries/second with index
- Containment queries: β₯600 queries/second with index
- Intersection queries: β₯500 queries/second with index
- Selectivity estimation: Within 10% of actual
- Execution time estimate: Within 20% of actual
- Index cost advantage: Minimum 3x speedup
Distance (ST_DISTANCE):
With index: log(N) * 10Β΅s + result_count * 5Β΅s
Without index: N * 50Β΅s
Containment (ST_CONTAINS):
With index: log(N) * 15Β΅s + candidates * (2Β΅s + complexity * 0.5Β΅s)
Without index: N * (100Β΅s + complexity * 10Β΅s)
Intersection (ST_INTERSECTS):
With index: log(N) * 20Β΅s + matches * (3Β΅s + complexity * 1Β΅s)
Without index: N * (150Β΅s + complexity * 15Β΅s)
Selectivity depends on query radius/area:
Distance Selectivity:
- 1km radius: 0.5%
- 10km radius: 5%
- 100km radius: 20%
- 1000km radius: 40%
Containment/Intersection:
- Depends on polygon complexity
- Typical range: 1-30%
- Estimated from spatial histogram
-
Check index exists:
SHOW INDEXES locations // Should show SPATIAL type index -
Verify hint is valid:
- Check index name matches exactly
- Verify field name is correct
- Ensure index supports spatial predicates
-
Check data distribution:
- Highly clustered data may benefit from grid index
- Try:
INDEX_PRIORITY(field, 0.5)to reduce cost weight
-
Query plan inspection:
- Use
EXPLAINto see optimizer decisions - Check if FULL_SCAN or INDEX_SCAN is used
- Use
- R-tree indexes: ~1 minute per 1M points
- Grid indexes: ~30 seconds per 1M points
- Normal for initial creation; maintained incrementally
- Verify search radius/area is reasonable
- Use histogram to validate distribution
- Check if predicates are redundant
The optimizer builds a spatial histogram to estimate selectivity:
// 10x10 grid of cells
// Each cell tracks: point count, density
// Selectivity = (points in query area) / (total points)This improves accuracy from 50% to <20% error.
Optimizer applies 5 rewrite rules:
- Index Path Reordering - Move indexed predicates first
- Distance Ordering - Combine filter + sort
- Intersection Optimization - Bbox + refinement
- Redundant Elimination - Remove duplicate predicates
- Predicate Pushdown - Move filters closer to source
If multiple spatial indexes exist:
- Score each index (0-100)
- Rank by score
- Select highest score
- Validate with actual cost estimate
-
Always index geographic fields:
- R-tree for general use
- Grid for uniform distributions
- Quadtree for adaptive needs
-
Place spatial predicates early in FILTER:
FILTER ST_DISTANCE(...) < 50km AND doc.type == "poi" // Good FILTER doc.type == "poi" AND ST_DISTANCE(...) < 50km // Less optimal -
Use reasonable query parameters:
- Distance: 1km-1000km typical range
- Complexity: keep polygons <100 vertices
- Avoid overly complex geometries
-
Monitor performance:
EXPLAIN FILTER ST_DISTANCE(...) < 50km // See cost estimate -
Test with FORCE_SCAN for benchmarking:
// Baseline: full scan performance FILTER ST_DISTANCE(...) < 50km FORCE_SCAN(location) // Indexed: with index FILTER ST_DISTANCE(...) < 50km USE_INDEX(location, "idx")
- AQL Reference - ST_* Functions
- Query Optimizer Guide
- Performance Tuning
- Phase 1 Geospatial Implementation
Phase 6C Status: β
Complete
Last Updated: 2026-08-05
Target Release: v2.0.0 (Q3 2026)
ThemisDB 1.9.0-beta Β· Home Β· Module-Index Β· GitHub Β· Issues
ThemisDB 1.9.0-beta Β· Home Β· Wiki-Index Β· Module-Index Β· FAQ Β· Quick-Reference Β· GitHub Β· Issues Β· Discussions Β· License
- Home
- Hero Articles
- All Wiki Pages
- FAQ
- Edition Comparison
- Repository README
- Changelog
- Roadmap
- Versioning
- Integration Mapping
- Overview
- Readme
- Appendix D Feature Status
- Appendix E Incident Runbooks
- Appendix F AQL Cheatsheet
- Appendix G Configuration
- Appendix H Glossary
- Appendix I Troubleshooting
- Appendix Literatur
- Chapter 00 Genesis
- Chapter 01 Introduction
- Chapter 02 Architecture
- Chapter 03 Multimodel
- Chapter 04 Installation
- Chapter 05 Relational
- Chapter 06 Graph
- Chapter 07 Document
- Chapter 08 Storage Layer
- Chapter 08 Vector
- Chapter 09 Timeseries
- Chapter 10 Enterprise
- Chapter 11 Realtime
- Chapter 12 Computervision
- Chapter 13 Fulltext
- Chapter 14 Geospatial
- Chapter 15 Analytics
- Chapter 16 Ml
- Chapter 16 Sharding
- Chapter 17 LLM Integration
- Chapter 17 Scaling
- Chapter 18 HA
- Chapter 18 Ml
- Chapter 19 Monitoring
- Chapter 19 Monitoring Observability
- Chapter 20 Backup
- Chapter 20 Performance
- Chapter 21 Auth
- Chapter 21 Performance
- Chapter 22 Clients
- Chapter 22 Encryption
- Chapter 23 Testing Qa
- Chapter 24 Ai Ethics
- Chapter 25 Devops Infrastructure
- Chapter 26 Migration Legacy
- Chapter 27 Troubleshooting
- Chapter 28 AQL Reference
- Chapter 29 Analytics Process Mining
- Chapter 30 Deployment Operations
- Chapter 31 API Protocols
- Chapter 32 API Design Rest Principles
- Chapter 32 AQL Oop Implementation
- Chapter 33 Best Practices
- Chapter 34 Query Optimization
- Chapter 35 Data Modeling Patterns
- Chapter 36 Security Hardening
- Chapter 37 Ecosystem Integration
- Chapter 38 Observability Sre
- Chapter 39 Performance Tuning Cookbook
- Chapter 40 Data Governance Compliance
- Chapter 41 Hands On Labs
- Chapter 42 Docs Assistant Usage
- Chapter MVCC Hlc
- Cover
- Cover Book
- Index
- Preface
- Test Links Example
- Batch Operations
- Best Practices
- CRUD Tutorial
- Custom Document Ingestion
- Getting Started Tutorial
- Interactive Examples
- Schema Design
- Video Tutorials
- AQL Reference
- AQL Examples
- AQL Overview
- AQL Feature Roadmap
- AQL Geospatial Guide
- AQL LLM Migration Guide
- AQL API
- AQL Grammar (EBNF)
- AQL Root Overview
- AQL Examples (root)
- API Reference
- API Module README
- OpenAPI Overview
- Client SDK Overview
- SDK Overview
- Operations
- Operations Overview
- Operations Runbook
- Operations Handbook
- ThemisCtl Admin Guide
- Pipeline E2E SOPs
- Docker Overview
- Docker Hub README
- Helm Overview
- Packaging Overview
- Operator Overview
- Security Policy
- Production Hardening Checklist
- Security Hardening Guide
- Encryption Key Management
- Access Control Framework
- Zero Trust Policy
- API Authentication & Authorization
- HSM Production Setup
- PKCS11 Integration
- DSGVO / SOC2 Checklist
- Access Model Runbooks
- Access Model Dashboard
- Maturity Automation Runbook
- Access Review Automation
- Access Model Dashboard
- Access Model Runbooks
- Rights Revocation
- Dr Checklists
- Dr Testing
- Incident Response Playbook
- Incident Response Testing
- GPU Oom Recovery
- Grammar Debugging
- Metrics Scrape Troubleshooting
- Model Swap Procedure
- Quota Tuning
- Subagent Deployment
- Logging Configuration
- Content Model
- Crypto & Keys
- Feature Flags Reference
- Modular Architecture Roadmap
- Modularization Guide
- Module Architecture Index
- PostgreSQL Wire Protocol
- Query Scheduling
- Raft Consensus Design
- Resource Pooling
- Source Directory Guide
- Unified Access Model
- E1 001 Layered Retrieval Design
- E1 002 Ann Abstraction Strategy
- E1 003 Tensor Summary Types
- E1 004 Lora Package Distinction
- E1 005 Model Switch Compatibility
- E1 006 Federated Tensor Summaries
- E2 001 Evaluation Framework Design
- E2 002 Hardware Profile Strategy
- E2 003 Query Planner Routing Model
- E2 004 Approximation Governance Rules
- E2 005 Cross Layer Fallback Confidence Policy
- E3 001 Distributed Tensor Design
- E3 002 Manifest Coordination Strategy
- E3 003 Recovery And Erasure Choice
- E3 004 Tensor Fabric Infrastructure
- Contributing
- Contributing (root)
- Code of Conduct
- Support
- Maintainers
- CTest Guide
- Build Quick Reference
- Developer Wiki Index
- Build / Test / CI
- Module Index
- Branching Strategy
- Release Strategy
- CI Policy Gates Wave C
- Disabled Stub Policy
- Docs PR Policy
- GA Promotion Sign Off
- Github Milestones Setup
- Governance Policies Phase1
- GPU Self Hosted Runner Requirements
- Hardening Phase 1 2 Summary 2026 09 23
- Maturity Claim Verification Checklist
- Maturity Evidence Registry
- Merge Gate Bot Config
- Merge Gate Status Live
- Phase 1 Closure Report
- Phase 1 Infrastructure Deployment
- Phase 1 Infrastructure Deployment Complete
- Phase 3 Baseline Capture
- Phase 3 Refinement Spec
- Phase 4 Sign Off And Closure
- Phase Closure Policy
- Phase Dependency Graph
- Phase3 Enforcement Runbook
- Plugin Submodule Rollback
- PR Version Targeting
- PR Version Targeting Backfill
- Production Ready 2026 Delivery Plan
- Publish Workflow Audit 2026 09 23
- Query Module Status
- Readme
- Release Governance
- Release Promotion Gate Policy
- Release Validation Checklist
- Root Hygiene Policy
- SBOM Approved Versions
- Security Compliance Audit Report 2026 08 10
- Security Module 5671 Evidence Summary
- Sharding P6 Residual Risk Acceptance
- Sourcecode Compliance Governance
- Src Module Documentation Compliance 2026 09 20
- Updates Development Status Sign Off
- Wave C Implementation Complete
- Wave C Implementation Plan
- Wave C Ml Exit Gate Sign Off
- Wave C Policy Gate Evidence
- Wiki Publish Tracking Guide
- Blob Storage
- Cuda
- Ethics Ai
- Exporters
- Huggingface
- Image Analysis
- Importers
- RPC
- Scraper
- Themisdb Ai Watermark Detector
- User Storage Encrypted
- Chimera Architecture
- Chimera Future
- Chimera Readme
- Chimera Roadmap
- Covina Fastapi Ingestion Architecture
- Covina Fastapi Ingestion Future
- Covina Fastapi Ingestion Roadmap
- Vcc Base Architecture
- Vcc Base Future
- Vcc Base Roadmap
- Vcc Clara Ingestion Architecture
- Vcc Clara Ingestion Future
- Vcc Clara Ingestion Roadmap
- Vcc Veritas Architecture
- Vcc Veritas Future
- Vcc Veritas Roadmap
- 01 Hello World
- 02 Todo App
- 03 Contact Manager
- 04 Inventory System
- 05 Time Series Monitor
- 06 Graph Social Network
- 07 Vector Search Documents
- 08 Dms Erp System
- 09 Iot Sensor Network
- 10 Drone Image Analysis
- 11 Blog Wiki
- 12 Expense Tracker
- 13 Recipe Manager
- 14 Ecommerce Catalog
- 15 Event Management
- 16 Kanban Board
- 17 Crm
- 18 Realtime Chat
- 19 Recommendation Engine
- 20 Smart Home
- 21 Coding Platform
- 22 AQL Diagram Tool
- 23 Traveling Salesman
- 24 Moral Philosophy Debates
- API Versioning
- Distributed Sharding
- Feedback Plugins
- Geo
- Gnn
- Image Analysis
- Legal Lora Training
- LLM
- Lora Sync
- Migration
- Nlp
- Performance
- Railway
- Replication
- Rope Visualization
- Sample Product Config
- Security
- Client SDK Overview
- Quickstart
- Sdk Enhancements
- Sdk Implementation Summary
- Test Suite Readme
- Go
- Java
- Javascript
- Php
- Python
- Ruby
- Rust
- Typescript
- 01 Grundlegende Operationen
- 02 AQL Queries
- 03 Graph Daten
- 04 Multimodell Anwendung
- 01 Quickstart Guide
- 02 AQL Referenz Kurzuebersicht
- 03 Datenmodellierung Guide
- 04 Uebungsaufgaben
- 05 Best Practices Guide
- Training Documents
- Training Overview
- 01 Einfuehrung Und Uebersicht
- 02 Datenmodelle Und Architektur
- 03 AQL Abfragesprache
- 04 Installation Und Setup
- 05 Anwendungsbeispiele
- Training Presentations
- Dependencies Readme
- Processmonitor Readme
- Themis.admintools.shared Readme
- Themis.aqlquerybuilder Readme
- Themis.aqlquerybuilder Roadmap
- Themis.auditlogviewer Readme
- Themis.auditlogviewer Roadmap
- Themis.classificationdashboard Readme
- Themis.classificationdashboard Roadmap
- Themis.compliancereports Readme
- Themis.compliancereports Roadmap
- Themis.gisviewer.controlpanel Readme
- Themis.gisviewer.controlpanel Roadmap
- Themis.impactanalysisviewer Readme
- Themis.impactanalysisviewer Roadmap
- Themis.ingestiontool Readme
- Themis.ingestiontool Roadmap
- Themis.keyrotationdashboard Readme
- Themis.keyrotationdashboard Roadmap
- Themis.piimanager Readme
- Themis.piimanager Roadmap
- Themis.retentionmanager Readme
- Themis.retentionmanager Roadmap
- Themis.sagaverifier Readme
- Themis.sagaverifier Roadmap
- Themis.usbadmintool Readme
- Themis.usbadmintool Roadmap
- Architecture Generator Readme
- CI Readme
- CI Roadmap
- Compiler Diagnostics Readme
- Compiler Diagnostics Roadmap
- Completion Readme
- Copilot Ollama Router Readme
- Copilot Ollama Router Roadmap
- Gnn Readme
- Gnn Roadmap
- Rope Visualizer Readme
- Rope Visualizer Roadmap
- Tco Calculator Readme
- Tco Calculator Roadmap
- Tests Readme
- Tests Roadmap
- Themis Config Wx Readme
- Themis Docs Builder Readme
- Wikipedia Ingestion Readme
- Ai Metadata And Provenance
- Build / Test / CI
- Governance And Roadmap
- Developer Wiki Index
- Module Direct Doxygen Check
- Module Doxygen Baseline Summary
- Module Doxygen Batch
- Module Doxygen Coverage Summary
- Module Doxygen Smoke Summary
- Modules And Apis
- Retrieval Direct Doxygen Check
- Soll Ist Gap Summary
- Wiki Delta Report