Repository navigation
Add S2 projection index and spatial predicate functions - #102485
JasonLi-cn wants to merge 51 commits into
Conversation
|
If we decide to merge this, then it needs to be under an |
Agreed. We can rename |
…d `s2CapContains` Implement granule-level spatial filtering for tables with S2 cell identifiers in the primary key. Three modes are available, controlled by settings: 1. Ancestor mode (`allow_experimental_s2_keycondition = 1`): lifts the granule's `[cell_min, cell_max]` range to a common ancestor cell and tests intersection with the query region. 2. Coverer mode (`s2_keycondition_use_coverer = 1`): decomposes the query region into ~20 cells via `S2RegionCoverer` at parse time; per-granule eval uses `S2CellUnion::Intersects` (integer comparisons, no trigonometry). 3. Range-intersect mode (`s2_keycondition_use_range_intersect = 1`): same parse-time covering as mode 2, but tests the granule's actual `[cell_min, cell_max]` Hilbert-curve interval directly against the covering via `coveringIntersectsRange`, bypassing the ancestor entirely. This is the most precise mode. All modes are conservative (no false negatives). Co-Authored-By: Claude (GLM-4.7) <[email protected]>
…on` setting Replace the three-setting hierarchy (`allow_experimental_s2_keycondition`, `s2_keycondition_use_coverer`, `s2_keycondition_use_range_intersect`) with a single `allow_experimental_s2_keycondition` that always activates the best code path: coverer + range-intersect. The intermediate ancestor-mode and coverer-mode paths added no value — range-intersect is strictly more precise at no extra cost (one binary search over ~20 covering cells, pure integer comparisons). Removing them simplifies the code by ~170 lines and eliminates two settings that users would never have a reason to toggle independently. `S2RectData` / `S2CapData` covering fields become non-optional (`S2CellUnion` instead of `std::optional<S2CellUnion>`), always populated at parse time. Eval blocks now call `coveringIntersectsRange` directly without branching. Delete tests 04043 and 04044 (they tested the removed intermediate modes). Rewrite test 04042 to verify correctness: count with pruning ON must equal count with pruning OFF for both `s2RectContains` and `s2CapContains`. Co-Authored-By: Claude (GLM-4.7) <[email protected]>
…tersect` support Refactor the two separate S2 enum values (`FUNCTION_S2_RECT_CONTAINS`, `FUNCTION_S2_CAP_CONTAINS`) and their data structs (`S2RectData`, `S2CapData`) into a single unified `FUNCTION_S2_COVERING` with `S2CoveringData` that stores a pre-computed `S2CellUnion` covering and the original function name for display. Add `s2CellsIntersect(cell_id, const)` key condition support: - A single S2 cell is already a perfect covering, so no `S2RegionCoverer` is needed — just wrap the constant cell in an `S2CellUnion`. - Supports both argument orders (commutative). - Dispatch `s2CellsIntersect` before the generic 2-arg `func(key, const)` path in `extractAtomFromTree`, since the generic path would match (one arg is the key column, the other is a constant) but skip the S2 covering computation. Existing `s2RectContains` and `s2CapContains` behavior is preserved — the unified `analyze_s2_covering` lambda handles all three functions through a shared `make_result` helper that builds the covering and calls the atom_map. Co-Authored-By: Claude (GLM-4.7) <[email protected]>
Replace the two hardcoded `opts.set_max_cells(20)` in `KeyCondition.cpp` with a new query-level setting `s2_max_covering_cells` (default 20), following the same pattern as `allow_experimental_s2_keycondition`. Merge the tests from 04042 and 04043 into a single test file `04042_s2_keycondition.sql` covering all S2 key condition functions (`s2RectContains`, `s2CapContains`, `s2CellsIntersect`) and the new `s2_max_covering_cells` setting. Co-Authored-By: Claude (GLM-4.7) <[email protected]>
`s2CellsIntersect` is a 2-argument function, so it is always handled by the early return in the `num_args == 2` branch (line 3141). The check in the `else` branch (for 3+ arguments) was unreachable dead code — only `s2RectContains` and `s2CapContains` (both 3-argument) can reach there. Co-Authored-By: Claude (GLM-4.7) <[email protected]>
- Guard `checkInHyperrectangle` against ±infinity `Field` boundaries: when
the S2 key column is not the leftmost key in a composite primary key,
`forAnyHyperrectangle` initialises its range with `NEGATIVE_INFINITY` /
`POSITIVE_INFINITY` (Null-typed `Field`s). `FieldVisitorConvertToNumber<UInt64>`
throws on `Null`, so an unbounded range now conservatively returns `{true, true}`
instead of throwing an exception.
- Add defensive `atom_map.end()` check in `make_result` lambda: if `func_name`
is absent from `atom_map` (e.g. after a future refactor), return `false` instead
of dereferencing `end()`.
- Expand `s2CellsIntersect` covering comment to explain why wrapping a single
`S2CellId` in a `S2CellUnion` is sound for ancestor/descendant intersection:
its Hilbert-curve range `[range_min, range_max]` exactly covers all leaf-cell
descendants, matching the semantics of `S2CellId::intersects`.
- Change `s2_max_covering_cells` default from 20 to 8, matching
`S2RegionCoverer::Options::kDefaultMaxCells`. Store the field as `int`
(matching `set_max_cells`) and clamp to `std::numeric_limits<int>::max()` at
construction to prevent `UInt64`→`int` overflow; the clamp is done once in the
initialiser list so the call sites need no further cast.
- Update `s2_max_covering_cells` setting description to note that it has no
effect for `s2CellsIntersect` (which always uses a single-cell exact covering).
- Add `no-parallel-replicas` tag to the test: the `EXPLAIN` granule counts and
query routing differ under parallel-replicas mode, which also injects a
`cluster_for_parallel_replicas` setting that does not exist in single-node CI.
- Add test case 11: composite primary key `(part_id, cell_id)` where the S2
column is not the first key column, verifying no false negatives via the
infinity-boundary fix above.
Co-Authored-By: Claude (claude-sonnet-4-6) <[email protected]>
- Update stale "default 20" comment in `KeyCondition.cpp` to "default 8" (the default was changed to match `S2RegionCoverer::Options::kDefaultMaxCells`). - Add `s2CellsIntersect` to the `allow_experimental_s2_keycondition` setting description, which previously only mentioned `s2RectContains` and `s2CapContains`. - Register `allow_experimental_s2_keycondition` and `s2_max_covering_cells` in `SettingsChangesHistory.cpp` (26.3 block) so that the `compatibility` mechanism can correctly reason about these settings across versions. - Remove two extra blank lines after the `#if USE_S2_GEOMETRY` include block. Co-Authored-By: Claude (claude-sonnet-4-6) <[email protected]>
Rename the setting and test file for clarity: - `allow_experimental_s2_keycondition` → `enable_s2_index_pruning` - `04042_s2_keycondition` → `04042_s2_index_pruning` Co-Authored-By: Claude (claude-sonnet-4-6) <[email protected]>
…uning` Follow-up to the setting rename: align the internal member variable name in `KeyCondition` with the new setting name `enable_s2_index_pruning`. Co-Authored-By: Claude (claude-sonnet-4-6) <[email protected]>
…ionS2.h/.cpp` Move ~200 lines of S2-specific logic out of the monolithic `KeyCondition.cpp` into a dedicated translation unit. This keeps S2 geometry headers (`s2cell_union.h`, `s2region_coverer.h`, etc.) out of `KeyCondition.cpp` and isolates the S2 parse-time analysis (`tryAnalyzeS2Covering`) and eval-time granule check (`evalS2Covering`) behind a clean interface. The `atom_map` stubs for `s2CellsIntersect`, `s2RectContains`, and `s2CapContains` are retained (returning false) because `extractAtomFromTree` gates on `atom_map` membership before reaching the S2 code path. Pure refactoring — no behavioral changes. Co-Authored-By: Claude (claude-opus-4-6) <[email protected]>
Co-Authored-By: Claude (claude-opus-4-6) <[email protected]>
…y cells Introduce a new projection index type `s2` that accelerates spatial queries on Polygon/MultiPolygon columns by rewriting polygonsIntersectSpherical and polygonsWithinSpherical predicates into s2CellsIntersect for mark-level pruning on the projection's cell_id primary key. Key changes: - ProjectionIndexS2: calculate() performs 1:N row expansion (geometry → S2 cells), tryRewriteFilterForQuery() rewrites spatial predicates for index pruning - Register S2 index in ProjectionIndexFactory - Gate S2 rewrite behind enable_s2_index_pruning setting in projectionsCommon.cpp - Stateless tests for core functionality, EXPLAIN output, and error cases
…x support New spherical geometry functions modeled after BigQuery's Geography API: - ST_Intersects: two geometries share any point - ST_Contains: geometry1 fully contains geometry2 (boundary excluded) - ST_Within: geometry1 is inside geometry2 (inverse of ST_Contains) - ST_Covers: like ST_Contains but includes boundary points - ST_CoveredBy: inverse of ST_Covers - ST_Equals: topological equality via mutual covered_by - ST_Touches: boundary-only contact, no interior overlap - ST_DWithin: distance-based proximity check (meters on sphere) - ST_IntersectsBox: geometry intersects lon/lat bounding box All functions support Point, Ring, Polygon, and MultiPolygon in spherical coordinates. All spatial predicates are integrated with ProjectionIndexS2 for S2-based mark pruning, including ST_DWithin (with distance-expanded ancestor cell) and ST_IntersectsBox (with box-to-polygon conversion).
Add Point, Ring, LineString, and MultiLineString column support to ProjectionIndexS2, which previously only supported Polygon and MultiPolygon. Point columns map to a single S2 cell at max_level, while Ring/LineString/MultiLineString use bounding-box coverings like Polygon/MultiPolygon.
- expandAncestorByDistance: go two S2 levels coarser instead of one, providing 4x safety margin when query geometry is near a cell edge, preventing false negatives for ST_DWithin queries. - calculate(): emit all 6 face-level (level 0) S2 cells for rows that fail geometry decoding or S2 covering, ensuring such rows are never pruned by the projection index (previously silently dropped). - haversineDistance: clamp intermediate value h to [0, 1] before asin(sqrt(h)) to prevent NaN for nearly-antipodal points due to floating-point rounding. - Fix empty reference file for 04045_projection_index_s2_errors test.
The Geometry type is Variant(LineString, MultiLineString, MultiPolygon, Point, Polygon, Ring) — a per-row union of all 6 geometry types. For Geometry columns, each nested variant column is decoded separately using its type-specific converter, and the ColumnVariant global discriminator is used at row level to dispatch to the correct decoded geometry vector. Uses globalDiscriminatorAt() and localDiscriminatorByGlobal() to correctly handle non-identity local/global discriminator mappings. NULL geometries emit face-level cells (never pruned). Global discriminator mapping (sorted alphabetically by DataTypeVariant): 0=LineString, 1=MultiLineString, 2=MultiPolygon, 3=Point, 4=Polygon, 5=Ring, 255=NULL
…jectionIndexS2 Previously, Nullable geometry columns (e.g. Nullable(Point)) silently produced empty projection data because prepareGeometryDecodeCache() compared types without unwrapping Nullable. Also, non-geometry column types (e.g. String, UInt64) were silently accepted at CREATE TABLE time and only failed at INSERT or produced empty projections. Now: - Unwrap Nullable in prepareGeometryDecodeCache() to correctly decode Nullable(Point), Nullable(Polygon), etc. NULL rows emit face-level S2 cells to prevent false negatives. - Validate INDEX column type in fillProjectionDescription() at DDL time, rejecting unsupported types with a clear error message. - Update tests to reflect DDL-time type validation.
Reject inverted bounding boxes (xmin > xmax or ymin > ymax) with a clear BAD_ARGUMENTS error instead of silently producing incorrect results from boost::geometry.
Avoid redundant O(N) work when geometry arguments are constant:
- Extract inner data column from ColumnConst via getDataColumnPtr()
instead of convertToFullColumnIfConst() which replicates data N times
- Convert and correct constant geometries only once, not per row
- Apply to all ST_* predicates and polygons{Within,Intersect,Equals}
Also fix missing expected output in 04046_st_intersectsbox.reference
and add const-optimization coverage to each function's test file.
…ingle `buildS2Covering` Replace the two-function try-native-then-fallback pattern at every call site with a single `buildS2Covering` that uses the best strategy per geometry kind: - Point: direct `S2CellId` at max_level (no coverer) - LineString: native `S2Polyline` covering; bounding-box fallback - MultiLineString: native `S2Polyline` per segment, union; bounding-box fallback - Ring/Polygon/MultiPolygon: `S2LatLngRect` bounding-box covering For LineString/MultiLineString, the native path now falls through internally to the bounding-box path when `S2Polyline` conversion fails, instead of returning `nullopt` and requiring the caller to call a second function. Also includes: multi-cell covering via `__s2CoveringIntersects` for tighter query pruning, native `S2Polyline` conversion helpers, `S2CellUnion::Expand` for `ST_DWithin` distance buffer, and unconstrained covering levels for query rewrite. Co-Authored-By: Claude (claude-opus-4-6) <[email protected]>
This file was missed in the previous commit. It implements the `__s2CoveringIntersects(cell_id, Array(UInt64))` function that checks whether a single S2 cell intersects any cell in a covering array. Used by `ProjectionIndexS2` query rewrite to pass the full multi-cell covering to `KeyCondition`. Co-Authored-By: Claude (claude-opus-4-6) <[email protected]>
- Unify `addRingToRect` and `addLineStringToRect` into `addPointsToRect<T>` - Extract `makeCoverer` and `getCovering` helpers to remove repeated `S2RegionCoverer::Options` setup in `buildS2Covering` - Extract `computeBoundingRect` using `std::visit` to replace 5-way if/else chain in the bounding-box path - Reuse `boostPointToS2Point` in Point path of `buildS2Covering` - Deduplicate `prepareGeometryDecodeCache` with `tryDecodeTypedColumn` - Deduplicate `tryDecodeGeometry` with `std::visit` on decoded variant - Deduplicate `decodeGeometryFromField` with `tryDecodeFieldAsType` Net effect: ~120 lines removed, all repetitive dispatch patterns replaced with template helpers or `std::visit`, all tests pass. Co-Authored-By: Claude (claude-opus-4-6) <[email protected]>
…hing Two changes to `ProjectionIndexS2`: 1. Replace `S2LatLngRect` bounding-box coverings with native `S2Polygon` for Ring, Polygon, and MultiPolygon geometry types. This produces significantly tighter S2 cell coverings, reducing false positives during projection index pruning. Added `tryConvertRingToS2Loop` and `tryConvertPolygonToS2Polygon` conversion helpers that handle boost::geometry winding order conventions (CW outer, CCW inner) → S2 conventions (CCW outer via `S2Loop::Normalize`, CW inner via `Invert`). Falls back to bounding-box when S2Polygon construction fails. Added missing `s2incident_edge_tracker.cc` and `s2index_cell_data.cc` to the S2 CMake build to resolve `S2Polygon` linker errors. 2. Fix geometry type misidentification in `tryDecodeFieldAsType` and `tryDecodeTypedColumn`: Polygon was decoded as MultiLineString because both share identical underlying structure (`Array(Array(Point))`). Changed from `DataTypeFactory::get(name)->equals(*type)` (structural comparison) to `type->getCustomName()->getName()` (custom name comparison) to correctly distinguish them. Co-Authored-By: Claude (claude-haiku-4-5) <[email protected]>
Two improvements to the S2 projection index PREWHERE filtering:
1. **Optimize `__s2CoveringIntersects` function** (`s2CoveringIntersects.cpp`):
- Parse constant Array(UInt64) covering once into sorted `S2CellUnion`
- Use binary search O(log N) instead of linear scan O(N) per row
- Cache last matched covering cell: consecutive rows (sorted by Hilbert)
often fall in same cell range, turning matches into O(1)
- Remove slow path that was never reachable (function only emitted
internally with constant covering)
2. **Fix face cell handling** (both files):
- Face cells (level 0) have Hilbert ranges spanning entire cube faces
- Their cell_id sort position far from range_min caused binary search
to miss valid intersections, creating false negatives
- In `KeyConditionS2::coveringIntersectsRange`: detect face cells in
granule endpoints, conservatively return true (don't skip granule)
- In `s2CoveringIntersects::executeImpl`: handle face cells separately,
check if any covering cell shares same face (O(N) scan), don't cache
face cells to avoid polluting subsequent rows
Result: Fixes missing face cell rows while maintaining O(log N) performance
for normal cells in sorted data.
Co-Authored-By: Claude (claude-haiku-4-5) <[email protected]>
When a Point geometry fails to build an S2 covering (due to invalid coordinates like NaN or out-of-range values), do not insert face cells. Invalid points cannot match any spatial query, so face cells are unnecessary and would only pollute the projection's granule ranges, increasing false positives during mark-level pruning. Non-point geometries (Ring, Polygon, etc.) still get face cells when covering construction fails, as the failure may be due to degeneracy (e.g., self-intersection) rather than invalid coordinates. Co-Authored-By: Claude (claude-opus-4-6) <[email protected]>
…o geo* prefix - Rename `st*.cpp` to `geo*.cpp` for all 7 spatial predicate functions: `geoWithin`, `geoContains`, `geoCoveredBy`, `geoCovers`, `geoEquals`, `geoIntersects`, `geoTouches` - Templatize each function class on `Point` type to support both `CartesianPoint` and `SphericalPoint`, following the pattern of `polygonsWithinCartesian`/`polygonsWithinSpherical` - Register named functions `geo*Cartesian` and `geo*Spherical`; keep all `ST_*` names as case-insensitive aliases for the Cartesian variants - Add `geoContainsCartesian`, `geoContainsSpherical`, `geoCoveredByCartesian`, `geoCoveredBySpherical`, `geoCoversCartesian`, `geoCoversSpherical`, `geoEqualsCartesian`, `geoEqualsSpherical`, `geoIntersectsCartesian`, `geoIntersectsSpherical`, `geoTouchesCartesian`, `geoTouchesSpherical` to `supported_two_arg_functions` in `ProjectionIndexS2.cpp` so they can benefit from S2 projection index pruning - Rename test files `04046_st_*.sql` to `04046_geo_*.sql` and update them to exercise both `geo*Cartesian` and `geo*Spherical` variants, including alias correctness checks Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
…stem Replace static `registerAlias` with dynamic `factory.registerFunction` for all 7 ST_* functions: `ST_Within`, `ST_Contains`, `ST_CoveredBy`, `ST_Covers`, `ST_Equals`, `ST_Intersects`, `ST_Touches`. Each ST_* function now reads `st_function_use_spherical` (default: true) at query planning time and dispatches to the corresponding `geo*Spherical` or `geo*Cartesian` implementation. The default (spherical) is consistent with BigQuery's ST_* semantics. The explicit `geo*Cartesian` and `geo*Spherical` variants are not affected by this setting. Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
…on_index # Please enter a commit message to explain why this merge is necessary, # especially if it merges an updated upstream into a topic branch. # # Lines starting with '#' will be ignored, and an empty message aborts # the commit.
| /// if the predicate is true, the geometries must have spatial overlap, | ||
| /// so S2 cell intersection is a necessary condition (no false negatives). | ||
| static const std::unordered_set<std::string> supported_two_arg_functions = { | ||
| "polygonsIntersectCartesian", |
There was a problem hiding this comment.
tryRewriteFilterForQuery currently includes Cartesian predicates in supported_two_arg_functions (for example geoContainsCartesian, geoIntersectsCartesian) and rewrites them to __s2CoveringIntersects using S2 spherical coverings.
That rewrite is only sound for spherical semantics. For Cartesian predicates, S2 coverings are not a guaranteed necessary condition, so projection pruning can drop marks that still contain rows where the Cartesian predicate is true (false negatives).
Please restrict this rewrite path to spherical predicates only (and keep Cartesian variants unrewritten), or add a proof-backed conservative mapping for Cartesian semantics.
…on_index # Please enter a commit message to explain why this merge is necessary, # especially if it merges an updated upstream into a topic branch. # # Lines starting with '#' will be ignored, and an empty message aborts # the commit.
- restrict projection rewrite to spherical predicates only\n- support wrapped longitude ranges in and index rewrite geometry construction\n- keep invalid box fallback conservative by skipping rewrite when bounds are unusable
| if (params.source_column.empty()) | ||
| throw Exception(ErrorCodes::INCORRECT_QUERY, "ProjectionIndexS2 source column is empty"); | ||
|
|
||
| if (params.max_cells == 0) |
There was a problem hiding this comment.
max_cells is parsed as UInt64, but later it is narrowed to int (covering_options.max_cells = static_cast<int>(params.max_cells) in both rewrite and calculate). Right now values greater than INT_MAX pass validation and then overflow during that cast, which can make S2RegionCoverer::Options::set_max_cells receive an invalid negative value.
Please reject oversized values in validateParams (for example max_cells <= std::numeric_limits<int>::max()), so invalid TYPE s2(max_cells=...) is rejected at DDL time instead of failing unpredictably during reads/inserts.
LLVM Coverage Report
Changed lines: 82.18% (2425/2951) | lost baseline coverage: 2 line(s) · Uncovered code |
…on_index Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. - retargeted PR record [email protected] to 26.10 (settings-history check rule) - retargeted PR record [email protected] to 26.10 (settings-history check rule) - retargeted PR record [email protected] to 26.10 (settings-history check rule) - semantic merge fixes in non-conflicting files: src/Functions/geoContains.cpp, src/Functions/geoCoveredBy.cpp, src/Functions/geoCovers.cpp, src/Functions/geoEquals.cpp, src/Functions/geoIntersectsBox.cpp, src/Functions/geoToS2Cells.cpp, src/Functions/geoTouches.cpp, src/Functions/geoWithin.cpp, src/Storages/MergeTree/ProjectionIndex/ProjectionIndexS2.cpp, src/Storages/MergeTree/ProjectionIndex/ProjectionIndexS2.h Also resolved conflicts in: - `src/Functions/CMakeLists.txt` - `src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp` - `src/Storages/MergeTree/KeyCondition.cpp` - `src/Storages/MergeTree/KeyCondition.h` Ported to master's APIs: the 6th `fillProjectionDescription` parameter, `VectorWithMemoryTracking` geometry types, the new `ActionsDAG::addColumn` signature, the per-atom `relaxed` flag and the sparse `checkInHyperrectangle`. The S2 functions reject master's new `MultiPoint` type with `ILLEGAL_TYPE_OF_ARGUMENT`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…on_index Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| col.type->getName()); | ||
| } | ||
|
|
||
| result.type = ProjectionDescription::Type::Normal; |
There was a problem hiding this comment.
[Blocker] Keep generated S2 columns out of ordinary projection planning
The generated cell_id shares the namespace of ordinary parent columns, and this projection is registered as Type::Normal. A parent table with (id UInt64, cell_id UInt64, g Point, PROJECTION s INDEX g TYPE s2) is accepted. After inserting (1, 42, (0, 0)), SELECT id FROM t WHERE cell_id = 42 SETTINGS optimize_use_projections = 1, optimize_use_projection_filtering = 1 can discard the matching parent part: no geometry rewrite exists, so filterPartsAndCollectProjectionCandidates analyzes the original equality against the generated S2 identifiers instead of the parent's 42. This also happens with enable_s2_index_pruning = 0.
Use an isolated internal column namespace and keep this derived index out of ordinary projection reads/filtering; it should enter filtering only with a successfully rewritten geometry predicate. Add a regression with a real parent cell_id column and S2 pruning disabled.
| auto it = std::lower_bound( | ||
| covering.begin(), covering.end(), cell_min, | ||
| [](S2CellId a, S2CellId b) { return a.range_max() < b.range_min(); }); | ||
| return it != covering.end() | ||
| && it->range_min() <= cell_max.range_max(); |
There was a problem hiding this comment.
[Blocker] Include interior ancestor cells in the granule's spatial range
The endpoint ranges do not bound all cells inside a numerically sorted interval when cell levels differ. With ORDER BY cell_id, index_granularity = 3, and sorted identifiers [1152921504606846975, 1152921504606846976, 1152921504606846977, 1152921504606846979], the first granule has leaf endpoints but contains face zero (1152921504606846976). s2CellsIntersect(cell_id, toUInt64(1)) must match that face row. Here lower_bound skips the singleton covering {1}, pruning the matching granule. Testing only whether an endpoint is a face cell misses this case; interior ancestors at other levels have the same problem.
Compute a conservative spatial bound for every possible cell in the numeric interval, or enforce a uniform-level invariant before using this algorithm. Cover mixed-level identifiers and interior fallback face cells in a regression test.
| auto make_polygon = [](Float64 box_xmin, Float64 box_ymin, Float64 box_xmax, Float64 box_ymax) | ||
| { | ||
| SphericalPolygon polygon; | ||
| polygon.outer().emplace_back(box_xmin, box_ymin); | ||
| polygon.outer().emplace_back(box_xmax, box_ymin); | ||
| polygon.outer().emplace_back(box_xmax, box_ymax); | ||
| polygon.outer().emplace_back(box_xmin, box_ymax); | ||
| polygon.outer().emplace_back(box_xmin, box_ymin); | ||
| boost::geometry::correct(polygon); |
There was a problem hiding this comment.
[Blocker] Cover the longitude/latitude box instead of its corner polygon
geoIntersectsBoxSpherical tests a longitude/latitude rectangle, but these corners become an S2 polygon with great-circle edges. For example, geoIntersectsBoxSpherical(CAST((45., 61.), 'Point'), 0., 60., 90., 70.) is true. The polygon constructed here has its lower edge at approximately latitude 67.79 at longitude 45, so it excludes that point. With a sufficiently fine covering, such as an index configured with min_level = 8, max_level = 20, the rewritten predicate can prune this matching row.
Build the query covering from an S2LatLngRect representing the same box, including wrapped longitude intervals. Add an executed pruning-on/off comparison at a nonzero latitude; the current near-equatorial fixtures do not establish this invariant.
| String source_column; /// The geometry column to index (Point/Ring/LineString/MultiLineString/Polygon/MultiPolygon/Geometry, or Nullable). | ||
|
|
||
| UInt64 max_cells = 8; /// Maximum number of S2 cells in the covering. | ||
| UInt64 min_level = 16; /// Minimum S2 cell level (0 = coarsest, 30 = finest). |
There was a problem hiding this comment.
[Blocker] Avoid forcing level-16 enumeration with the default index parameters
S2RegionCoverer gives min_level priority over max_cells, so the default eight-cell budget does not bound this work. Both insertion and query rewriting pass this default to the coverer. A valid polygon with corners [(-50,-40), (50,-40), (50,40), (-50,40), (-50,-40)] contains an entire S2 cube face, forcing at least 4^16 = 4,294,967,296 level-16 cells before normalization: 32 GiB of raw cell identifiers, plus the covering work and other allocations. Even a query against an indexed point column can trigger this from a small constant polygon.
Use an adaptive coarse default, such as min_level = 0, consistently with S2CoveringOptions, and bound covering work. Add a focused case using the default parameters and an ordinary large-area polygon.
| { | ||
| registerProjectionIndex<ProjectionIndexBasic>(); | ||
| registerProjectionIndex<ProjectionIndexCommitOrder>(); | ||
| registerProjectionIndex<ProjectionIndexS2>(); |
There was a problem hiding this comment.
[Blocker] Gate the new S2 index behind an experimental opt-in
The index is registered unconditionally, and neither create nor fillProjectionDescription checks an experimental setting. Consequently TYPE s2 can be created and maintained during inserts with every setting at its default. enable_s2_index_pruning only controls read optimization and is itself registered with flags 0, so it does not gate the new storage/index behavior.
Add an experimental gate for fresh index creation and use, with appropriate handling for loading existing metadata. This also implements the maintainer's explicit requirement and the author's agreement.
| if constexpr (left_is_point && right_is_point) | ||
| return haversineDistance(a, b); | ||
| else | ||
| return boost::geometry::distance(a, b) * EARTH_RADIUS_METERS; |
There was a problem hiding this comment.
[Major] Return false for empty geometries before computing distance
ST_DWithin(CAST([], 'Polygon'), CAST((0., 0.), 'Point'), 100.) reaches boost::geometry::distance, whose throw_on_empty_input raises empty_input_exception. One empty geometry therefore fails the whole query instead of returning false, contrary to the advertised BigQuery ST_DWITHIN semantics.
Handle either empty input before distance computation in both coordinate variants, and cover both argument orders with constant and column inputs.
|
|
||
| SET enable_s2_index_pruning = 1; | ||
| SET optimize_use_projections = 1; | ||
| SET optimize_use_projection_filtering = 1; |
There was a problem hiding this comment.
[Major] Execute the row-level projection filter in the correctness tests
These fixtures contain at most five rows, but actual result assertions retain the default min_table_rows_to_use_projection_index = 1000000. They can exercise whole-part pruning, but cannot enter the rewritten projection PREWHERE and _parent_part_offset bitmap path in projectionsCommon.cpp. The override appears only in EXPLAIN, which does not execute that path.
Set min_table_rows_to_use_projection_index = 0 for an executed pruning-on/off comparison using matching and nonmatching rows in the same parent part. Assert the returned IDs, including reordered source rows and overlapping coverings, so the new row-level filtering and offset mapping are validated.
ClickHouse has basic S2 cell functions but lacks real spatial predicate support
(within, contains, intersects, etc.) and has no way to accelerate spatial queries
using an index. This adds both.
New spatial predicate functions:
geoWithin,geoContains,geoCoveredBy,geoCovers,geoDWithin,geoEquals,geoIntersects,geoIntersectsBox,geoTouches— each with explicit Cartesian/Spherical variants plusBigQuery-compatible
ST_*aliases. Thest_function_use_sphericalsettingcontrols whether
ST_*functions use spherical (default, matching BigQuery) orCartesian coordinates.
New
s2projection index type accelerates spatial queries on geometry columns.During INSERT, geometries are decomposed into S2 cell coverings stored as a
sorted projection. At query time, spatial predicates are rewritten to
__s2CoveringIntersectswhich usesKeyConditionto prune granules viabinary search over the S2 cell union's Hilbert-curve intervals.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add spatial predicate functions (
geoWithin,geoContains,geoIntersects,geoDWithin, etc.) with Cartesian/Spherical variants and BigQuery-compatibleST_*aliases. Add
s2projection index type that accelerates spatial queries on geometry columns using S2 cell coverings. New settings:enable_s2_index_pruning,s2_max_covering_cells,st_function_use_spherical.Documentation entry for user-facing changes
Want me to create the PR with this description, or would you like to adjust anything?
Workflow [PR]
Sync PR [sync-upstream/pr/102485]