0
# Core Indexing Operations
1
2
Fundamental spatial indexing functionality that forms the foundation of Rtree's capabilities. These operations provide the essential CRUD (Create, Read, Update, Delete) functionality for spatial data.
3
4
## Capabilities
5
6
### Index Creation
7
8
Create spatial indexes with various configuration options.
9
10
```python { .api }
11
def __init__(self, *args: Any, **kwargs: Any) -> None:
12
"""
13
Creates a new index (R-Tree, MVR-Tree, or TPR-Tree).
14
15
Parameters:
16
- filename (str, optional): Path for file-based storage
17
- stream (iterable, optional): Input stream of index items
18
- storage (ICustomStorage, optional): Custom storage implementation
19
- interleaved (bool): Coordinate ordering format (default: True)
20
- properties (Property, optional): Index configuration object
21
- pagesize (int, optional): Page size for disk storage
22
- overwrite (bool, optional): Overwrite existing files
23
24
Returns:
25
None
26
"""
27
```
28
29
### Data Insertion
30
31
Insert spatial objects into the index.
32
33
```python { .api }
34
def insert(self, id: int, coordinates: Any, obj: object = None) -> None:
35
"""
36
Insert an item into the index.
37
38
Parameters:
39
- id (int): Unique identifier for the item
40
- coordinates (sequence): Spatial coordinates (minx, miny, maxx, maxy, ...)
41
- obj (object, optional): Python object to store with the item
42
43
Returns:
44
None
45
"""
46
47
def add(self, id: int, coordinates: Any, obj: object = None) -> None:
48
"""
49
Alias for insert method.
50
51
Parameters:
52
- id (int): Unique identifier for the item
53
- coordinates (sequence): Spatial coordinates
54
- obj (object, optional): Python object to store with the item
55
56
Returns:
57
None
58
"""
59
```
60
61
Usage example:
62
63
```python
64
from rtree import index
65
66
idx = index.Index()
67
68
# Insert basic spatial data
69
idx.insert(0, (0, 0, 1, 1)) # Rectangle from (0,0) to (1,1)
70
idx.insert(1, (0.5, 0.5, 1.5, 1.5)) # Overlapping rectangle
71
72
# Insert with associated objects
73
idx.insert(2, (2, 2, 3, 3), obj={"name": "Building A", "type": "commercial"})
74
idx.insert(3, (4, 4, 5, 5), obj="Simple string object")
75
```
76
77
### Spatial Queries
78
79
Query the index for spatial relationships.
80
81
```python { .api }
82
def intersection(self, coordinates: Any, objects: bool | Literal["raw"] = False) -> Iterator[Item | int | object]:
83
"""
84
Find items that intersect with the given coordinates.
85
86
Parameters:
87
- coordinates (sequence): Query bounds (minx, miny, maxx, maxy, ...)
88
- objects (bool | "raw"): Return format
89
- False: Return item IDs only
90
- True: Return Item objects with id, object, bounds
91
- "raw": Return stored objects directly
92
93
Returns:
94
Iterator of IDs, Item objects, or stored objects
95
"""
96
97
def contains(self, coordinates: Any, objects: bool | Literal["raw"] = False) -> Iterator[Item | int | object] | None:
98
"""
99
Find items contained within the given coordinates.
100
101
Parameters:
102
- coordinates (sequence): Query bounds
103
- objects (bool | "raw"): Return format (same as intersection)
104
105
Returns:
106
Iterator of IDs, Item objects, or stored objects
107
"""
108
109
def nearest(self, coordinates: Any, num_results: int = 1, objects: bool | Literal["raw"] = False) -> Iterator[Item | int | object]:
110
"""
111
Find k-nearest items to the given coordinates.
112
113
Parameters:
114
- coordinates (sequence): Query point or bounds
115
- num_results (int): Maximum number of results to return
116
- objects (bool | "raw"): Return format (same as intersection)
117
118
Returns:
119
Iterator of IDs, Item objects, or stored objects (up to num_results)
120
"""
121
122
def count(self, coordinates: Any) -> int:
123
"""
124
Count items that intersect with the given coordinates.
125
126
Parameters:
127
- coordinates (sequence): Query bounds
128
129
Returns:
130
int: Number of intersecting items
131
"""
132
```
133
134
Usage example:
135
136
```python
137
from rtree import index
138
139
idx = index.Index()
140
idx.insert(0, (0, 0, 1, 1), obj="Rectangle 1")
141
idx.insert(1, (0.5, 0.5, 1.5, 1.5), obj="Rectangle 2")
142
idx.insert(2, (2, 2, 3, 3), obj="Rectangle 3")
143
144
# Intersection query - return IDs only
145
hits = list(idx.intersection((0.5, 0.5, 1.5, 1.5)))
146
print(hits) # [0, 1]
147
148
# Intersection query - return Item objects
149
for item in idx.intersection((0.5, 0.5, 1.5, 1.5), objects=True):
150
print(f"ID: {item.id}, Object: {item.object}, Bounds: {item.bounds}")
151
152
# Intersection query - return stored objects directly
153
objects = list(idx.intersection((0.5, 0.5, 1.5, 1.5), objects="raw"))
154
print(objects) # ["Rectangle 1", "Rectangle 2"]
155
156
# Nearest neighbor search
157
nearest_ids = list(idx.nearest((0.25, 0.25), 2))
158
print(nearest_ids) # [0, 1]
159
160
# Count intersections
161
count = idx.count((0, 0, 2, 2))
162
print(count) # 2
163
```
164
165
### Data Deletion
166
167
Remove items from the index.
168
169
```python { .api }
170
def delete(self, id: int, coordinates: Any) -> None:
171
"""
172
Delete an item from the index.
173
174
Parameters:
175
- id (int): Unique identifier of the item to delete
176
- coordinates (sequence): Spatial coordinates of the item
177
178
Returns:
179
None
180
181
Note:
182
Both ID and coordinates must match the inserted item exactly.
183
"""
184
```
185
186
Usage example:
187
188
```python
189
from rtree import index
190
191
idx = index.Index()
192
idx.insert(0, (0, 0, 1, 1))
193
idx.insert(1, (2, 2, 3, 3))
194
195
print(len(idx)) # 2
196
197
# Delete item with matching ID and coordinates
198
idx.delete(0, (0, 0, 1, 1))
199
print(len(idx)) # 1
200
201
# Verify deletion
202
hits = list(idx.intersection((0, 0, 1, 1)))
203
print(hits) # []
204
```
205
206
### Index Information
207
208
Get information about the index state and contents.
209
210
```python { .api }
211
def __len__(self) -> int:
212
"""
213
Get the number of items in the index.
214
215
Returns:
216
int: Number of items in the index
217
"""
218
219
def get_size(self) -> int:
220
"""
221
Get the number of items in the index (deprecated).
222
223
Returns:
224
int: Number of items in the index
225
226
Note:
227
This method is deprecated. Use len(index) instead.
228
"""
229
230
def valid(self) -> bool:
231
"""
232
Check if the index is in a valid state.
233
234
Returns:
235
bool: True if index is valid, False otherwise
236
"""
237
238
def get_bounds(self, coordinate_interleaved=None):
239
"""
240
Get the bounding box of all items in the index.
241
242
Parameters:
243
- coordinate_interleaved (bool, optional): Return format
244
- True: Interleaved format [minx, miny, maxx, maxy, ...]
245
- False/None: Non-interleaved format [minx, maxx, miny, maxy, ...]
246
247
Returns:
248
list: Bounding box coordinates or None if empty
249
"""
250
251
@property
252
def bounds(self):
253
"""
254
Property for getting index bounds.
255
256
Returns:
257
list: Bounding box in non-interleaved format or None if empty
258
"""
259
```
260
261
Usage example:
262
263
```python
264
from rtree import index
265
266
idx = index.Index()
267
idx.insert(0, (0, 0, 1, 1))
268
idx.insert(1, (2, 2, 3, 3))
269
270
# Check index size
271
print(len(idx)) # 2
272
print(idx.valid()) # True
273
274
# Get overall bounds
275
print(idx.bounds) # [0.0, 3.0, 0.0, 3.0] (minx, maxx, miny, maxy)
276
print(idx.get_bounds(coordinate_interleaved=True)) # [0.0, 0.0, 3.0, 3.0]
277
```
278
279
## Coordinate Formats
280
281
Rtree supports two coordinate ordering formats controlled by the `interleaved` attribute:
282
283
- **Interleaved** (default): `[minx, miny, maxx, maxy, minz, maxz, ...]`
284
- **Non-interleaved**: `[minx, maxx, miny, maxy, minz, maxz, ...]`
285
286
```python { .api }
287
@classmethod
288
def interleave(cls, deinterleaved: Sequence[float]) -> list[float]:
289
"""
290
Convert non-interleaved coordinates to interleaved format.
291
292
Parameters:
293
- deinterleaved (sequence): Non-interleaved coordinates
294
295
Returns:
296
list: Interleaved coordinates
297
"""
298
299
@classmethod
300
def deinterleave(cls, interleaved: Sequence[object]) -> list[object]:
301
"""
302
Convert interleaved coordinates to non-interleaved format.
303
304
Parameters:
305
- interleaved (sequence): Interleaved coordinates
306
307
Returns:
308
list: Non-interleaved coordinates
309
"""
310
```
311
312
## Storage Management
313
314
Control index persistence and memory management.
315
316
```python { .api }
317
def flush(self) -> None:
318
"""
319
Force a flush of pending operations to storage.
320
321
Returns:
322
None
323
"""
324
325
def close(self) -> None:
326
"""
327
Close the index and free all resources.
328
329
Returns:
330
None
331
332
Note:
333
Index becomes inaccessible after closing.
334
"""
335
336
def clearBuffer(self) -> None:
337
"""
338
Clear the index buffer.
339
340
Returns:
341
None
342
"""
343
```
344
345
## Error Handling
346
347
Core indexing operations can raise `RTreeError` exceptions for various error conditions:
348
349
- Invalid coordinate specifications (e.g., min > max)
350
- Invalid arguments or parameters
351
- Library-level errors from libspatialindex
352
- Storage or memory allocation errors
353
354
```python
355
from rtree import index
356
from rtree.exceptions import RTreeError
357
358
idx = index.Index()
359
360
try:
361
# This will raise RTreeError due to invalid bounds
362
idx.insert(0, (1.0, 1.0, 0.0, 0.0)) # minx > maxx
363
except RTreeError as e:
364
print(f"Index error: {e}")
365
```