Kontinuation commented on code in PR #277: URL: https://github.com/apache/sedona-db/pull/277#discussion_r2501691512
########## rust/sedona-spatial-join/src/index/spatial_index.rs: ########## @@ -0,0 +1,1487 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, +}; + +use arrow_array::RecordBatch; +use arrow_schema::SchemaRef; +use datafusion_common::Result; +use datafusion_execution::memory_pool::{MemoryPool, MemoryReservation}; +use geo_index::rtree::distance::{DistanceMetric, GeometryAccessor}; +use geo_index::rtree::{sort::HilbertSort, RTree, RTreeBuilder, RTreeIndex}; +use geo_index::IndexableNum; +use geo_types::{Point, Rect}; +use parking_lot::Mutex; +use sedona_expr::statistics::GeoStatistics; +use sedona_geo::to_geo::item_to_geometry; +use sedona_geo_generic_alg::algorithm::Centroid; +use wkb::reader::Wkb; + +use crate::{ + collect::BuildSideBatch, + index::{ + knn_adapter::{KnnComponents, SedonaKnnAdapter}, + IndexQueryResult, QueryResultMetrics, + }, + operand_evaluator::{create_operand_evaluator, OperandEvaluator}, + refine::{create_refiner, IndexQueryResultRefiner}, + spatial_predicate::SpatialPredicate, + utils::concurrent_reservation::ConcurrentReservation, +}; +use arrow::array::BooleanBufferBuilder; +use sedona_common::{option::SpatialJoinOptions, ExecutionMode}; + +pub(crate) struct SpatialIndex { + schema: SchemaRef, + + /// The spatial predicate evaluator for the spatial predicate. + evaluator: Arc<dyn OperandEvaluator>, + + /// The refiner for refining the index query results. + refiner: Arc<dyn IndexQueryResultRefiner>, + + /// Memory reservation for tracking the memory usage of the refiner + refiner_reservation: ConcurrentReservation, + + /// R-tree index for the geometry batches. It takes MBRs as query windows and returns + /// data indexes. These data indexes should be translated using `data_id_to_batch_pos` to get + /// the original geometry batch index and row index, or translated using `prepared_geom_idx_vec` + /// to get the prepared geometries array index. + rtree: RTree<f32>, + + /// Indexed batches containing evaluated geometry arrays. It contains the original record + /// batches and geometry arrays obtained by evaluating the geometry expression on the build side. + indexed_batches: Vec<BuildSideBatch>, + /// An array for translating rtree data index to geometry batch index and row index + data_id_to_batch_pos: Vec<(i32, i32)>, + + /// An array for translating rtree data index to consecutive index. Each geometry may be indexed by + /// multiple boxes, so there could be multiple data indexes for the same geometry. A mapping for + /// squashing the index makes it easier for persisting per-geometry auxiliary data for evaluating + /// the spatial predicate. This is extensively used by the spatial predicate evaluators for storing + /// prepared geometries. + geom_idx_vec: Vec<usize>, + + /// Shared bitmap builders for visited left indices, one per batch + visited_left_side: Option<Mutex<Vec<BooleanBufferBuilder>>>, + + /// Counter of running probe-threads, potentially able to update `bitmap`. + /// Each time a probe thread finished probing the index, it will decrement the counter. + /// The last finished probe thread will produce the extra output batches for unmatched + /// build side when running left-outer joins. See also [`report_probe_completed`]. + probe_threads_counter: AtomicUsize, + + /// Shared KNN components (distance metrics and geometry cache) for efficient KNN queries + knn_components: KnnComponents, + + /// Memory reservation for tracking the memory usage of the spatial index + /// Cleared on `SpatialIndex` drop + #[expect(dead_code)] + reservation: MemoryReservation, +} + +impl SpatialIndex { + pub fn empty( + spatial_predicate: SpatialPredicate, + schema: SchemaRef, + options: SpatialJoinOptions, + probe_threads_counter: AtomicUsize, + mut reservation: MemoryReservation, + memory_pool: Arc<dyn MemoryPool>, + ) -> Self { + let evaluator = create_operand_evaluator(&spatial_predicate, options.clone()); + let refiner = create_refiner( + options.spatial_library, + &spatial_predicate, + options.clone(), + 0, + GeoStatistics::empty(), + ); + let refiner_reservation = reservation.split(0); + let refiner_reservation = ConcurrentReservation::try_new(0, refiner_reservation).unwrap(); + let rtree = RTreeBuilder::<f32>::new(0).finish::<HilbertSort>(); + Self { + schema, + evaluator, + refiner, + refiner_reservation, + rtree, + data_id_to_batch_pos: Vec::new(), + indexed_batches: Vec::new(), + geom_idx_vec: Vec::new(), + visited_left_side: None, + probe_threads_counter, + knn_components: KnnComponents::new(0, &[], memory_pool.clone()).unwrap(), // Empty index has no cache + reservation, + } + } + + #[allow(clippy::too_many_arguments)] + pub fn new( Review Comment: Dropped this new() call and marked all fields as `pub(crate)` to be accessible in spatial_index_builder.rs. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
