Debian Codegraph @

www/rtree.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>The SQLite R*Tree Module</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 The SQLite R*Tree Module
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#overview">1. Overview</a></div>
129 <div class="fancy-toc1"><a href="#compiling_the_r_tree_module">2. Compiling The R*Tree Module</a></div>
130 <div class="fancy-toc1"><a href="#using_the_r_tree_module">3. Using the R*Tree Module</a></div>
131 <div class="fancy-toc2"><a href="#creating_an_r_tree_index">3.1. Creating An R*Tree Index</a></div>
132 <div class="fancy-toc3"><a href="#column_naming_details">3.1.1. Column naming details</a></div>
133 <div class="fancy-toc2"><a href="#populating_an_r_tree_index">3.2. Populating An R*Tree Index</a></div>
134 <div class="fancy-toc2"><a href="#querying_an_r_tree_index">3.3. Querying An R*Tree Index</a></div>
135 <div class="fancy-toc2"><a href="#roundoff_error">3.4. Roundoff Error</a></div>
136 <div class="fancy-toc2"><a href="#reading_and_writing_at_the_same_time">3.5. Reading And Writing At The Same Time</a></div>
137 <div class="fancy-toc1"><a href="#using_r_trees_effectively">4. Using R*Trees Effectively</a></div>
138 <div class="fancy-toc2"><a href="#auxiliary_columns">4.1. Auxiliary Columns</a></div>
139 <div class="fancy-toc3"><a href="#limitations">4.1.1. Limitations</a></div>
140 <div class="fancy-toc1"><a href="#integer_valued_r_trees">5. Integer-Valued R-Trees</a></div>
141 <div class="fancy-toc1"><a href="#custom_r_tree_queries">6. Custom R-Tree Queries</a></div>
142 <div class="fancy-toc2"><a href="#the_legacy_xgeom_callback">6.1. The Legacy xGeom Callback</a></div>
143 <div class="fancy-toc2"><a href="#the_new_xqueryfunc_callback">6.2. The New xQueryFunc Callback</a></div>
144 <div class="fancy-toc2"><a href="#additional_considerations_for_custom_queries">6.3. Additional Considerations for Custom Queries</a></div>
145 <div class="fancy-toc1"><a href="#implementation_details">7. Implementation Details</a></div>
146 <div class="fancy-toc2"><a href="#shadow_tables">7.1. Shadow Tables</a></div>
147 <div class="fancy-toc2"><a href="#integrity_check_using_the_rtreecheck_sql_function">7.2. Integrity Check using the rtreecheck() SQL function</a></div>
148 </div>
149 </div>
150 <script>
151 function toggle_toc(){
152 var sub = document.getElementById("toc_sub")
153 var mk = document.getElementById("toc_mk")
154 if( sub.style.display!="block" ){
155 sub.style.display = "block";
156 mk.innerHTML = "&#x25bc;";
157 } else {
158 sub.style.display = "none";
159 mk.innerHTML = "&#x25ba;";
160 }
161 }
162 </script>
163 </div>
164
165
166
167
168 <h1 id="overview"><span>1. </span>Overview</h1>
169
170 <p>
171 An <a href="http://en.wikipedia.org/wiki/R-tree">R-Tree</a> is a special
172 index that is designed for doing range queries. R-Trees are most commonly
173 used in geospatial systems where each entry is a rectangle with minimum and
174 maximum X and Y coordinates. Given a query rectangle, an R-Tree is able
175 to quickly find all entries that are contained within the query rectangle
176 or which overlap the query rectangle. This idea is easily extended to
177 three dimensions for use in CAD systems. R-Trees also find use in time-domain
178 range look-ups. For example, suppose a database records the starting and
179 ending times for a large number of events. A R-Tree is able to quickly
180 find all events that were active at any time during a given
181 time interval, or all events that started during a particular time interval,
182 or all events that both started and ended within a given time interval.
183 And so forth.
184 </p>
185
186 <p>
187 The R-Tree concept originated with
188 <a href="https://link.springer.com/referenceworkentry/10.1007/978-0-387-35973-1_1151">Toni Guttman</a>:
189 <em>R-Trees: A Dynamic Index Structure for Spatial Searching</em>,
190 Proc. 1984 ACM SIGMOD International Conference on Management of Data,
191 pp. 47-57.
192 The implementation found in SQLite is a refinement of Guttman's original
193 idea, commonly called "R*Trees", that was described by
194 Norbert Beckmann, Hans-Peter Kriegel, Ralf Schneider, Bernhard Seeger:
195 <em>The R*-Tree: An Efficient and Robust Access Method for Points
196 and Rectangles.</em> SIGMOD Conference 1990: 322-331.
197 </p>
198
199 <h1 id="compiling_the_r_tree_module"><span>2. </span>Compiling The R*Tree Module</h1>
200
201 <p>
202 The source code to the SQLite R*Tree module is included as part
203 of the <a href="amalgamation.html">amalgamation</a>. However, depending on configuration options
204 and the particular version of SQLite you are using, it may or may not
205 be enabled by default. To ensure that the R*Tree module is enabled,
206 simply compile with the <a href="compile.html#enable_rtree">SQLITE_ENABLE_RTREE</a>
207 C-preprocessor macro defined. With many compilers, this is accomplished
208 by adding the option "-DSQLITE_ENABLE_RTREE=1" to the compiler
209 command-line.
210 </p>
211
212 <h1 id="using_the_r_tree_module"><span>3. </span>Using the R*Tree Module</h1>
213
214 <p>
215 The SQLite R*Tree module is implemented as a
216 <a href="c3ref/create_module.html">virtual table</a>. Each R*Tree index is a
217 virtual table with an odd number of columns between 3 and 11.
218 The first column is always a 64-bit signed integer primary key.
219 The other columns are pairs, one pair per dimension, containing the
220 minimum and maximum values for that dimension, respectively.
221 A 1-dimensional R*Tree thus has 3 columns.
222 A 2-dimensional R*Tree has 5 columns.
223 A 3-dimensional R*Tree has 7 columns.
224 A 4-dimensional R*Tree has 9 columns.
225 And a 5-dimensional R*Tree has 11 columns. The SQLite R*Tree implementation
226 does not support R*Trees wider than 5 dimensions.
227 </p>
228
229 <p>
230 The first column of an SQLite R*Tree is similar to an integer primary
231 key column of a normal SQLite table. It may only store a 64-bit signed
232 integer value. Inserting a NULL value into this column causes SQLite
233 to automatically generate a new unique primary key value. If an attempt
234 is made to insert any other non-integer value into this column,
235 the r-tree module silently converts it to an integer before writing it
236 into the database.
237 </p><p>
238 The min/max-value pair columns are stored as 32-bit floating point values for
239 "rtree" virtual tables or as 32-bit signed integers in "rtree_i32" virtual
240 tables. Unlike regular SQLite tables which can store data in a variety of
241 datatypes and formats, the R*Tree rigidly enforce these storage types.
242 If any other type of value is inserted into such a column, the r-tree
243 module silently converts it to the required type before writing the
244 new record to the database.
245
246 </p><h2 id="creating_an_r_tree_index"><span>3.1. </span>Creating An R*Tree Index</h2>
247
248 <p>
249 A new R*Tree index is created as follows:
250 </p>
251
252 <div class="codeblock"><pre>CREATE VIRTUAL TABLE <em>&lt;name&gt;</em> USING rtree(<em>&lt;column-names&gt;</em>);
253 </pre></div>
254
255 <p>
256 The <em>&lt;name&gt;</em> is the name your application chooses for the
257 R*Tree index and <em>&lt;column-names&gt;</em> is a comma separated list
258 of between 3 and 11 columns.
259 The virtual &lt;name&gt; table creates three <a href="vtab.html#xshadowname">shadow tables</a> to actually
260 store its content. The names of these shadow tables are:
261 </p>
262
263 <div class="codeblock"><pre><em>&lt;name&gt;</em><strong>_node</strong><br>
264 <em>&lt;name&gt;</em><strong>_rowid</strong><br>
265 <em>&lt;name&gt;</em><strong>_parent</strong>
266 </pre></div>
267
268
269 <p>
270 The shadow tables are ordinary SQLite data tables. You can query them
271 directly if you like, though this unlikely to reveal anything particularly
272 useful.
273 And you can <a href="lang_update.html">UPDATE</a>, <a href="lang_delete.html">DELETE</a>, <a href="lang_insert.html">INSERT</a> or even <a href="lang_droptable.html">DROP</a>
274 the shadow tables, though doing so will corrupt your R*Tree index.
275 So it is best to simply ignore the shadow tables. Recognize that they
276 hold your R*Tree index information and let it go as that.
277 </p>
278
279 <p>
280 As an example, consider creating a two-dimensional R*Tree index for use in
281 spatial queries:
282 </p>
283
284 <div class="codeblock"><pre>CREATE VIRTUAL TABLE demo_index USING rtree(
285 id, -- Integer primary key
286 minX, maxX, -- Minimum and maximum X coordinate
287 minY, maxY -- Minimum and maximum Y coordinate
288 );
289 </pre></div>
290
291
292 <h3 id="column_naming_details"><span>3.1.1. </span>Column naming details</h3>
293
294 <p>
295 In the argments to "rtree" in the CREATE VIRTUAL TABLE statement, the
296 names of the columns are taken from the first token of each argument.
297 All subsequent tokens within each argument are silently ignored.
298 This means, for example, that if you try to give a column a
299 <a href="datatype3.html#affinity">type affinity</a> or add a constraint such as UNIQUE or NOT NULL or DEFAULT to
300 a column, those extra tokens are accepted as valid, but they do not change
301 the behavior of the rtree.
302 In an RTREE virtual table, the first column always has a
303 <a href="datatype3.html#affinity">type affinity</a> of INTEGER and all other data columns have a
304 <a href="datatype3.html#affinity">type affinity</a> of REAL.
305 In an RTREE_I32 virtual table, all columns have type affinity of INTEGER.
306
307 </p><p>
308 Recommended practice is to omit any extra tokens in the rtree specification.
309 Let each argument to "rtree" be a single ordinary label that is the name of
310 the corresponding column, and omit all other tokens from the argument list.
311
312 </p><h2 id="populating_an_r_tree_index"><span>3.2. </span>Populating An R*Tree Index</h2>
313
314 <p>
315 The usual <a href="lang_insert.html">INSERT</a>, <a href="lang_update.html">UPDATE</a>, and <a href="lang_delete.html">DELETE</a> commands work on an R*Tree
316 index just like on regular tables. So to insert some data into our sample
317 R*Tree index, we can do something like this:
318 </p>
319
320 <div class="codeblock"><pre>INSERT INTO demo_index VALUES
321 (28215, -80.781227, -80.604706, 35.208813, 35.297367),
322 (28216, -80.957283, -80.840599, 35.235920, 35.367825),
323 (28217, -80.960869, -80.869431, 35.133682, 35.208233),
324 (28226, -80.878983, -80.778275, 35.060287, 35.154446),
325 (28227, -80.745544, -80.555382, 35.130215, 35.236916),
326 (28244, -80.844208, -80.841988, 35.223728, 35.225471),
327 (28262, -80.809074, -80.682938, 35.276207, 35.377747),
328 (28269, -80.851471, -80.735718, 35.272560, 35.407925),
329 (28270, -80.794983, -80.728966, 35.059872, 35.161823),
330 (28273, -80.994766, -80.875259, 35.074734, 35.172836),
331 (28277, -80.876793, -80.767586, 35.001709, 35.101063),
332 (28278, -81.058029, -80.956375, 35.044701, 35.223812),
333 (28280, -80.844208, -80.841972, 35.225468, 35.227203),
334 (28282, -80.846382, -80.844193, 35.223972, 35.225655);
335 </pre></div>
336
337
338 <p>
339 The entries above are bounding boxes (longitude and latitude) for 14
340 zipcodes near Charlotte, NC. A real database would have many thousands,
341 millions, or billions of such entries, but this small 14-row sample will
342 be sufficient to illustrate the ideas.
343 </p>
344
345 <h2 id="querying_an_r_tree_index"><span>3.3. </span>Querying An R*Tree Index</h2>
346
347 <p>
348 Any valid query will work against an R*Tree index. The R*Tree
349 implementation just makes some kinds of queries especially
350 efficient. Queries against the primary key are efficient:
351 </p>
352
353 <div class="codeblock"><pre>SELECT * FROM demo_index WHERE id=28269;
354 </pre></div>
355
356
357 <p>
358 Of course, an ordinary SQLite table will also do a query against its
359 integer primary key efficiently, so the previous is not important.
360 The big reason for using an R*Tree is so that
361 you can efficiently do range queries against the coordinate
362 ranges. For example, the main office of the SQLite project is
363 located at 35.37785, -80.77470.
364 To find which zipcodes might service that office, one could right:
365 </p>
366
367 <div class="codeblock"><pre>SELECT id FROM demo_index
368 WHERE minX&lt;=-80.77470 AND maxX&gt;=-80.77470
369 AND minY&lt;=35.37785 AND maxY&gt;=35.37785;
370 </pre></div>
371
372
373 <p>
374 The query above will quickly locate all zipcodes that contain
375 the SQLite main office in their bounding box, even if the
376 R*Tree contains many entries. The previous is an example
377 of a "contained-within" query. The R*Tree also supports "overlapping"
378 queries. For example, to find all zipcode bounding boxes that overlap
379 with the 28269 zipcode:
380 </p>
381
382 <div class="codeblock"><pre>SELECT A.id FROM demo_index AS A, demo_index AS B
383 WHERE A.maxX&gt;=B.minX AND A.minX&lt;=B.maxX
384 AND A.maxY&gt;=B.minY AND A.minY&lt;=B.maxY
385 AND B.id=28269;
386 </pre></div>
387
388
389 <p>
390 This second query will find both 28269 entry (since every bounding box
391 overlaps with itself) and also other zipcode that is close enough to
392 28269 that their bounding boxes overlap.
393 </p>
394
395 <p>
396 Note that it is not necessary for all coordinates in an R*Tree index
397 to be constrained in order for the index search to be efficient.
398 One might, for example, want to query all objects that overlap with
399 the 35th parallel:
400 </p>
401
402 <div class="codeblock"><pre>SELECT id FROM demo_index
403 WHERE maxY&gt;=35.0 AND minY&lt;=35.0;
404 </pre></div>
405
406
407 <p>
408 But, generally speaking, the more constraints that the R*Tree module
409 has to work with, and the smaller the bounding box, the faster the
410 results will come back.
411 </p>
412
413 <h2 id="roundoff_error"><span>3.4. </span>Roundoff Error</h2>
414
415 <p>
416 By default, coordinates are stored in an R*Tree using 32-bit floating
417 point values. When a coordinate cannot be exactly represented by a
418 32-bit floating point number, the lower-bound coordinates are rounded down
419 and the upper-bound coordinates are rounded up. Thus, bounding boxes might
420 be slightly larger than specified, but will never be any smaller. This
421 is exactly what is desired for doing the more common "overlapping" queries
422 where the application wants to find every entry in the R*Tree that overlaps
423 a query bounding box. Rounding the entry bounding boxes outward might cause a
424 few extra entries to appears in an overlapping query if the edge of the
425 entry bounding box corresponds to an edge of the query bounding box. But
426 the overlapping query will never miss a valid table entry.
427
428 </p><p>However, for a "contained-within" style query, rounding the bounding
429 boxes outward might cause some entries to be excluded from the result set
430 if the edge of the entry bounding box corresponds to the edge of the query
431 bounding box. To guard against this, applications should expand their
432 contained-within query boxes slightly (by 0.000012%) by rounding down the
433 lower coordinates and rounding up the top coordinates, in each dimension.
434
435 <a name="readwrite"></a>
436
437 </p><h2 id="reading_and_writing_at_the_same_time"><span>3.5. </span>Reading And Writing At The Same Time</h2>
438
439 <p>
440 It is the nature of the Guttman R-Tree algorithm that any write might
441 radically restructure the tree, and in the process change the scan order
442 of the nodes. For this reason, it is not generally possible to modify
443 the R-Tree in the middle of a query of the R-Tree. Attempts to do so
444 will fail with a <a href="rescode.html#locked">SQLITE_LOCKED</a> "database table is locked" error.
445
446 </p><p>
447 So, for example, suppose an application runs one query against an R-Tree like
448 this:
449
450 </p><div class="codeblock"><pre>SELECT id FROM demo_index
451 WHERE maxY&gt;=35.0 AND minY&lt;=35.0;
452 </pre></div>
453
454 <p>
455 Then for each "id" value returned, suppose the application creates an
456 UPDATE statement like the following and binds the "id" value returned against
457 the "?1" parameter:
458
459 </p><div class="codeblock"><pre>UPDATE demo_index SET maxY=maxY+0.5 WHERE id=?1;
460 </pre></div>
461
462 <p>
463 Then the UPDATE might fail with an SQLITE_LOCKED error. The reason is that
464 the initial query has not run to completion. It is remembering its place
465 in the middle of a scan of the R-Tree. So an update to the R-Tree cannot
466 be tolerated as this would disrupt the scan.
467
468 </p><p>
469 This is a limitation of the R-Tree extension only. Ordinary tables in
470 SQLite are able to read and write at the same time. Other virtual tables
471 might (or might not) also that capability. And R-Tree can appear to read
472 and write at the same time in some circumstances, if it can figure out how
473 to reliably run the query to completion before starting the update. But
474 you shouldn't count on that for every query. Generally speaking, it is
475 best to avoid running queries and updates to the same R-Tree at the same
476 time.
477
478 </p><p>
479 If you really need to update an R-Tree based on complex queries against
480 the same R-Tree, it is best to run the complex queries first and store
481 the results in a temporary table, then update the R-Tree based on the values
482 stored in the temporary table.
483
484 </p><h1 id="using_r_trees_effectively"><span>4. </span>Using R*Trees Effectively</h1>
485
486 <p>
487 For SQLite versions prior to 3.24.0 (2018-06-04),
488 the only information that an R*Tree index stores about an object is
489 its integer ID and its bounding box. Additional information needs to
490 be stored in separate tables and related to the R*Tree index using
491 the primary key. For the example above, one might create an auxiliary
492 table as follows:
493 </p>
494
495 <div class="codeblock"><pre>CREATE TABLE demo_data(
496 id INTEGER PRIMARY KEY, -- primary key
497 objname TEXT, -- name of the object
498 objtype TEXT, -- object type
499 boundary BLOB -- detailed boundary of object
500 );
501 </pre></div>
502
503 <p>
504 In this example, the demo_data.boundary field is intended to hold some
505 kind of binary representation of the precise boundaries of the object.
506 The R*Tree index only holds an axis-aligned rectangular boundary for the
507 object. The R*Tree boundary is just an approximation of the true object
508 boundary. So what typically happens is that the R*Tree index is used to
509 narrow a search down to a list of candidate objects and then more detailed
510 and expensive computations are done on each candidate to find if the
511 candidate truly meets the search criteria.
512 </p>
513
514 <blockquote><p>
515 <strong>Key Point:</strong>
516 An R*Tree index does not normally provide the exact answer but merely
517 reduces the set of potential answers from millions to dozens.
518 </p></blockquote>
519
520 <p>
521 Suppose the demo_data.boundary field holds some proprietary data description
522 of a complex two-dimensional boundary for a zipcode and suppose that the
523 application has used the <a href="c3ref/create_function.html">sqlite3_create_function()</a> interface to
524 created an application-defined function "contained_in(boundary,lat,long)"
525 that accepts the demo_data.boundary object and a latitute and longitude
526 and returns return true or false if the lat/long is contained within
527 the boundary.
528 One may assume that "contained_in()" is a relatively slow
529 functions that we do not want to invoke too frequently.
530 Then an efficient way to find the specific ZIP code for the main
531 SQLite office would be to run a query like this:
532 </p>
533
534 <a name="diquery"></a>
535 <div class="codeblock"><pre>SELECT objname FROM demo_data, demo_index
536 WHERE demo_data.id=demo_index.id
537 AND contained_in(demo_data.boundary, 35.37785, -80.77470)
538 AND minX&lt;=-80.77470 AND maxX&gt;=-80.77470
539 AND minY&lt;=35.37785 AND maxY&gt;=35.37785;
540 </pre></div>
541
542 <p>Notice how the query above works: The R*Tree index runs in the outer
543 loop to find entries that contain the SQLite main office in their
544 boundary box.
545 For each row found, SQLite looks up
546 the corresponding entry in the demo_data table. It then uses the boundary
547 field from the demo_data table as a parameter to the contained_in()
548 function and if that function returns true, then we know the sought after
549 coordinate is in that ZIP code boundary.</p>
550
551 <p>One would get the same answer without the use of the R*Tree index
552 using the following simpler query:</p>
553
554 <div class="codeblock"><pre>SELECT objname FROM demo_data
555 WHERE contained_in(demo_data.boundary, 35.37785, -80.77470);
556 </pre></div>
557
558 <p>The problem with this latter query is that it must apply the
559 contained_in() function to all entries in the demo_data table.
560 The use of the R*Tree in the penultimate query reduces the number of
561 calls to contained_in() function to a small subset of the entire table.
562 The R*Tree index did not find the exact answer itself, it merely
563 limited the search space.</p>
564
565 <a name="auxcol"></a>
566
567 <h2 id="auxiliary_columns"><span>4.1. </span>Auxiliary Columns</h2>
568
569 <p>
570 Beginning with SQLite version 3.24.0 (2018-06-04), r-tree tables
571 can have auxiliary columns that store arbitrary data.
572 Auxiliary columns can be used in place of
573 secondary tables such as "demo_data".
574
575 </p><p>
576 Auxiliary columns are marked with a "+" symbol before the column name.
577 Auxiliary columns must come after all of the coordinate boundary columns.
578 An RTREE table can have no more than 100 columns total. In other words,
579 the count of columns including the integer primary key column,
580 the coordinate boundary columns, and all auxiliary columns must be 100 or less.
581 The following example shows an r-tree table with auxiliary columns that
582 is equivalent to the two tables "demo_index" and "demo_data" above:
583
584 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE demo_index2 USING rtree(
585 id, -- Integer primary key
586 minX, maxX, -- Minimum and maximum X coordinate
587 minY, maxY, -- Minimum and maximum Y coordinate
588 +objname TEXT, -- name of the object
589 +objtype TEXT, -- object type
590 +boundary BLOB -- detailed boundary of object
591 );
592 </pre></div>
593
594 <p>
595 By combining location data and related information into the same
596 table, auxiliary columns can provide a cleaner model
597 and reduce the need to joins.
598 For example, the earlier
599 <a href="#diquery">join between demo_index and demo_data</a> can now
600 be written as a simple query, like this:
601
602 </p><div class="codeblock"><pre>SELECT objname FROM demo_index2
603 WHERE contained_in(boundary, 35.37785, -80.77470)
604 AND minX&lt;=-80.77470 AND maxX&gt;=-80.77470
605 AND minY&lt;=35.37785 AND maxY&gt;=35.37785;
606 </pre></div>
607
608 <h3 id="limitations"><span>4.1.1. </span>Limitations</h3>
609
610 <p>
611 For auxiliary columns, only the name of the column matters.
612 The <a href="datatype3.html#affinity">type affinity</a> is ignored.
613 Constraints such as NOT NULL, UNIQUE, REFERENCES, or CHECK
614 are also ignored. However, future versions
615 of SQLite might start paying attention to the type affinity and
616 constraints, so users of auxiliary columns are advised to leave
617 both blank, to avoid future compatibility problems.
618
619 <a name="intrtree"></a>
620
621 </p><h1 id="integer_valued_r_trees"><span>5. </span>Integer-Valued R-Trees</h1>
622
623 <p>
624 The default virtual table ("rtree") stores coordinates as
625 single-precision (4-byte) floating point numbers. If integer coordinates
626 are desired, declare the table using "rtree_i32" instead:
627
628 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE intrtree USING rtree_i32(id,x0,x1,y0,y1,z0,z1);
629 </pre></div>
630
631 <p>
632 An rtree_i32 stores coordinates as 32-bit signed integers.
633 Even though it stores values using integer, the rtree_i32 virtual
634 table still uses floating point computations internally as part of
635 the r-tree algorithm.
636
637 <a name="customquery"></a>
638
639 </p><h1 id="custom_r_tree_queries"><span>6. </span>Custom R-Tree Queries</h1>
640
641 <p>By using standard SQL expressions in the WHERE clause of a SELECT query,
642 a programmer can query for all R*Tree entries that
643 intersect with or are contained within a particular bounding-box.
644 Custom R*Tree queries, using the MATCH
645 operator in the WHERE clause of a SELECT, allow the programmer to query for
646 the set of R*Tree entries that intersect any arbitrary region or shape, not
647 just a box. This capability is useful, for example, in computing the
648 subset of objects in the R*Tree that are visible from a camera positioned
649 in 3-D space.
650
651 </p><p>Regions for custom R*Tree queries are defined by R*Tree geometry callbacks
652 implemented by the application and registered with SQLite via a call to one
653 of the following two APIs:
654
655 </p><div class="codeblock"><pre>int sqlite3_rtree_query_callback(
656 sqlite3 *db,
657 const char *zQueryFunc,
658 int (*xQueryFunc)(sqlite3_rtree_query_info*),
659 void *pContext,
660 void (*xDestructor)(void*)
661 );
662 int sqlite3_rtree_geometry_callback(
663 sqlite3 *db,
664 const char *zGeom,
665 int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
666 void *pContext
667 );
668 </pre></div>
669
670 <p>The sqlite3_rtree_query_callback() became available with SQLite
671 <a href="releaselog/3_8_5.html">version 3.8.5</a> (2014-06-04) and is the preferred interface.
672 The sqlite3_rtree_geometry_callback() is an older and less flexible
673 interface that is supported for backwards compatibility.
674
675 </p><p>A call to one of the above APIs creates a new SQL function named by the
676 second parameter (zQueryFunc or zGeom). When that SQL function appears
677 on the right-hand side of the MATCH operator and the left-hand side of the
678 MATCH operator is any column in the R*Tree virtual table, then the callback
679 defined by the third argument (xQueryFunc or xGeom) is invoked to determine
680 if a particular object or subtree overlaps the desired region.
681
682 </p><p>For example, a query like the following might be used to find all
683 R*Tree entries that overlap with a circle centered a 45.3,22.9 with a
684 radius of 5.0:
685
686 </p><div class="codeblock"><pre>SELECT id FROM demo_index WHERE id MATCH circle(45.3, 22.9, 5.0)
687 </pre></div>
688
689 <p>The SQL syntax for custom queries is the same regardless of which
690 interface, sqlite3_rtree_geometry_callback() or sqlite3_rtree_query_callback(),
691 is used to register the SQL function. However, the newer query-style
692 callbacks give the application greater control over how the query proceeds.
693
694 </p><h2 id="the_legacy_xgeom_callback"><span>6.1. </span>The Legacy xGeom Callback</h2>
695
696 <p>The legacy xGeom callback is invoked with four arguments. The first
697 argument is a pointer to an sqlite3_rtree_geometry structure which provides
698 information about how the SQL function was invoked. The second argument
699 is the number of coordinates in each r-tree entry, and is always the same
700 for any given R*Tree. The number of coordinates is 2 for a 1-dimensional R*Tree,
701 4 for a 2-dimensional R*Tree, 6 for a 3-dimensional R*Tree, and so forth.
702 The third argument, aCoord[], is an array of nCoord coordinates that defines
703 a bounding box to be tested. The last argument is a pointer into which
704 the callback result should be written. The result is zero
705 if the bounding-box defined by aCoord[] is completely outside
706 the region defined by the xGeom callback and the result is non-zero if
707 the bounding-box is inside or overlaps with the xGeom region. The xGeom
708 callback should normally return SQLITE_OK. If xGeom returns anything other
709 than SQLITE_OK, then the r-tree query will abort with an error.
710
711 </p><p>The sqlite3_rtree_geometry structure that the first argument to the
712 xGeom callback points to has a structure shown below. The exact same
713 sqlite3_rtree_geometry
714 structure is used for every callback for same MATCH operator in the same
715 query. The contents of the sqlite3_rtree_geometry
716 structure are initialized by SQLite but are
717 not subsequently modified. The callback is free to make changes to the
718 pUser and xDelUser elements of the structure if desired.
719
720 </p><div class="codeblock"><pre>typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
721 struct sqlite3_rtree_geometry {
722 void *pContext; /* Copy of pContext passed to s_r_g_c() */
723 int nParam; /* Size of array aParam */
724 double *aParam; /* Parameters passed to SQL geom function */
725 void *pUser; /* Callback implementation user data */
726 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
727 };
728 </pre></div>
729
730 <p>The pContext member of the sqlite3_rtree_geometry
731 structure is always set to a copy of the pContext
732 argument passed to sqlite3_rtree_geometry_callback() when the
733 callback is registered. The aParam[] array (size nParam) contains the parameter
734 values passed to the SQL function on the right-hand side of the MATCH operator.
735 In the example "circle" query above, nParam would be set to 3 and the aParam[]
736 array would contain the three values 45.3, 22.9 and 5.0.
737
738 </p><p>The pUser and xDelUser members of the sqlite3_rtree_geometry structure are
739 initially set to NULL. The pUser variable may be set by the callback
740 implementation to any arbitrary value that may be useful to subsequent
741 invocations of the callback within the same query (for example, a
742 pointer to a complicated data structure used to test for region intersection).
743 If the xDelUser variable is set to a non-NULL value, then after the
744 query has finished running SQLite automatically invokes it with the
745 value of the pUser variable as the only argument. In other words, xDelUser
746 may be set to a destructor function for the pUser value.
747
748 </p><p>The xGeom callback always does a depth-first search of the r-tree.
749
750 <a name="xquery"></a>
751
752 </p><h2 id="the_new_xqueryfunc_callback"><span>6.2. </span>The New xQueryFunc Callback</h2>
753
754 <p>The newer xQueryFunc callback receives more information from the r-tree
755 query engine on each call, and it sends more information back to the query engine
756 before it returns.
757 To help keep the interface manageable, the xQueryFunc callback sends and receives
758 information from the query engine as fields in the
759 sqlite3_rtree_query_info structure:
760
761 </p><div class="codeblock"><pre>struct sqlite3_rtree_query_info {
762 void *pContext; /* pContext from when function registered */
763 int nParam; /* Number of function parameters */
764 sqlite3_rtree_dbl *aParam; /* value of function parameters */
765 void *pUser; /* callback can use this, if desired */
766 void (*xDelUser)(void*); /* function to free pUser */
767 sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
768 unsigned int *anQueue; /* Number of pending entries in the queue */
769 int nCoord; /* Number of coordinates */
770 int iLevel; /* Level of current node or entry */
771 int mxLevel; /* The largest iLevel value in the tree */
772 sqlite3_int64 iRowid; /* Rowid for current entry */
773 sqlite3_rtree_dbl rParentScore; /* Score of parent node */
774 int eParentWithin; /* Visibility of parent node */
775 int eWithin; /* OUT: Visiblity */
776 sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
777 /* The following fields are only available in 3.8.11 and later */
778 sqlite3_value **apSqlParam; /* Original SQL values of parameters */
779 };
780 </pre></div>
781
782 <p>The first five fields of the sqlite3_rtree_query_info structure are identical
783 to the sqlite3_rtree_geometry structure, and have exactly the same meaning.
784 The sqlite3_rtree_query_info structure also contains nCoord and aCoord fields
785 which have the same meaning as the parameter of the same name in the xGeom callback.
786
787 </p><p>The xQueryFunc must set the eWithin field of sqlite3_rtree_query_info to
788 one of the values NOT_WITHIN, PARTLY_WITHIN, or FULLY_WITHIN depending on whether
789 or not the bounding box defined by aCoord[] is completely outside the region,
790 overlaps the region, or is completely inside the region, respectively. In
791 addition, the xQueryFunc must set the rScore field to a non-negative value that
792 indicates the order in which subtrees and entries of the query should be analyzed
793 and returned. Smaller scores are processed first.
794
795 </p><p>As its name implies, an R*Tree is organized as a tree. Each node of the
796 tree is a bounding box. The root of the tree is a bounding box that encapsulates
797 all elements of the tree. Beneath the root are a number of subtrees (typically
798 20 or more) each with their own smaller bounding boxes and each containing some
799 subset of the R*Tree entries. The subtrees may have sub-subtrees, and so forth
800 until finally one reaches the leaves of the tree which are the actual R*Tree
801 entries.
802
803 </p><p>An R*Tree query is initialized by making the root node the only entry
804 in a priority queue sorted by rScore.
805 The query proceeds by extracting the entry from the priority queue that has
806 the lowest score. If that entry is a leaf (meaning that it is an actual
807 R*Tree entry and not a subtree) then that entry
808 is returned as one row of the query result.
809 If the extracted priority queue entry is a node (a subtree),
810 then the next child of that node is passed to the xQueryFunc callback.
811 If the node has more children then it is returned to the priority queue.
812 Otherwise it is discarded. Those subelements for which the xQueryFunc
813 callback sets eWithin to PARTLY_WITHIN or FULLY_WITHIN are added to the
814 priority queue using the score supplied by the callback. Subelements that
815 return NOT_WITHIN are discarded. The query runs until the priority queue is
816 empty.
817
818 </p><p>Every leaf entry and node (subtree) within the R*Tree has an integer "level".
819 The leaves have a level of 0. The first containing subtree of the leaves has
820 a level of 1. The root of the R*Tree has the largest level value. The
821 mxLevel entry in the sqlite3_rtree_query_info structure is the level value for
822 the root of the R*Tree. The iLevel entry in sqlite3_rtree_query_info gives the
823 level for the object being interrogated.
824
825 </p><p>Most R*Tree queries use a depth-first search. This is accomplished by setting
826 the rScore equal to iLevel. A depth-first search is usually preferred since it
827 minimizes the number of elements in the priority queue, which reduces memory
828 requirements and speeds processing. However, some application may prefer a
829 breadth-first search, which can be accomplished by setting rScore to mxLevel-iLevel.
830 By creating more complex formulas for rScore, applications can exercise
831 detailed control over the order in which subtree are searched and leaf
832 R*Tree entries are returned. For example, in an application with many
833 millions of R*Tree entries, the rScore might be arranged so that the
834 largest or most significant entries are returned first, allowing the
835 application to display the most important information quickly, and
836 filling in smaller and less important details as they become available.
837
838 </p><p>Other information fields of the sqlite3_rtree_query_info structure are
839 available for use by the xQueryFunc callback, if desired. The iRowid field
840 is the rowid (the first of the 3 to 11 columns in the R*Tree) for the element
841 being considered. iRowid is only valid for leaves. The eParentWithin and
842 rParentScore values are copies of the eWithin and rScore values from the
843 containing subtree of the current row. The anQueue field is an array
844 of mxLevel+1 unsigned integers that tell the current number of elements in
845 the priority queue at each level.
846
847 </p><h2 id="additional_considerations_for_custom_queries"><span>6.3. </span>Additional Considerations for Custom Queries</h2>
848
849 <p>
850 The MATCH operator of a custom R*Tree query function must be a top-level
851 AND-connected term of the WHERE clause, or else it will not be usable
852 by the R*Tree query optimizer and the query will not be runnable.
853 If the MATCH operator is connected to other terms of the WHERE clause
854 via an OR operator, for example, the query will fail with an error.
855
856 </p><p>
857 Two or more MATCH operators are allowed in the same WHERE clause, as long
858 as they are connected by AND operators. However,
859 the R*Tree query engine only contains a single priority queue. The priority
860 assigned to each node in the search is the lowest priority returned by any
861 of the MATCH operators.
862
863 </p><h1 id="implementation_details"><span>7. </span>Implementation Details</h1>
864
865 <p>
866 The following sections describe some low-level details of the R*Tree implementation,
867 that might be useful for trouble-shooting or performance analysis.
868
869 <a name="xshadow"></a>
870
871 </p><h2 id="shadow_tables"><span>7.1. </span>Shadow Tables</h2>
872
873 <p>The content of an R*Tree index is actually stored in three ordinary
874 SQLite tables with names derived from the name of the R*Tree. These
875 three tables are called "<a href="vtab.html#xshadowname">shadow tables</a>". This is their schema:
876
877 </p><div class="codeblock"><pre>CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data)
878 CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode)
879 CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno)
880 </pre></div>
881
882 <p>The "%" in the name of each shadow table is replaced by the name of the
883 R*Tree virtual table. So, if the name of the R*Tree table is "xyz" then
884 the three shadow tables would be "xyz_node", "xyz_parent", and "xyz_rowid".
885
886 </p><p>There is one entry in the %_node table for each R*Tree node. An
887 R*Tree node consists of one or more entries that are proximate to one another.
888 The nodes of an R*Tree for a tree. All nodes other than the root have an
889 entry in the %_parent shadow table that identifies the parent node.
890 Each entry in an R*Tree has a rowid. The %_rowid shadow table maps entry
891 rowids to the node that contains that entry.
892
893 </p><p>Extra columns appended to the %_rowid table hold the
894 content of <a href="rtree.html#auxcol">auxiliary columns</a>. The names of these extra
895 %_rowid columns are probably not the same as the
896 actual auxiliary column names.
897
898 <a name="rtreecheck"></a>
899
900 </p><h2 id="integrity_check_using_the_rtreecheck_sql_function"><span>7.2. </span>Integrity Check using the rtreecheck() SQL function</h2>
901
902 <p>The scalar SQL function rtreecheck(R) or rtreecheck(S,R) runs an
903 integrity check on the rtree table named R contained within database S.
904 The function returns a human-language description of any problems found,
905 or the string 'ok' if everything is ok. Running rtreecheck() on an R*Tree
906 virtual table is similar to running <a href="pragma.html#pragma_integrity_check">PRAGMA integrity_check</a> on a
907 database.
908
909 </p><p>Example: To verify that an R*Tree named "demo_index" is well-formed
910 and internally consistent, run:
911
912 </p><div class="codeblock"><pre>SELECT rtreecheck('demo_index');
913 </pre></div>
914
915 <p>The rtreecheck() function performs the following checks:
916
917 </p><ol>
918 <li><p>
919 For each cell in the r-tree structure (%_node table), that:
920 </p><ol type="a">
921 <li><p> for each dimension, (coord1 &lt;= coord2).
922 </p></li><li><p> unless the cell is on the root node, that the cell is bounded
923 by the parent cell on the parent node.
924 </p></li><li><p> for leaf nodes, that there is an entry in the %_rowid
925 table corresponding to the cell's rowid value that
926 points to the correct node.
927 </p></li><li><p> for cells on non-leaf nodes, that there is an entry in the
928 %_parent table mapping from the cell's child node to the
929 node that it resides on.
930 </p></li></ol>
931 </li><li><p>
932 That there are the same number of entries in the %_rowid table
933 as there are leaf cells in the r-tree structure, and that there
934 is a leaf cell that corresponds to each entry in the %_rowid table.
935 </p></li><li><p>
936 That there are the same number of entries in the %_parent table
937 as there are non-leaf cells in the r-tree structure, and that
938 there is a non-leaf cell that corresponds to each entry in the
939 %_parent table.
940 </p></li></ol>
941 <p align="center"><small><i>This page last modified on <a href="https://sqlite.org/docsrc/honeypot" id="mtimelink" data-href="https://sqlite.org/docsrc/finfo/pages/rtree.in?m=703d907909">2023-02-20 00:00:42</a> UTC </small></i></p>
942