nitrite_spatial 0.3.1

Spatial indexing support for Nitrite database using R-Tree
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
use std::{path::PathBuf, sync::Arc};

use nitrite::{
    collection::{FindPlan, NitriteId},
    common::{FieldValues, Value},
    errors::{ErrorKind, NitriteError, NitriteResult},
    index::IndexDescriptor,
    nitrite_config::NitriteConfig,
};

use crate::{
    filter::{as_spatial_filter, is_spatial_filter, value_to_geometry, KNearestFilter},
    BoundingBox, DiskRTree, Geometry, IntersectsFilter, NitriteRTree, WithinFilter,
    NearFilter, GeoNearFilter,
};

/// A spatial index instance for a specific field.
/// Uses Pimpl pattern for cheap cloning and encapsulation.
#[derive(Clone)]
pub struct SpatialIndex {
    inner: Arc<SpatialIndexInner>,
}

/// Private implementation details of SpatialIndex.
struct SpatialIndexInner {
    index_descriptor: IndexDescriptor,
    rtree: Arc<dyn NitriteRTree>,
    collection_name: String,
}

impl SpatialIndex {
    pub fn new(index_descriptor: IndexDescriptor, base_path: Option<PathBuf>) -> NitriteResult<Self> {
        let index_name = derive_index_map_name(&index_descriptor);
        let collection_name = index_descriptor.collection_name().to_string();

        // Determine the path for the R-tree file
        let rtree_path = if let Some(base) = &base_path {
            base.join(format!("{}.rtree", index_name))
        } else {
            // Use a temp directory for in-memory mode
            std::env::temp_dir().join(format!("nitrite_{}.rtree", index_name))
        };

        // Create or open the R-tree
        let rtree = if rtree_path.exists() {
            log::debug!("Opening existing spatial index at {:?}", rtree_path);
            DiskRTree::open(&rtree_path).map_err(|e| {
                NitriteError::new(
                    &format!("Failed to open spatial index: {}", e),
                    ErrorKind::Extension("spatial".to_string()),
                )
            })?
        } else {
            log::debug!("Creating new spatial index at {:?}", rtree_path);
            DiskRTree::create(&rtree_path).map_err(|e| {
                NitriteError::new(
                    &format!("Failed to create spatial index: {}", e),
                    ErrorKind::Extension("spatial".to_string()),
                )
            })?
        };

        Ok(Self {
            inner: Arc::new(SpatialIndexInner {
                index_descriptor,
                rtree: Arc::new(rtree),
                collection_name,
            }),
        })
    }

    pub fn write(&self, field_values: &FieldValues) -> NitriteResult<()> {
        let fields = field_values.fields();
        let field_names = fields.field_names();

        if field_names.is_empty() {
            return Ok(());
        }

        let first_field = &field_names[0];
        let value = field_values.get_value(first_field);
        let nitrite_id = field_values.nitrite_id().id_value();

        let bbox = match value {
            Some(v) => {
                if let Some(geom) = value_to_geometry(v) {
                    geom.bounding_box()
                } else {
                    BoundingBox::default()
                }
            }
            None => BoundingBox::default(),
        };

        self.inner.rtree.add(&bbox, nitrite_id).map_err(|e| {
            NitriteError::new(
                &format!("Failed to write to spatial index: {}", e),
                ErrorKind::Extension("spatial".to_string()),
            )
        })
    }

    pub fn remove(&self, field_values: &FieldValues) -> NitriteResult<()> {
        let fields = field_values.fields();
        let field_names = fields.field_names();

        if field_names.is_empty() {
            return Ok(());
        }

        let first_field = &field_names[0];
        let value = field_values.get_value(first_field);
        let nitrite_id = field_values.nitrite_id().id_value();

        let bbox = match value {
            Some(v) => {
                if let Some(geom) = value_to_geometry(v) {
                    geom.bounding_box()
                } else {
                    BoundingBox::default()
                }
            }
            None => BoundingBox::default(),
        };

        self.inner.rtree.remove(&bbox, nitrite_id).map_err(|e| {
            NitriteError::new(
                &format!("Failed to remove from spatial index: {}", e),
                ErrorKind::Extension("spatial".to_string()),
            )
        })?;

        Ok(())
    }

    pub fn find_nitrite_ids(
        &self,
        find_plan: &FindPlan,
        config: &NitriteConfig,
    ) -> NitriteResult<Vec<NitriteId>> {
        let index_scan_filter = find_plan
            .index_scan_filter()
            .ok_or_else(|| {
                NitriteError::new("No spatial filter found", ErrorKind::FilterError)
            })?;

        let filters = index_scan_filter.filters();
        
        if filters.is_empty() {
            return Err(NitriteError::new(
                "No spatial filter found",
                ErrorKind::FilterError,
            ));
        }

        let filter = &filters[0];
        
        if !is_spatial_filter(filter) {
            return Err(NitriteError::new(
                "Spatial filter must be the first filter for index scan",
                ErrorKind::FilterError,
            ));
        }

        // Get the search geometry from the filter
        let spatial_filter = as_spatial_filter(filter).ok_or_else(|| {
            NitriteError::new("Failed to get spatial filter", ErrorKind::FilterError)
        })?;

        // Handle KNearestFilter separately as it uses find_nearest, not find_intersecting_keys
        if let Some(knearest_filter) = filter.as_any().downcast_ref::<KNearestFilter>() {
            return self.find_knearest_nitrite_ids(knearest_filter, config);
        }

        let search_geometry = spatial_filter.geometry();
        let search_bbox = search_geometry.bounding_box();

        // Phase 1: R-tree bounding box search
        let candidate_ids = if filter.as_any().is::<WithinFilter>()
            || filter.as_any().is::<NearFilter>()
            || filter.as_any().is::<GeoNearFilter>()
        {
            // For within/near filters, find keys that intersect with the search bbox
            self.inner.rtree.find_intersecting_keys(&search_bbox)
        } else if filter.as_any().is::<IntersectsFilter>() {
            self.inner.rtree.find_intersecting_keys(&search_bbox)
        } else {
            return Err(NitriteError::new(
                &format!("Unsupported spatial filter: {}", filter),
                ErrorKind::FilterError,
            ));
        };

        let candidate_ids = candidate_ids.map_err(|e| {
            NitriteError::new(
                &format!("Failed to query spatial index: {}", e),
                ErrorKind::Extension("spatial".to_string()),
            )
        })?;

        // Phase 2: Geometry refinement
        // For precise results, we need to retrieve the actual geometry from each
        // candidate document and apply the exact spatial predicate.
        let mut results = Vec::new();

        for id in candidate_ids {
            let nitrite_id = NitriteId::create_id(id)?;

            // Try to get the stored geometry and apply precise filter
            if let Some(stored_geom) = self.get_stored_geometry(&nitrite_id, config)? {
                if spatial_filter.matches_geometry(&stored_geom) {
                    results.push(nitrite_id);
                }
            }
        }

        Ok(results)
    }

    /// Finds K nearest entries to a point using the spatial index.
    /// This method uses find_nearest from DiskRTree which performs KNN search directly.
    fn find_knearest_nitrite_ids(
        &self,
        knearest_filter: &KNearestFilter,
        _config: &NitriteConfig,
    ) -> NitriteResult<Vec<NitriteId>> {
        let center = knearest_filter.center();
        let k = knearest_filter.k();
        let max_distance = knearest_filter.max_distance();

        // Use DiskRTree's find_nearest method for KNN search
        // Note: find_nearest returns (id, distance) tuples
        let knearest_results = self
            .inner
            .rtree
            .find_nearest(center.x(), center.y(), k, max_distance)
            .map_err(|e| {
                NitriteError::new(
                    &format!("Failed to execute KNN query on spatial index: {}", e),
                    ErrorKind::Extension("spatial".to_string()),
                )
            })?;

        // Convert (id, distance) tuples to Vec<NitriteId>
        let mut results = Vec::new();
        for (id, _distance) in knearest_results {
            let nitrite_id = NitriteId::create_id(id)?;
            results.push(nitrite_id);
        }

        Ok(results)
    }

    /// Retrieves the stored geometry for a document.
    /// This is used in Phase 2 of the two-phase query for precise filtering.
    fn get_stored_geometry(
        &self,
        nitrite_id: &NitriteId,
        config: &NitriteConfig,
    ) -> NitriteResult<Option<Geometry>> {
        // Get the field from the index descriptor
        let field_names = self.inner.index_descriptor.index_fields().field_names();

        if field_names.is_empty() {
            return Ok(None);
        }

        let collection_name = &self.inner.collection_name;
        let nitrite_map = config
            .nitrite_store()
            .and_then(|store| store.open_map(collection_name))?;

        let document_opt = nitrite_map.get(&Value::NitriteId(*nitrite_id))?;

        if let Some(value) = document_opt {
            let first_field = &field_names[0];
            return match value {
                Value::Document(doc) => {
                    let geom_value = doc.get(first_field)?;
                    value_to_geometry(&geom_value).map(Some).ok_or_else(|| {
                        NitriteError::new(
                            "Failed to convert stored value to geometry",
                            ErrorKind::Extension("spatial".to_string()),
                        )
                    })
                }
                _ => Ok(None),
            };
        };

        Ok(None)
    }

   pub fn close(&self) -> NitriteResult<()> {
        self.inner.rtree.close().map_err(|e| {
            NitriteError::new(
                &format!("Failed to close spatial index: {}", e),
                ErrorKind::Extension("spatial".to_string()),
            )
        })
    }

    pub fn drop(&self) -> NitriteResult<()> {
        self.inner.rtree.drop_tree().map_err(|e| {
            NitriteError::new(
                &format!("Failed to drop spatial index: {}", e),
                ErrorKind::Extension("spatial".to_string()),
            )
        })
    }
}

/// Derives the index map name from an index descriptor.
pub(crate) fn derive_index_map_name(descriptor: &IndexDescriptor) -> String {
    let collection = descriptor.collection_name();
    let fields = descriptor.index_fields().field_names().join("_");
    let index_type = descriptor.index_type();
    format!("{}_{}_{}_{}", collection, fields, index_type, "idx")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Point, BoundingBox};

    /// Helper to create a mock IndexDescriptor with a unique collection name for testing.
    /// Uses UUID to ensure uniqueness across test runs.
    fn create_test_index_descriptor() -> IndexDescriptor {
        let uuid = uuid::Uuid::new_v4();
        let fields = nitrite::common::Fields::with_names(vec!["location"]).unwrap();
        IndexDescriptor::new("spatial", fields, &format!("test_collection_{}", uuid))
    }

    // Valid NitriteId values must be >= 10^18
    const TEST_ID_1: u64 = 1_000_000_000_000_000_001;
    const TEST_ID_2: u64 = 1_000_000_000_000_000_002;
    const TEST_ID_3: u64 = 1_000_000_000_000_000_003;

    #[test]
    fn test_knearest_filter_in_find_nitrite_ids() {
        // Create a test index
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        // Add some test entries with valid NitriteId values
        let bbox1 = BoundingBox::new(0.0, 0.0, 1.0, 1.0);
        let bbox2 = BoundingBox::new(2.0, 2.0, 3.0, 3.0);
        let bbox3 = BoundingBox::new(5.0, 5.0, 6.0, 6.0);

        index
            .inner
            .rtree
            .add(&bbox1, TEST_ID_1)
            .expect("Failed to add entry 1");
        index
            .inner
            .rtree
            .add(&bbox2, TEST_ID_2)
            .expect("Failed to add entry 2");
        index
            .inner
            .rtree
            .add(&bbox3, TEST_ID_3)
            .expect("Failed to add entry 3");

        // Create a KNearestFilter for center point (1.5, 1.5) with k=2
        let knearest = KNearestFilter::from_coords("location", 1.5, 1.5, 2)
            .expect("Failed to create KNearestFilter");

        // Call find_knearest_nitrite_ids directly
        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed to find knearest");

        // We expect to get 2 results (k=2)
        assert_eq!(results.len(), 2);

        // The two closest points should be 1 and 2 (at coordinates 0.5,0.5 and 2.5,2.5)
        // Close to (1.5, 1.5)
        let ids: Vec<u64> = results.iter().map(|id| id.id_value()).collect();
        assert!(ids.contains(&TEST_ID_1) || ids.contains(&TEST_ID_2));

        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_filter_with_max_distance() {
        // Create a test index
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        // Add test entries at different distances
        let bbox1 = BoundingBox::new(0.0, 0.0, 1.0, 1.0); // Close
        let bbox2 = BoundingBox::new(2.0, 2.0, 3.0, 3.0); // Medium
        let bbox3 = BoundingBox::new(10.0, 10.0, 11.0, 11.0); // Far

        index
            .inner
            .rtree
            .add(&bbox1, TEST_ID_1)
            .expect("Failed to add entry 1");
        index
            .inner
            .rtree
            .add(&bbox2, TEST_ID_2)
            .expect("Failed to add entry 2");
        index
            .inner
            .rtree
            .add(&bbox3, TEST_ID_3)
            .expect("Failed to add entry 3");

        // Create a KNearestFilter with max_distance constraint
        let knearest = KNearestFilter::with_max_distance("location", Point::new(0.5, 0.5), 10, 5.0)
            .expect("Failed to create KNearestFilter");

        // Call find_knearest_nitrite_ids
        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed to find knearest");

        // Should get results within max_distance, not the far one
        let ids: Vec<u64> = results.iter().map(|id| id.id_value()).collect();
        assert!(!ids.contains(&TEST_ID_3), "Should not include entry 3 (too far away)");

        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_filter_k_equals_one() {
        // Create a test index
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        // Add test entries - place them at very different distances
        // bbox1 center is at (0.5, 0.5), bbox2 center is at (10.5, 10.5), bbox3 center is at (100.5, 100.5)
        let bbox1 = BoundingBox::new(0.0, 0.0, 1.0, 1.0);
        let bbox2 = BoundingBox::new(10.0, 10.0, 11.0, 11.0);
        let bbox3 = BoundingBox::new(100.0, 100.0, 101.0, 101.0);

        index
            .inner
            .rtree
            .add(&bbox1, TEST_ID_1)
            .expect("Failed to add entry 1");
        index
            .inner
            .rtree
            .add(&bbox2, TEST_ID_2)
            .expect("Failed to add entry 2");
        index
            .inner
            .rtree
            .add(&bbox3, TEST_ID_3)
            .expect("Failed to add entry 3");

        // Create a KNearestFilter with k=1 (find nearest single entry)
        // Query at (0.5, 0.5) which is the center of bbox1 - distance should be 0
        let knearest = KNearestFilter::from_coords("location", 0.5, 0.5, 1)
            .expect("Failed to create KNearestFilter");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed to find knearest");

        // Should get exactly 1 result
        assert_eq!(results.len(), 1);

        // The closest point should be bbox1 since the query point is at its center
        // bbox1 contains point (0.5, 0.5), so distance is 0
        // bbox2 is 10 units away, bbox3 is 100 units away
        let id = results[0].id_value();
        assert_eq!(id, TEST_ID_1, "Expected bbox1 (at 0,0,1,1) to be closest to query point (0.5, 0.5)");

        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_filter_k_greater_than_entries() {
        // Create a test index
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        // Add only 2 entries
        let bbox1 = BoundingBox::new(0.0, 0.0, 1.0, 1.0);
        let bbox2 = BoundingBox::new(2.0, 2.0, 3.0, 3.0);

        index
            .inner
            .rtree
            .add(&bbox1, TEST_ID_1)
            .expect("Failed to add entry 1");
        index
            .inner
            .rtree
            .add(&bbox2, TEST_ID_2)
            .expect("Failed to add entry 2");

        // Request k=5 (more than available entries)
        let knearest = KNearestFilter::from_coords("location", 1.5, 1.5, 5)
            .expect("Failed to create KNearestFilter");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed to find knearest");

        // Should get all 2 available entries (not 5)
        assert_eq!(results.len(), 2);

        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_filter_empty_index() {
        // Create a test index
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        // Don't add any entries

        // Create a KNearestFilter
        let knearest = KNearestFilter::from_coords("location", 0.0, 0.0, 5)
            .expect("Failed to create KNearestFilter");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed to find knearest");

        // Should get 0 results from empty index
        assert_eq!(results.len(), 0);

        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_derive_index_map_name() {
        let descriptor = create_test_index_descriptor();
        let name = derive_index_map_name(&descriptor);
        
        // Check that the name contains all expected components
        assert!(name.contains("test_collection"));
        assert!(name.contains("location"));
        assert!(name.contains("spatial"));
        assert!(name.contains("idx"));
    }

    #[test]
    fn test_derive_index_map_name_format() {
        // Use a hardcoded descriptor for format testing
        let fields = nitrite::common::Fields::with_names(vec!["location"]).unwrap();
        let descriptor = IndexDescriptor::new("spatial", fields, "my_collection");
        let name = derive_index_map_name(&descriptor);
        
        // Verify the format: collection_fields_type_idx
        assert_eq!(name, "my_collection_location_spatial_idx");
    }

    // ===== POSITIVE TEST CASES =====
    #[test]
    fn test_spatial_index_clone() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");
        let _cloned = index.clone();
        assert_eq!(
            index.inner.collection_name,
            _cloned.inner.collection_name
        );
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_multiple_entries_sorted() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox1 = BoundingBox::new(0.0, 0.0, 1.0, 1.0);
        let bbox2 = BoundingBox::new(5.0, 5.0, 6.0, 6.0);
        let bbox3 = BoundingBox::new(10.0, 10.0, 11.0, 11.0);

        index.inner.rtree.add(&bbox1, TEST_ID_1).expect("Failed");
        index.inner.rtree.add(&bbox2, TEST_ID_2).expect("Failed");
        index.inner.rtree.add(&bbox3, TEST_ID_3).expect("Failed");

        let knearest = KNearestFilter::from_coords("location", 0.5, 0.5, 3)
            .expect("Failed to create KNearestFilter");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 3);
        assert_eq!(results[0].id_value(), TEST_ID_1);
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_intersects_filter_finds_matching() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox = BoundingBox::new(0.0, 0.0, 10.0, 10.0);
        index
            .inner
            .rtree
            .add(&bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let _intersects = IntersectsFilter::new("location", Geometry::point(5.0, 5.0));
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_within_filter_finds_contained() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox = BoundingBox::new(2.0, 2.0, 3.0, 3.0);
        index
            .inner
            .rtree
            .add(&bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let _within = WithinFilter::new("location", Geometry::circle(2.5, 2.5, 5.0));
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_k_one_multiple_entries() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox1 = BoundingBox::new(0.0, 0.0, 1.0, 1.0);
        let bbox2 = BoundingBox::new(100.0, 100.0, 101.0, 101.0);
        let bbox3 = BoundingBox::new(200.0, 200.0, 201.0, 201.0);

        index.inner.rtree.add(&bbox1, TEST_ID_1).expect("Failed");
        index.inner.rtree.add(&bbox2, TEST_ID_2).expect("Failed");
        index.inner.rtree.add(&bbox3, TEST_ID_3).expect("Failed");

        let knearest = KNearestFilter::from_coords("location", 0.0, 0.0, 1)
            .expect("Failed to create KNearestFilter");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].id_value(), TEST_ID_1);
        index.drop().expect("Failed to drop index");
    }

    // ===== NEGATIVE TEST CASES =====
    #[test]
    fn test_knearest_zero_max_distance() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox = BoundingBox::new(5.0, 5.0, 6.0, 6.0);
        index
            .inner
            .rtree
            .add(&bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let knearest = KNearestFilter::with_max_distance(
            "location",
            crate::Point::new(0.0, 0.0),
            10,
            0.0,
        )
        .expect("Failed");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 0);
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_far_away_location() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox = BoundingBox::new(0.0, 0.0, 1.0, 1.0);
        index
            .inner
            .rtree
            .add(&bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let knearest = KNearestFilter::with_max_distance(
            "location",
            crate::Point::new(1000.0, 1000.0),
            10,
            0.1,
        )
        .expect("Failed");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 0);
        index.drop().expect("Failed to drop index");
    }

    // ===== EDGE CASES =====
    #[test]
    fn test_derive_multiple_fields() {
        let fields = nitrite::common::Fields::with_names(vec!["location", "geometry"])
            .expect("Failed to create fields");
        let descriptor = IndexDescriptor::new("spatial", fields, "my_collection");
        let name = derive_index_map_name(&descriptor);
        
        assert!(name.contains("location"));
        assert!(name.contains("geometry"));
        assert!(name.contains("spatial"));
        assert!(name.contains("idx"));
    }

    #[test]
    fn test_knearest_boundary_max_distance() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox = BoundingBox::new(5.0, 5.0, 6.0, 6.0);
        index
            .inner
            .rtree
            .add(&bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let knearest = KNearestFilter::with_max_distance(
            "location",
            crate::Point::new(0.0, 0.0),
            10,
            7.1,
        )
        .expect("Failed");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 1);
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_negative_coordinates() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox = BoundingBox::new(-10.0, -10.0, -5.0, -5.0);
        index
            .inner
            .rtree
            .add(&bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let knearest = KNearestFilter::from_coords("location", -7.5, -7.5, 1)
            .expect("Failed");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].id_value(), TEST_ID_1);
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_very_large_coordinates() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox = BoundingBox::new(1_000_000.0, 1_000_000.0, 1_000_001.0, 1_000_001.0);
        index
            .inner
            .rtree
            .add(&bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let knearest = KNearestFilter::from_coords("location", 1_000_000.5, 1_000_000.5, 1)
            .expect("Failed");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 1);
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_tiny_coordinates() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox = BoundingBox::new(0.00001, 0.00001, 0.00002, 0.00002);
        index
            .inner
            .rtree
            .add(&bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let knearest = KNearestFilter::from_coords("location", 0.000015, 0.000015, 1)
            .expect("Failed");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 1);
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_collection_name_matches_descriptor() {
        let descriptor = create_test_index_descriptor();
        let collection_name = descriptor.collection_name().to_string();
        
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");
        
        assert_eq!(index.inner.collection_name, collection_name);
        
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_identical_distance_entries() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let bbox1 = BoundingBox::new(5.0, 10.0, 6.0, 11.0);
        let bbox2 = BoundingBox::new(10.0, 5.0, 11.0, 6.0);
        let bbox3 = BoundingBox::new(0.0, 5.0, 1.0, 6.0);
        let bbox4 = BoundingBox::new(5.0, 0.0, 6.0, 1.0);

        index.inner.rtree.add(&bbox1, TEST_ID_1).expect("Failed");
        index.inner.rtree.add(&bbox2, TEST_ID_2).expect("Failed");
        index.inner.rtree.add(&bbox3, TEST_ID_3).expect("Failed");
        index
            .inner
            .rtree
            .add(&bbox4, 1_000_000_000_000_000_004)
            .expect("Failed");

        let knearest = KNearestFilter::from_coords("location", 5.0, 5.0, 2)
            .expect("Failed");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 2);
        index.drop().expect("Failed to drop index");
    }

    #[test]
    fn test_knearest_large_bbox() {
        let descriptor = create_test_index_descriptor();
        let index = SpatialIndex::new(descriptor, None).expect("Failed to create index");

        let large_bbox = BoundingBox::new(-1000.0, -1000.0, 1000.0, 1000.0);
        index
            .inner
            .rtree
            .add(&large_bbox, TEST_ID_1)
            .expect("Failed to add entry");

        let knearest = KNearestFilter::from_coords("location", 0.0, 0.0, 1)
            .expect("Failed");

        let results = index
            .find_knearest_nitrite_ids(&knearest, &NitriteConfig::new())
            .expect("Failed");

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].id_value(), TEST_ID_1);
        index.drop().expect("Failed to drop index");
    }
}