Debian Codegraph @

www/fts5.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>SQLite FTS5 Extension</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 SQLite FTS5 Extension
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_of_fts5">1. Overview of FTS5</a></div>
129 <div class="fancy-toc1"><a href="#compiling_and_using_fts5">2. Compiling and Using FTS5</a></div>
130 <div class="fancy-toc2"><a href="#building_fts5_as_part_of_sqlite">2.1. Building FTS5 as part of SQLite</a></div>
131 <div class="fancy-toc2"><a href="#building_a_loadable_extension">2.2. Building a Loadable Extension</a></div>
132 <div class="fancy-toc1"><a href="#full_text_query_syntax">3. Full-text Query Syntax</a></div>
133 <div class="fancy-toc2"><a href="#fts5_strings">3.1. FTS5 Strings</a></div>
134 <div class="fancy-toc2"><a href="#fts5_phrases">3.2. FTS5 Phrases</a></div>
135 <div class="fancy-toc2"><a href="#fts5_prefix_queries">3.3. FTS5 Prefix Queries</a></div>
136 <div class="fancy-toc2"><a href="#fts5_initial_token_queries">3.4. FTS5 Initial Token Queries</a></div>
137 <div class="fancy-toc2"><a href="#fts5_near_queries">3.5. FTS5 NEAR Queries</a></div>
138 <div class="fancy-toc2"><a href="#fts5_column_filters">3.6. FTS5 Column Filters</a></div>
139 <div class="fancy-toc2"><a href="#fts5_boolean_operators">3.7. FTS5 Boolean Operators</a></div>
140 <div class="fancy-toc1"><a href="#fts5_table_creation_and_initialization">4. FTS5 Table Creation and Initialization</a></div>
141 <div class="fancy-toc2"><a href="#the_unindexed_column_option">4.1. The UNINDEXED column option</a></div>
142 <div class="fancy-toc2"><a href="#prefix_indexes">4.2. Prefix Indexes</a></div>
143 <div class="fancy-toc2"><a href="#tokenizers">4.3. Tokenizers</a></div>
144 <div class="fancy-toc3"><a href="#unicode61_tokenizer">4.3.1. Unicode61 Tokenizer</a></div>
145 <div class="fancy-toc3"><a href="#ascii_tokenizer">4.3.2. Ascii Tokenizer</a></div>
146 <div class="fancy-toc3"><a href="#porter_tokenizer">4.3.3. Porter Tokenizer</a></div>
147 <div class="fancy-toc3"><a href="#the_trigram_tokenizer">4.3.4. The Trigram Tokenizer</a></div>
148 <div class="fancy-toc2"><a href="#external_content_and_contentless_tables">4.4. External Content and Contentless Tables</a></div>
149 <div class="fancy-toc3"><a href="#contentless_tables">4.4.1. Contentless Tables</a></div>
150 <div class="fancy-toc3"><a href="#contentless_delete_tables">4.4.2. Contentless-Delete Tables</a></div>
151 <div class="fancy-toc3"><a href="#external_content_tables">4.4.3. External Content Tables</a></div>
152 <div class="fancy-toc3"><a href="#external_content_table_pitfalls">4.4.4. External Content Table Pitfalls</a></div>
153 <div class="fancy-toc2"><a href="#the_columnsize_option">4.5. The Columnsize Option</a></div>
154 <div class="fancy-toc2"><a href="#the_detail_option">4.6. The Detail Option</a></div>
155 <div class="fancy-toc2"><a href="#the_tokendata_option">4.7. The Tokendata Option</a></div>
156 <div class="fancy-toc1"><a href="#_auxiliary_functions_">5. Auxiliary Functions </a></div>
157 <div class="fancy-toc2"><a href="#built_in_auxiliary_functions">5.1. Built-in Auxiliary Functions</a></div>
158 <div class="fancy-toc3"><a href="#the_bm25_function">5.1.1. The bm25() function</a></div>
159 <div class="fancy-toc3"><a href="#the_highlight_function">5.1.2. The highlight() function</a></div>
160 <div class="fancy-toc3"><a href="#the_snippet_function">5.1.3. The snippet() function</a></div>
161 <div class="fancy-toc2"><a href="#sorting_by_auxiliary_function_results">5.2. Sorting by Auxiliary Function Results</a></div>
162 <div class="fancy-toc1"><a href="#special_insert_commands">6. Special INSERT Commands</a></div>
163 <div class="fancy-toc2"><a href="#the_automerge_configuration_option">6.1. The 'automerge' Configuration Option</a></div>
164 <div class="fancy-toc2"><a href="#the_crisismerge_configuration_option">6.2. The 'crisismerge' Configuration Option</a></div>
165 <div class="fancy-toc2"><a href="#the_delete_command">6.3. The 'delete' Command</a></div>
166 <div class="fancy-toc2"><a href="#the_delete_all_command">6.4. The 'delete-all' Command</a></div>
167 <div class="fancy-toc2"><a href="#the_deletemerge_configuration_option">6.5. The 'deletemerge' Configuration Option</a></div>
168 <div class="fancy-toc2"><a href="#the_integrity_check_command">6.6. The 'integrity-check' Command</a></div>
169 <div class="fancy-toc2"><a href="#the_merge_command">6.7. The 'merge' Command</a></div>
170 <div class="fancy-toc2"><a href="#the_optimize_command">6.8. The 'optimize' Command</a></div>
171 <div class="fancy-toc2"><a href="#the_pgsz_configuration_option">6.9. The 'pgsz' Configuration Option</a></div>
172 <div class="fancy-toc2"><a href="#the_rank_configuration_option">6.10. The 'rank' Configuration Option</a></div>
173 <div class="fancy-toc2"><a href="#the_rebuild_command">6.11. The 'rebuild' Command</a></div>
174 <div class="fancy-toc2"><a href="#the_secure_delete_configuration_option">6.12. The 'secure-delete' Configuration Option</a></div>
175 <div class="fancy-toc2"><a href="#the_usermerge_configuration_option">6.13. The 'usermerge' Configuration Option</a></div>
176 <div class="fancy-toc1"><a href="#extending_fts5">7. Extending FTS5</a></div>
177 <div class="fancy-toc2"><a href="#custom_tokenizers">7.1. Custom Tokenizers</a></div>
178 <div class="fancy-toc3"><a href="#synonym_support">7.1.1. Synonym Support</a></div>
179 <div class="fancy-toc2"><a href="#custom_auxiliary_functions">7.2. Custom Auxiliary Functions</a></div>
180 <div class="fancy-toc3"><a href="#custom_auxiliary_functions_api_overview">7.2.1. Custom Auxiliary Functions API Overview</a></div>
181 <div class="fancy-toc3"><a href="#custom_auxiliary_functions_api_reference">7.2.2. Custom Auxiliary Functions API Reference</a></div>
182 <div class="fancy-toc1"><a href="#the_fts5vocab_virtual_table_module">8. The fts5vocab Virtual Table Module</a></div>
183 <div class="fancy-toc1"><a href="#fts5_data_structures">9. FTS5 Data Structures</a></div>
184 <div class="fancy-toc2"><a href="#varint_format">9.1. Varint Format</a></div>
185 <div class="fancy-toc2"><a href="#the_fts_index_idx_and_data_tables_">9.2. The FTS Index (%_idx and %_data tables)</a></div>
186 <div class="fancy-toc3"><a href="#data_structure">9.2.1. The %_data Table Rowid Space</a></div>
187 <div class="fancy-toc3"><a href="#structure_record_format">9.2.2. Structure Record Format</a></div>
188 <div class="fancy-toc3"><a href="#averages_record_format">9.2.3. Averages Record Format</a></div>
189 <div class="fancy-toc3"><a href="#segment_b_tree_format">9.2.4. Segment B-Tree Format</a></div>
190 <div class="fancy-toc4"><a href="#the_key_doclist_format">9.2.4.1. The Key/Doclist Format</a></div>
191 <div class="fancy-toc4"><a href="#data_pagination">9.2.4.2. Pagination</a></div>
192 <div class="fancy-toc4"><a href="#data_term_index">9.2.4.3. Segment Index Format</a></div>
193 <div class="fancy-toc4"><a href="#doclist_index_format">9.2.4.4. Doclist Index Format</a></div>
194 <div class="fancy-toc2"><a href="#document_sizes_table_docsize_table_">9.3. Document Sizes Table (%_docsize table)</a></div>
195 <div class="fancy-toc2"><a href="#the_table_contents_content_table_">9.4. The Table Contents (%_content table)</a></div>
196 <div class="fancy-toc2"><a href="#configuration_options_config_table_">9.5. Configuration Options (%_config table)</a></div>
197 <div class="fancy-toc1"><a href="#appendix_a">
198 Appendix A: Comparison with FTS3/4
199 </a></div>
200 <div class="fancy-toc2"><a href="#_application_porting_guide_"> Application Porting Guide </a></div>
201 <div class="fancy-toc3"><a href="#_changes_to_create_virtual_table_statements_"> Changes to CREATE VIRTUAL TABLE statements </a></div>
202 <div class="fancy-toc3"><a href="#_changes_to_select_statements_"> Changes to SELECT statements </a></div>
203 <div class="fancy-toc3"><a href="#_auxiliary_function_changes_"> Auxiliary Function Changes </a></div>
204 <div class="fancy-toc3"><a href="#_other_issues"> Other Issues</a></div>
205 <div class="fancy-toc2"><a href="#_summary_of_technical_differences_">
206 Summary of Technical Differences
207 </a></div>
208 </div>
209 </div>
210 <script>
211 function toggle_toc(){
212 var sub = document.getElementById("toc_sub")
213 var mk = document.getElementById("toc_mk")
214 if( sub.style.display!="block" ){
215 sub.style.display = "block";
216 mk.innerHTML = "&#x25bc;";
217 } else {
218 sub.style.display = "none";
219 mk.innerHTML = "&#x25ba;";
220 }
221 }
222 </script>
223 </div>
224
225
226
227
228
229
230 <h1 id="overview_of_fts5"><span>1. </span>Overview of FTS5</h1>
231
232 <p>FTS5 is an SQLite <a href="c3ref/module.html">virtual table module</a> that provides
233 <a href="https://en.wikipedia.org/wiki/Full_text_search">full-text search</a>
234 functionality to database applications. In their most elementary form,
235 full-text search engines allow the user to efficiently search a large
236 collection of documents for the subset that contain one or more instances of a
237 search term. The search functionality provided to world wide web users by
238 <a href="https://www.google.com/">Google</a> is, among other things, a full-text search
239 engine, as it allows users to search for all documents on the web that contain,
240 for example, the term "fts5".
241
242 </p><p>To use FTS5, the user creates an FTS5 virtual table with one or more
243 columns. For example:
244
245 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE email USING fts5(sender, title, body);
246 </pre></div>
247
248 <p>It is an error to add types, constraints or <a href="lang_createtable.html#primkeyconst">PRIMARY KEY</a> declarations to
249 a CREATE VIRTUAL TABLE statement used to create an FTS5 table. Once created,
250 an FTS5 table may be populated using <a href="lang_insert.html">INSERT</a>, <a href="lang_update.html">UPDATE</a> or <a href="lang_delete.html">DELETE</a> statements
251 like any other table. Like any other table with no PRIMARY KEY declaration, an
252 FTS5 table has an implicit INTEGER PRIMARY KEY field named rowid.
253
254 </p><p>Not shown in the example above is that there are also
255 <a href="fts5.html#fts5_table_creation_and_initialization">various options</a> that may be provided to FTS5 as
256 part of the CREATE VIRTUAL TABLE statement to configure various aspects of the
257 new table. These may be used to modify the way in which the FTS5 table extracts
258 terms from documents and queries, to create extra indexes on disk to speed up
259 prefix queries, or to create an FTS5 table that acts as an index on content
260 stored elsewhere.
261
262 </p><p>Once populated, there are three ways to execute a full-text query against
263 the contents of an FTS5 table:
264
265 </p><ul><li> Using a MATCH operator in the WHERE clause of a SELECT statement, or
266 </li><li> Using an equals ("=") operator in the WHERE clause of a SELECT statement, or
267 </li><li> using the <a href="vtab.html#tabfunc2">table-valued function</a> syntax.
268 </li></ul>
269
270 <p>If using the MATCH or = operators, the expression to the left of the MATCH
271 operator is usually the name of the FTS5 table (the exception is when
272 <a href="fts5.html#fts5_column_filters">specifying a column-filter</a>). The expression on the right
273 must be a text value specifying the term to search for. For the table-valued
274 function syntax, the term to search for is specified as the first table argument.
275 For example:
276
277 </p><div class="codeblock"><pre><i>-- Query for all rows that contain at least once instance of the term</i>
278 <i>-- "fts5" (in any column). The following three queries are equivalent.</i>
279 SELECT * FROM email WHERE email MATCH 'fts5';
280 SELECT * FROM email WHERE email = 'fts5';
281 SELECT * FROM email('fts5');
282 </pre></div>
283
284 <p> By default, FTS5 full-text searches are case-independent. Like any other
285 SQL query that does not contain an ORDER BY clause, the example above returns
286 results in an arbitrary order. To sort results by relevance (most to least
287 relevant), an ORDER BY may be added to a full-text query as follows:
288
289 </p><div class="codeblock"><pre><i>-- Query for all rows that contain at least once instance of the term</i>
290 <i>-- "fts5" (in any column). Return results in order from best to worst</i>
291 <i>-- match. </i>
292 SELECT * FROM email WHERE email MATCH 'fts5' ORDER BY rank;
293 </pre></div>
294
295 <p> As well as the column values and rowid of a matching row, an application
296 may use <a href="fts5.html#_auxiliary_functions_">FTS5 auxiliary functions</a> to retrieve extra information regarding
297 the matched row. For example, an auxiliary function may be used to retrieve
298 a copy of a column value for a matched row with all instances of the matched
299 term surrounded by html &lt;b&gt;&lt;/b&gt; tags. Auxiliary functions are
300 invoked in the same way as SQLite <a href="lang_corefunc.html">scalar functions</a>, except that the name
301 of the FTS5 table is specified as the first argument. For example:
302
303 </p><div class="codeblock"><pre><i>-- Query for rows that match "fts5". Return a copy of the "body" column</i>
304 <i>-- of each row with the matches surrounded by &lt;b&gt;&lt;/b&gt; tags.</i>
305 SELECT highlight(email, 2, '&lt;b&gt;', '&lt;/b&gt;') FROM email('fts5');
306 </pre></div>
307
308 <p>A description of the available auxiliary functions, and more details
309 regarding configuration of the special "rank" column, are
310 <a href="fts5.html#_auxiliary_functions_">available below</a>. <a href="fts5.html#custom_auxiliary_functions">Custom auxiliary functions</a> may also be implemented in C and registered with
311 FTS5, just as custom SQL functions may be registered with the SQLite core.
312
313 </p><p> As well as searching for all rows that contain a term, FTS5 allows
314 the user to search for rows that contain:
315
316 </p><ul>
317 <li> any terms that begin with a specified prefix,
318 </li><li> "phrases" - sequences of terms or prefix terms that must feature in a
319 document for it to match the query,
320 </li><li> sets of terms, prefix terms or phrases that appear within a specified
321 proximity of each other (these are called "NEAR queries"), or
322 </li><li> boolean combinations of any of the above.
323 </li></ul>
324
325 <p> Such advanced searches are requested by providing a more complicated
326 FTS5 query string as the text to the right of the MATCH operator (or =
327 operator, or as the first argument to a table-valued function syntax). The
328 full query syntax is <a href="fts5.html#full_text_query_syntax">described here</a>.
329
330 </p><a name="compiling_and_using_fts5"></a>
331 <h1 tags="FTS5 building" id="compiling_and_using_fts5"><span>2. </span>Compiling and Using FTS5</h1>
332
333 <h2 id="building_fts5_as_part_of_sqlite"><span>2.1. </span>Building FTS5 as part of SQLite</h2>
334
335 <p>As of <a href="releaselog/3_9_0.html">version 3.9.0</a> (2015-10-14),
336 FTS5 is included as part of the SQLite <a href="amalgamation.html">amalgamation</a>.
337 If using one of the two autoconf build system, FTS5 is
338 enabled by specifying the "--enable-fts5" option when running the configure
339 script. (FTS5 is currently disabled by default for the
340 source-tree configure script and enabled by default for
341 the amalgamation configure script, but these defaults might
342 change in the future.)
343
344 </p><p>Or, if sqlite3.c is compiled using some other build system, by arranging for
345 the SQLITE_ENABLE_FTS5 pre-processor symbol to be defined.
346
347 </p><h2 id="building_a_loadable_extension"><span>2.2. </span>Building a Loadable Extension</h2>
348
349 <p>Alternatively, FTS5 may be built as a loadable extension.
350
351 </p><p>The canonical FTS5 source code consists of a series of *.c and other files
352 in the "ext/fts5" directory of the SQLite source tree. A build process reduces
353 this to just two files - "fts5.c" and "fts5.h" - which may be used to build an
354 SQLite loadable extension.
355
356 </p><ol>
357 <li> Obtain the latest SQLite code from fossil.
358 </li><li> Create a Makefile as described in <a href="howtocompile.html">How To Compile SQLite</a>.
359 </li><li> Build the "fts5.c" target. Which also creates fts5.h.
360 </li></ol>
361
362 <div class="codeblock"><pre>$ wget -c https://www.sqlite.org/src/tarball/SQLite-trunk.tgz?uuid=trunk -O SQLite-trunk.tgz
363 .... output ...
364 $ tar -xzf SQLite-trunk.tgz
365 $ cd SQLite-trunk
366 $ ./configure && make fts5.c
367 ... lots of output ...
368 $ ls fts5.&#91;ch]
369 fts5.c fts5.h
370 </pre></div>
371
372 <p>
373 The code in "fts5.c" may then be compiled into a loadable extension or
374 statically linked into an application as described in
375 <a href="loadext.html#build">Compiling Loadable Extensions</a>. There are two entry points defined, both
376 of which do the same thing:
377
378 </p><ul>
379 <li> sqlite3_fts_init
380 </li><li> sqlite3_fts5_init
381 </li></ul>
382
383 <p>
384 The other file, "fts5.h", is not required to compile the FTS5 extension.
385 It is used by applications that implement <a href="fts5.html#extending_fts5">custom FTS5 tokenizers or auxiliary functions</a>.
386
387 </p><a name="full_text_query_syntax"></a>
388 <h1 tags="FTS5 query syntax" id="full_text_query_syntax"><span>3. </span>Full-text Query Syntax</h1>
389
390 <p>
391 The following block contains a summary of the FTS query syntax in BNF form.
392 A detailed explanation follows.
393
394 </p><div class="codeblock"><pre>&lt;phrase&gt; := string &#91;*]
395 &lt;phrase&gt; := &lt;phrase&gt; + &lt;phrase&gt;
396 &lt;neargroup&gt; := NEAR ( &lt;phrase&gt; &lt;phrase&gt; ... &#91;, N] )
397 &lt;query&gt; := &#91; &#91;-] &lt;colspec&gt; :] &#91;&#94;] &lt;phrase&gt;
398 &lt;query&gt; := &#91; &#91;-] &lt;colspec&gt; :] &lt;neargroup&gt;
399 &lt;query&gt; := &#91; &#91;-] &lt;colspec&gt; :] ( &lt;query&gt; )
400 &lt;query&gt; := &lt;query&gt; AND &lt;query&gt;
401 &lt;query&gt; := &lt;query&gt; OR &lt;query&gt;
402 &lt;query&gt; := &lt;query&gt; NOT &lt;query&gt;
403 &lt;colspec&gt; := colname
404 &lt;colspec&gt; := { colname1 colname2 ... }
405 </pre></div>
406
407 <a name="fts5_strings"></a>
408 <h2 tags="FTS5 Strings" id="fts5_strings"><span>3.1. </span>FTS5 Strings</h2>
409 <p>
410 Within an FTS expression a <b>string</b> may be specified in one of two ways:
411
412 </p><ul>
413 <li> <p>By enclosing it in double quotes ("). Within a string, any embedded
414 double quote characters may be escaped SQL-style - by adding a second
415 double-quote character.
416
417 </p></li><li> <p>As an FTS5 bareword that is not "AND", "OR" or "NOT" (case sensitive).
418 An FTS5 bareword is a string of one or more consecutive characters that
419 are all either:
420
421 </p><ul>
422 <li> Non-ASCII range characters (i.e. unicode codepoints greater
423 than 127), or
424 </li><li> One of the 52 upper and lower case ASCII characters, or
425 </li><li> One of the 10 decimal digit ASCII characters, or
426 </li><li> The underscore character (unicode codepoint 96).
427 </li><li> The substitute character (unicode codepoint 26).
428 </li></ul>
429
430 Strings that include any other characters must be quoted. Characters
431 that are not currently allowed in barewords, are not quote characters and
432 do not currently serve any special purpose in FTS5 query expressions may
433 at some point in the future be allowed in barewords or used to implement
434 new query functionality. This means that queries that are currently
435 syntax errors because they include such a character outside of a quoted
436 string may be interpreted differently by some future version of FTS5.
437 </li></ul>
438
439 <a name="fts5_phrases"></a>
440 <h2 tags="FTS5 Phrases" id="fts5_phrases"><span>3.2. </span>FTS5 Phrases</h2>
441 <p>
442 Each string in an fts5 query is parsed ("tokenized") by the
443 <a href="fts5.html#tokenizers">tokenizer</a> and a list of zero or more <b>tokens</b>, or
444 terms, extracted. For example, the default tokenizer tokenizes the string "alpha
445 beta gamma" to three separate tokens - "alpha", "beta" and "gamma" - in that
446 order.
447
448 </p><p>
449 FTS queries are made up of <b>phrases</b>. A phrase is an ordered list of
450 one or more tokens. The tokens from each string in the query each make up a
451 single phrase. Two phrases can be concatenated into a single large phrase
452 using the "+" operator. For example, assuming the tokenizer module being used
453 tokenizes the input "one.two.three" to three separate tokens, the following
454 four queries all specify the same phrase:
455
456 </p><div class="codeblock"><pre>... MATCH '"one two three"'
457 ... MATCH 'one + two + three'
458 ... MATCH '"one two" + three'
459 ... MATCH 'one.two.three'
460 </pre></div>
461
462 <p>
463 A phrase matches a document if the document contains at least one sub-sequence
464 of tokens that matches the sequence of tokens that make up the phrase.
465
466 </p><a name="fts5_prefix_queries"></a>
467 <h2 tags="FTS5 prefix queries" id="fts5_prefix_queries"><span>3.3. </span>FTS5 Prefix Queries</h2>
468 <p>
469 If a "*" character follows a string within an FTS expression, then the final
470 token extracted from the string is marked as a <b>prefix token</b>. As you
471 might expect, a prefix token matches any document token of which it is a
472 prefix. For example, the first two queries in the following block will match
473 any document that contains the token "one" immediately followed by the token
474 "two" and then any token that begins with "thr".
475
476 </p><div class="codeblock"><pre>... MATCH '"one two thr" * '
477 ... MATCH 'one + two + thr*'
478 ... MATCH '"one two thr*"' <b>-- May not work as expected!</b>
479 </pre></div>
480
481 <p>The final query in the block above may not work as expected. Because the
482 "*" character is inside the double-quotes, it will be passed to the tokenizer,
483 which will likely discard it (or perhaps, depending on the specific tokenizer
484 in use, include it as part of the final token) instead of recognizing it as
485 a special FTS character.
486
487 <a name="carrotq"></a>
488
489 </p><a name="fts5_initial_token_queries"></a>
490 <h2 tags="FTS5 initial token queries" id="fts5_initial_token_queries"><span>3.4. </span>FTS5 Initial Token Queries</h2>
491 <p>
492 If a "&#94;" character appears immediately before a phrase that is not part of a
493 NEAR query, then that phrase only matches a document only if it starts at the
494 first token in a column. The "&#94;" syntax may be combined with a
495 <a href="fts5.html#fts5_column_filters">column filter</a>, but may not be inserted into the middle of
496 a phrase.
497
498 </p><div class="codeblock"><pre>... MATCH '&#94;one' <i>-- first token in any column must be "one"</i>
499 ... MATCH '&#94; one + two' <i>-- phrase "one two" must appear at start of a column</i>
500 ... MATCH '&#94; "one two"' <i>-- same as previous </i>
501 ... MATCH 'a : &#94;two' <i>-- first token of column "a" must be "two"</i>
502 ... MATCH 'NEAR(&#94;one, two)' <b>-- syntax error! </b>
503 ... MATCH 'one + &#94;two' <b>-- syntax error! </b>
504 ... MATCH '"&#94;one two"' <b>-- May not work as expected!</b>
505 </pre></div>
506
507 <a name="fts5_near_queries"></a>
508 <h2 tags="FTS5 NEAR queries" id="fts5_near_queries"><span>3.5. </span>FTS5 NEAR Queries</h2>
509
510 <p>Two or more phrases may be grouped into a <b>NEAR group</b>. A NEAR group
511 is specified by the token "NEAR" (case sensitive) followed by an open
512 parenthesis character, followed by two or more whitespace separated phrases, optionally followed by a comma and the numeric parameter <i>N</i>, followed by
513 a close parenthesis. For example:
514
515 </p><div class="codeblock"><pre>... MATCH 'NEAR("one two" "three four", 10)'
516 ... MATCH 'NEAR("one two" thr* + four)'
517 </pre></div>
518
519 <p>If no <i>N</i> parameter is supplied, it defaults to 10. A NEAR group
520 matches a document if the document contains at least one clump of tokens that:
521
522 </p><ol>
523 <li> contains at least one instance of each phrase, and
524 </li><li> for which the number of tokens between the end of the first phrase
525 and the beginning of the last phrase in the clump is less than or equal to <i>N</i>.
526 </li></ol>
527
528 <p>For example:
529
530 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE f USING fts5(x);
531 INSERT INTO f(rowid, x) VALUES(1, 'A B C D x x x E F x');
532
533 ... MATCH 'NEAR(e d, 4)'; <i>-- Matches!</i>
534 ... MATCH 'NEAR(e d, 3)'; <i>-- Matches!</i>
535 ... MATCH 'NEAR(e d, 2)'; <i>-- Does not match!</i>
536
537 ... MATCH 'NEAR("c d" "e f", 3)'; <i>-- Matches!</i>
538 ... MATCH 'NEAR("c" "e f", 3)'; <i>-- Does not match!</i>
539
540 ... MATCH 'NEAR(a d e, 6)'; <i>-- Matches!</i>
541 ... MATCH 'NEAR(a d e, 5)'; <i>-- Does not match!</i>
542
543 ... MATCH 'NEAR("a b c d" "b c" "e f", 4)'; <i>-- Matches!</i>
544 ... MATCH 'NEAR("a b c d" "b c" "e f", 3)'; <i>-- Does not match!</i>
545 </pre></div>
546
547 <a name="fts5_column_filters"></a>
548 <h2 tags="FTS5 column filters" id="fts5_column_filters"><span>3.6. </span>FTS5 Column Filters</h2>
549
550 <p>
551 A single phrase or NEAR group may be restricted to matching text within a
552 specified column of the FTS table by prefixing it with the column name
553 followed by a colon character. Or to a set of columns by prefixing it
554 with a whitespace separated list of column names enclosed in parenthesis
555 ("curly brackets") followed by a colon character. Column names may be specified
556 using either of the two forms described for strings above. Unlike strings that
557 are part of phrases, column names are not passed to the tokenizer module.
558 Column names are case-insensitive in the usual way for SQLite column names -
559 upper/lower case equivalence is understood for ASCII-range characters only.
560
561 </p><div class="codeblock"><pre>... MATCH 'colname : NEAR("one two" "three four", 10)'
562 ... MATCH '"colname" : one + two + three'
563
564 ... MATCH '{col1 col2} : NEAR("one two" "three four", 10)'
565 ... MATCH '{col2 col1 col3} : one + two + three'
566 </pre></div>
567
568 <p>
569 If a column filter specification is preceded by a "-" character, then
570 it is interpreted as a list of column not to match against. For example:
571
572 </p><div class="codeblock"><pre><i>-- Search for matches in all columns except "colname"</i>
573 ... MATCH '- colname : NEAR("one two" "three four", 10)'
574
575 <i>-- Search for matches in all columns except "col1", "col2" and "col3"</i>
576 ... MATCH '- {col2 col1 col3} : one + two + three'
577 </pre></div>
578
579 <p>
580 Column filter specifications may also be applied to arbitrary expressions
581 enclosed in parenthesis. In this case the column filter applies to all
582 phrases within the expression. Nested column filter operations may only
583 further restrict the subset of columns matched, they can not be used to
584 re-enable filtered columns. For example:
585
586 </p><div class="codeblock"><pre><i>-- The following are equivalent:</i>
587 ... MATCH '{a b} : ( {b c} : "hello" AND "world" )'
588 ... MATCH '(b : "hello") AND ({a b} : "world")'
589 </pre></div>
590
591 <p>
592 Finally, a column filter for a single column may be specified by using
593 the column name as the LHS of a MATCH operator (instead of the usual
594 table name). For example:
595
596 </p><div class="codeblock"><pre><i>-- Given the following table</i>
597 CREATE VIRTUAL TABLE ft USING fts5(a, b, c);
598
599 <i>-- The following are equivalent</i>
600 SELECT * FROM ft WHERE b MATCH 'uvw AND xyz';
601 SELECT * FROM ft WHERE ft MATCH 'b : (uvw AND xyz)';
602
603 <i>-- This query cannot match any rows (since all columns are filtered out): </i>
604 SELECT * FROM ft WHERE b MATCH 'a : xyz';
605 </pre></div>
606
607 <a name="fts5_boolean_operators"></a>
608 <h2 tags="FTS5 boolean operators" id="fts5_boolean_operators"><span>3.7. </span>FTS5 Boolean Operators</h2>
609
610 <p>
611 Phrases and NEAR groups may be arranged into expressions using <b>boolean
612 operators</b>. In order of precedence, from highest (tightest grouping) to
613 lowest (loosest grouping), the operators are:
614
615 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
616 <tr style="text-align:left"><th>Operator </th><th>Function
617
618 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td><code>&lt;query1&gt; NOT &lt;query2&gt;</code>
619 </td><td>Matches if query1 matches and query2 does not match.
620
621 </td></tr><tr style="text-align:left"><td><code>&lt;query1&gt; AND &lt;query2&gt;</code>
622 </td><td>Matches if both query1 and query2 match.
623
624 </td></tr><tr style="text-align:left;background-color:#DDDDDD"><td><code>&lt;query1&gt; OR &lt;query2&gt;</code>
625 </td><td>Matches if either query1 or query2 match.
626
627 </td></tr></table>
628
629 <p>
630 Parenthesis may be used to group expressions in order to modify operator
631 precedence in the usual ways. For example:
632
633 </p><div class="codeblock"><pre><i>-- Because NOT groups more tightly than OR, either of the following may</i>
634 <i>-- be used to match all documents that contain the token "two" but not</i>
635 <i>-- "three", or contain the token "one". </i>
636 ... MATCH 'one OR two NOT three'
637 ... MATCH 'one OR (two NOT three)'
638
639 <i>-- Matches documents that contain at least one instance of either "one"</i>
640 <i>-- or "two", but do not contain any instances of token "three".</i>
641 ... MATCH '(one OR two) NOT three'
642 </pre></div>
643
644 <p>
645 Phrases and NEAR groups may also be connected by <b>implicit AND operators</b>.
646 For simplicity, these are not shown in the BNF grammar above. Essentially, any
647 sequence of phrases or NEAR groups (including those restricted to matching
648 specified columns) separated only by whitespace are handled as if there were an
649 implicit AND operator between each pair of phrases or NEAR groups. Implicit
650 AND operators are never inserted after or before an expression enclosed in
651 parenthesis. Implicit AND operators group more tightly than all other
652 operators, including NOT. For example:
653
654 </p><div class="codeblock"><pre>... MATCH 'one two three' <i>-- 'one AND two AND three'</i>
655 ... MATCH 'three "one two"' <i>-- 'three AND "one two"'</i>
656 ... MATCH 'NEAR(one two) three' <i>-- 'NEAR(one two) AND three'</i>
657 ... MATCH 'one OR two three' <i>-- 'one OR two AND three'</i>
658 ... MATCH 'one NOT two three' <i>-- 'one NOT (two AND three)'</i>
659
660 ... MATCH '(one OR two) three' <i>-- Syntax error!</i>
661 ... MATCH 'func(one two)' <i>-- Syntax error!</i>
662 </pre></div>
663
664 <a name="fts5_table_creation_and_initialization"></a>
665 <h1 tags="FTS5 CREATE TABLE Options" id="fts5_table_creation_and_initialization"><span>4. </span>FTS5 Table Creation and Initialization</h1>
666
667 <p>Each argument specified as part of a "CREATE VIRTUAL TABLE ... USING fts5
668 ..." statement is either a column declaration or a configuration option. A
669 <b>column declaration</b> consists of one or more whitespace separated FTS5
670 barewords or string literals quoted in any manner acceptable to SQLite.
671
672 </p><p>The first string or bareword in a column declaration is the column name. It
673 is an error to attempt to name an fts5 table column "rowid" or "rank", or to
674 assign the same name to a column as is used by the table itself. This is not
675 supported.
676
677 </p><p>Each subsequent string or bareword in a column declaration is a column
678 option that modifies the behaviour of that column. Column options are
679 case-independent. Unlike the SQLite core, FTS5 considers unrecognized column
680 options to be errors. Currently, the only option recognized is
681 <a href="fts5.html#the_unindexed_column_option">"UNINDEXED" (see below)</a>.
682
683 </p><p>A <b>configuration option</b> consists of an FTS5 bareword - the option name -
684 followed by an "=" character, followed by the option value. The option value is
685 specified using either a single FTS5 bareword or a string literal, again quoted
686 in any manner acceptable to the SQLite core. For example:
687
688 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE mail USING fts5(sender, title, body, tokenize = 'porter ascii');
689 </pre></div>
690
691 <p> There are currently the following configuration options:
692
693 </p><ul>
694 <li> The "tokenize" option, used to configure a <a href="fts5.html#tokenizers">custom tokenizer</a>.
695 </li><li> The "prefix" option, used to add <a href="fts5.html#prefix_indexes">prefix indexes</a>
696 to an FTS5 table.
697 </li><li> The "content" option, used to make the FTS5 table an
698 <a href="fts5.html#external_content_and_contentless_tables">external content or contentless table</a>.
699 </li><li> The "content_rowid" option, used to set the rowid field of an
700 <a href="fts5.html#external_content_tables">external content table</a>.
701 </li><li> The <a href="fts5.html#the_columnsize_option">"columnsize" option</a>, used to configure
702 whether or not the size in tokens of each value in the FTS5 table is
703 stored separately within the database.
704 </li><li> The <a href="fts5.html#the_detail_option">"detail" option</a>. This option may be used
705 to reduce the size of the FTS index on disk by omitting some information
706 from it.
707 </li></ul>
708
709 <a name="the_unindexed_column_option"></a>
710 <h2 tags="unindexed" id="the_unindexed_column_option"><span>4.1. </span>The UNINDEXED column option</h2>
711
712 <p>The contents of columns qualified with the UNINDEXED column option are not
713 added to the FTS index. This means that for the purposes of MATCH queries and
714 <a href="fts5.html#_auxiliary_functions_">FTS5 auxiliary functions</a>, the column contains no matchable tokens.
715
716 </p><p>For example, to avoid adding the contents of the "uuid" field to the FTS
717 index:
718 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE customers USING fts5(name, addr, uuid UNINDEXED);
719 </pre></div>
720
721 <a name="prefix_indexes"></a>
722 <h2 tags="FTS5 prefix indexes" id="prefix_indexes"><span>4.2. </span>Prefix Indexes</h2>
723
724 <p> By default, FTS5 maintains a single index recording the location of each
725 token instance within the document set. This means that querying for complete
726 tokens is fast, as it requires a single lookup, but querying for a prefix
727 token can be slow, as it requires a range scan. For example, to query for
728 the prefix token "abc*" requires a range scan of all tokens greater than
729 or equal to "abc" and less than "abd".
730
731 </p><p> A prefix index is a separate index that records the location of all
732 instances of prefix tokens of a certain length in characters used to speed
733 up queries for prefix tokens. For example, optimizing a query for prefix
734 token "abc*" requires a prefix index of three-character prefixes.
735
736 </p><p> To add prefix indexes to an FTS5 table, the "prefix" option is set to
737 either a single positive integer or a text value containing a white-space
738 separated list of one or more positive integer values. A prefix index is
739 created for each integer specified. If more than one "prefix" option is
740 specified as part of a single CREATE VIRTUAL TABLE statement, all apply.
741
742 </p><div class="codeblock"><pre><i>-- Two ways to create an FTS5 table that maintains prefix indexes for
743 -- two and three character prefix tokens.</i>
744 CREATE VIRTUAL TABLE ft USING fts5(a, b, prefix='2 3');
745 CREATE VIRTUAL TABLE ft USING fts5(a, b, prefix=2, prefix=3);
746 </pre></div>
747
748 <a name="tokenizers"></a>
749 <h2 tags="FTS5 tokenizers" id="tokenizers"><span>4.3. </span>Tokenizers</h2>
750
751 <p> The CREATE VIRTUAL TABLE "tokenize" option is used to configure the
752 specific tokenizer used by the FTS5 table. The option argument must be either
753 an FTS5 bareword, or an SQL text literal. The text of the argument is itself
754 treated as a white-space series of one or more FTS5 barewords or SQL text
755 literals. The first of these is the name of the tokenizer to use. The second
756 and subsequent list elements, if they exist, are arguments passed to the
757 tokenizer implementation.
758
759 </p><p> Unlike option values and column names, SQL text literals intended as
760 tokenizers must be quoted using single quote characters. For example:
761
762 </p><div class="codeblock"><pre><i>-- The following are all equivalent</i>
763 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = 'porter ascii');
764 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = "porter ascii");
765 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = "'porter' 'ascii'");
766 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = '''porter'' ''ascii''');
767
768 <i>-- But this will fail:</i>
769 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = '"porter" "ascii"');
770
771 <i>-- This will fail too:</i>
772 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = 'porter' 'ascii');
773 </pre></div>
774
775
776 <p>
777 FTS5 features four built-in tokenizer modules, described in subsequent
778 sections:
779
780 </p><ul>
781 <li> The <b>unicode61</b> tokenizer, based on the Unicode 6.1 standard. This
782 is the default.
783
784 </li><li> The <b>ascii</b> tokenizer, which assumes all characters outside of
785 the ASCII codepoint range (0-127) are to be treated as token characters.
786
787 </li><li> The <b>porter</b> tokenizer, which implements the
788 <a href="https://tartarus.org/martin/PorterStemmer" /="1">porter stemming algorithm</a>.
789
790 </li><li> The <b>trigram</b> tokenizer, which treats each contiguous sequence of
791 three characters as a token, allowing FTS5 to support more general substring matching.
792 </li></ul>
793
794 <p> It is also possible to create custom tokenizers for FTS5. The API for doing so is <a href="fts5.html#custom_tokenizers">described here</a>.
795
796 </p><h3 id="unicode61_tokenizer"><span>4.3.1. </span>Unicode61 Tokenizer</h3>
797
798 <p> The unicode tokenizer classifies all unicode characters as either
799 "separator" or "token" characters. By default all space and punctuation
800 characters, as defined by Unicode 6.1, are considered separators, and all
801 other characters as token characters. More specifically, all unicode
802 characters assigned to a
803 <a href="https://en.wikipedia.org/wiki/Unicode_character_property#General_Category">
804 general category</a> beginning with "L" or "N" (letters and numbers,
805 specifically) or to category "Co" ("other, private use") are considered tokens.
806 All other characters are separators.
807
808 </p><p>Each contiguous run of one or more token characters is considered to be a
809 token. The tokenizer is case-insensitive according to the rules defined by
810 Unicode 6.1.
811
812 </p><p> By default, diacritics are removed from all Latin script characters. This
813 means, for example, that "A", "a", "&#192;", "&#224;", "&#194;" and "&#226;"
814 are all considered to be equivalent.
815
816 </p><p> Any arguments following "unicode61" in the token specification are treated
817 as a list of alternating option names and values. Unicode61 supports the
818 following options:
819
820 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
821 <tr style="text-align:left"><th> Option </th><th> Usage
822 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td> remove_diacritics
823 </td><td>This option should be set to "0", "1" or "2". The default value is "1".
824 If it is set to "1" or "2", then diacritics are removed from Latin script
825 characters as described above. However, if it is set to "1", then diacritics
826 are not removed in the fairly uncommon case where a single unicode codepoint
827 is used to represent a character with more that one diacritic. For example,
828 diacritics are not removed from codepoint 0x1ED9 ("LATIN SMALL LETTER O WITH
829 CIRCUMFLEX AND DOT BELOW"). This is technically a bug, but cannot be fixed
830 without creating backwards compatibility problems. If this option is set to
831 "2", then diacritics are correctly removed from all Latin characters.
832
833 </td></tr><tr style="text-align:left"><td> categories
834 </td><td>This option may be used to modify the set of Unicode general categories
835 that are considered to correspond to token characters. The argument must
836 consist of a space separated list of two-character general category
837 abbreviations (e.g. "Lu" or "Nd"), or of the same with the second character
838 replaced with an asterisk ("*"), interpreted as a glob pattern. The default
839 value is "L* N* Co".
840
841 </td></tr><tr style="text-align:left;background-color:#DDDDDD"><td> tokenchars
842 </td><td> This option is used to specify additional unicode characters that
843 should be considered token characters, even if they are white-space or
844 punctuation characters according to Unicode 6.1. All characters in the
845 string that this option is set to are considered token characters.
846
847 </td></tr><tr style="text-align:left"><td> separators
848 </td><td> This option is used to specify additional unicode characters that
849 should be considered as separator characters, even if they are token
850 characters according to Unicode 6.1. All characters in the string that
851 this option is set to are considered separators.
852 </td></tr></table>
853
854 <p> For example:
855
856 </p><div class="codeblock"><pre><i>-- Create an FTS5 table that does not remove diacritics from Latin
857 -- script characters, and that considers hyphens and underscore characters
858 -- to be part of tokens. </i>
859 CREATE VIRTUAL TABLE ft USING fts5(a, b,
860 tokenize = "unicode61 remove_diacritics 0 tokenchars '-_'"
861 );
862 </pre></div>
863
864 <p> or:
865
866 </p><div class="codeblock"><pre><i>-- Create an FTS5 table that, as well as the default token character classes,</i>
867 <i>-- considers characters in class "Mn" to be token characters.</i>
868 CREATE VIRTUAL TABLE ft USING fts5(a, b,
869 tokenize = "unicode61 categories 'L* N* Co Mn'"
870 );
871 </pre></div>
872
873 <p> The fts5 unicode61 tokenizer is byte-for-byte compatible with the fts3/4
874 unicode61 tokenizer.
875
876 </p><h3 id="ascii_tokenizer"><span>4.3.2. </span>Ascii Tokenizer</h3>
877
878 <p> The Ascii tokenizer is similar to the Unicode61 tokenizer, except that:
879
880 </p><ul>
881 <li> All non-ASCII characters (those with codepoints greater than 127) are
882 always considered token characters. If any non-ASCII characters are specified
883 as part of the separators option, they are ignored.
884
885 </li><li> Case-folding is only performed for ASCII characters. So while "A" and
886 "a" are considered to be equivalent, "&#195;" and "&#227;" are distinct.
887
888 </li><li> The remove_diacritics option is not supported.
889 </li></ul>
890
891 <p> For example:
892
893 </p><div class="codeblock"><pre><i>-- Create an FTS5 table that uses the ascii tokenizer, but does not
894 -- consider numeric characters to be part of tokens.</i>
895 CREATE VIRTUAL TABLE ft USING fts5(a, b,
896 tokenize = "ascii separators '0123456789'"
897 );
898 </pre></div>
899
900 <h3 id="porter_tokenizer"><span>4.3.3. </span>Porter Tokenizer</h3>
901
902 <p> The porter tokenizer is a wrapper tokenizer. It takes the output of some
903 other tokenizer and applies the
904 <a href="https://tartarus.org/martin/PorterStemmer/">porter stemming algorithm</a>
905 to each token before it returns it to FTS5. This allows search terms like
906 "correction" to match similar words such as "corrected" or "correcting". The
907 porter stemmer algorithm is designed for use with English language terms
908 only - using it with other languages may or may not improve search utility.
909
910 </p><p> By default, the porter tokenizer operates as a wrapper around the default
911 tokenizer (unicode61). Or, if one or more extra arguments are added to the
912 "tokenize" option following "porter", they are treated as a specification for
913 the underlying tokenizer that the porter stemmer uses. For example:
914
915 </p><div class="codeblock"><pre><i>-- Two ways to create an FTS5 table that uses the porter tokenizer to
916 -- stem the output of the default tokenizer (unicode61). </i>
917 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = porter);
918 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = 'porter unicode61');
919
920 <i>-- A porter tokenizer used to stem the output of the unicode61 tokenizer,
921 -- with diacritics removed before stemming.</i>
922 CREATE VIRTUAL TABLE t1 USING fts5(x, tokenize = 'porter unicode61 remove_diacritics 1');
923 </pre></div>
924
925 <a name="trigramidx"></a>
926
927 <h3 id="the_trigram_tokenizer"><span>4.3.4. </span>The Trigram Tokenizer</h3>
928
929 <p>
930 The trigram tokenizer extends FTS5 to support substring
931 matching in general, instead of the usual token matching. When using the
932 trigram tokenizer, a query or phrase token may match any sequence of characters
933 within a row, not just a complete token. For example:
934
935 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE tri USING fts5(a, tokenize="trigram");
936 INSERT INTO tri VALUES('abcdefghij KLMNOPQRST uvwxyz');
937
938 <i>-- The following queries all match the single row in the table</i>
939 SELECT * FROM tri('cdefg');
940 SELECT * FROM tri('cdefg AND pqr');
941 SELECT * FROM tri('"hij klm" NOT stuv');
942 </pre></div>
943
944 <p>
945 The trigram tokenizer supports the following options:
946
947 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
948 <tr style="text-align:left"><th> Option </th><th> Usage
949 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td> case_sensitive
950 </td><td> This value may be set to 1 or 0 (the default). If it is set to 1,
951 then matching is case sensitive. Otherwise, if this option is set to
952 0, matching is case insensitive.
953
954 </td></tr><tr style="text-align:left"><td> remove_diacritics
955 </td><td> This value may also be set to 1 or 0 (the default). It may only
956 be set to 1 if the case_sensitive options is set to 0 - setting both
957 options to 1 is an error. If this option is set, then diacritics are
958 removed from the text before matching (e.g. so that "á" matches "a").
959 </td></tr></table>
960
961 <div class="codeblock"><pre><i>-- A case-sensitive trigram index</i>
962 CREATE VIRTUAL TABLE tri USING fts5(a, tokenize="trigram case_sensitive 1");
963 </pre></div>
964
965 <p>
966 Unless the remove_diacritics option is set, FTS5 tables that use the trigram
967 tokenizer also support indexed GLOB and LIKE pattern matching. For example:
968
969 </p><div class="codeblock"><pre>SELECT * FROM tri WHERE a LIKE '%cdefg%';
970 SELECT * FROM tri WHERE a GLOB '*ij klm*xyz';
971 </pre></div>
972
973 <p>
974 If an FTS5 trigram tokenizer is created with the case_sensitive option set to 1,
975 it may only index GLOB queries, not LIKE.
976
977 </p><p>
978 Notes:
979
980 </p><ul>
981 <li> Substrings consisting of fewer than 3 unicode characters do not match any
982 rows when used with a full-text query. If a LIKE or GLOB pattern does not
983 contain at least one sequence of non-wildcard unicode characters, FTS5
984 falls back to a linear scan of the entire table.
985
986 </li><li> If the FTS5 table is created with the detail=none or detail=column option
987 specified, full-text queries may not contain any tokens longer than 3
988 unicode characters. LIKE and GLOB pattern matching may be slightly slower,
989 but still works. If the index is to be used only for LIKE and/or GLOB
990 pattern matching, these options are worth experimenting with to reduce
991 the index size.
992
993 </li><li> The index cannot be used to optimize LIKE patterns if the LIKE operator
994 has an ESCAPE clause.
995 </li></ul>
996
997 <a name="external_content_and_contentless_tables"></a>
998 <h2 tags="FTS5 content option" id="external_content_and_contentless_tables"><span>4.4. </span>External Content and Contentless Tables</h2>
999
1000 <p>
1001 Normally, when a row is inserted into an FTS5 table, in addition to building
1002 the index, FTS5 makes a copy of the original row content.
1003 When column values are requested from the FTS5 table by the user or by an
1004 auxiliary function implementation, those values are
1005 read from that private copy of the content. The "content" option may be used
1006 to create an FTS5 table that stores only FTS full-text index entries.
1007 Because the column values themselves are usually much larger than the
1008 associated full-text index entries, this can save significant database space.
1009
1010 </p><p>
1011 There are two ways to use the "content" option:
1012 </p><ul>
1013 <li> By setting it to an empty string to create a contentless FTS5 table. In
1014 this case FTS5 assumes that the original column values are unavailable
1015 to it when processing queries. Full-text queries and some auxiliary
1016 functions can still be used, but no column values apart from the rowid
1017 may be read from the table.
1018
1019 </li><li> By setting it to the name of a database object (table, virtual table or
1020 view) that may be queried by FTS5 at any time to retrieve the column
1021 values. This is known as an "external content" table. In this case all
1022 FTS5 functionality may be used, but it is the responsibility of the user
1023 to ensure that the contents of the full-text index are consistent with
1024 the named database object. If they are not, query results may be
1025 unpredictable.
1026 </li></ul>
1027
1028 <a name="contentless_tables"></a>
1029 <h3 tags="FTS5 contentless tables" id="contentless_tables"><span>4.4.1. </span>Contentless Tables</h3>
1030
1031 <p> A contentless FTS5 table is created by setting the "content" option to
1032 an empty string. For example:
1033
1034 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE f1 USING fts5(a, b, c, content='');
1035 </pre></div>
1036
1037 <p> Contentless FTS5 tables do not support UPDATE or DELETE statements, or
1038 INSERT statements that do not supply a non-NULL value for the rowid field.
1039 Contentless tables do not support REPLACE conflict handling. REPLACE
1040 and INSERT OR REPLACE statements are treated as regular INSERT statements.
1041 Rows may be deleted from a contentless table using an <a href="fts5.html#the_delete_command">FTS5 delete command</a>.
1042
1043 </p><p> Attempting to read any column value except the rowid from a contentless
1044 FTS5 table returns an SQL NULL value.
1045
1046 <a name="clssdeltab"></a>
1047
1048 </p><a name="contentless_delete_tables"></a>
1049 <h3 tags="FTS5 contentless-delete tables" id="contentless_delete_tables"><span>4.4.2. </span>Contentless-Delete Tables</h3>
1050
1051 <p>As of version 3.43.0, also available are contentless-delete tables.
1052 A contentless-delete table is created by setting the content option to an
1053 empty string and also setting the contentless_delete option to 1. For example:
1054
1055 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE f1 USING fts5(a, b, c, content='', contentless_delete=1);
1056 </pre></div>
1057
1058 <p>A contentless-delete table differs from a contentless table in that:
1059
1060 </p><ul>
1061 <li> Contentless-delete tables support both DELETE and "INSERT OR REPLACE
1062 INTO" statements.
1063 </li><li> Contentless-delete tables support UPDATE statements, but only if new
1064 values are supplied for all user-defined columns of the fts5 table.
1065 </li><li> Contentless-delete tables do <b>not</b> support the
1066 <a href="fts5.html#the_delete_command">FTS5 delete command</a>.
1067 </li></ul>
1068
1069 <div class="codeblock"><pre><i>-- Supported UPDATE statement:</i>
1070 UPDATE f1 SET a=?, b=?, c=? WHERE rowid=?;
1071
1072 <i>-- This UPDATE is not supported, as it does not supply a new value</i>
1073 <i>-- for column "c".</i>
1074 UPDATE f1 SET a=?, b=? WHERE rowid=?;
1075 </pre></div>
1076
1077 <p> Unless backwards compatibility is required, new code should prefer
1078 contentless-delete tables to contentless tables.
1079
1080 </p><a name="external_content_tables"></a>
1081 <h3 tags="FTS5 external content tables" id="external_content_tables"><span>4.4.3. </span>External Content Tables</h3>
1082
1083 <p> An external content FTS5 table is created by setting the content
1084 option to the name of a table, virtual table or view (hereafter the "content
1085 table") within the same database. Whenever column values are required by
1086 FTS5, it queries the content table as follows, with the rowid of the row
1087 for which values are required bound to the SQL variable:
1088
1089 </p><div class="codeblock"><pre>SELECT &lt;content_rowid&gt;, &lt;cols&gt; FROM &lt;content&gt; WHERE &lt;content_rowid&gt; = ?;
1090 </pre></div>
1091
1092 <p> In the above, &lt;content&gt; is replaced by the name of the content table.
1093 By default, &lt;content_rowid&gt; is replaced by the literal text "rowid". Or,
1094 if the "content_rowid" option is set within the CREATE VIRTUAL TABLE statement,
1095 by the value of that option. &lt;cols&gt; is replaced by a comma-separated list
1096 of the FTS5 table column names. For example:
1097
1098 </p><div class="codeblock"><pre><i>-- If the database schema is: </i>
1099 CREATE TABLE tbl (a, b, c, d INTEGER PRIMARY KEY);
1100 CREATE VIRTUAL TABLE fts USING fts5(a, c, content=tbl, content_rowid=d);
1101
1102 <i>-- Fts5 may issue queries such as:</i>
1103 SELECT d, a, c FROM tbl WHERE d = ?;
1104 </pre></div>
1105
1106 <p> The content table may also be queried as follows:
1107
1108 </p><div class="codeblock"><pre>SELECT &lt;content_rowid&gt;, &lt;cols&gt; FROM &lt;content&gt; ORDER BY &lt;content_rowid&gt; ASC;
1109 SELECT &lt;content_rowid&gt;, &lt;cols&gt; FROM &lt;content&gt; ORDER BY &lt;content_rowid&gt; DESC;
1110 </pre></div>
1111
1112 <p> It is still the responsibility of the user to ensure that the contents of
1113 an external content FTS5 table are kept up to date with the content table.
1114 One way to do this is with triggers. For example:
1115
1116 </p><div class="codeblock"><pre><i>-- Create a table. And an external content fts5 table to index it.</i>
1117 CREATE TABLE tbl(a INTEGER PRIMARY KEY, b, c);
1118 CREATE VIRTUAL TABLE fts_idx USING fts5(b, c, content='tbl', content_rowid='a');
1119
1120 <i>-- Triggers to keep the FTS index up to date.</i>
1121 CREATE TRIGGER tbl_ai AFTER INSERT ON tbl BEGIN
1122 INSERT INTO fts_idx(rowid, b, c) VALUES (new.a, new.b, new.c);
1123 END;
1124 CREATE TRIGGER tbl_ad AFTER DELETE ON tbl BEGIN
1125 INSERT INTO fts_idx(fts_idx, rowid, b, c) VALUES('delete', old.a, old.b, old.c);
1126 END;
1127 CREATE TRIGGER tbl_au AFTER UPDATE ON tbl BEGIN
1128 INSERT INTO fts_idx(fts_idx, rowid, b, c) VALUES('delete', old.a, old.b, old.c);
1129 INSERT INTO fts_idx(rowid, b, c) VALUES (new.a, new.b, new.c);
1130 END;
1131 </pre></div>
1132
1133 <p> Like contentless tables, external content tables do not support REPLACE
1134 conflict handling. Any operations that specify REPLACE conflict handling are
1135 handled using ABORT.
1136
1137 </p><a name="external_content_table_pitfalls"></a>
1138 <h3 tags="FTS5 external content pitfalls" id="external_content_table_pitfalls"><span>4.4.4. </span>External Content Table Pitfalls</h3>
1139
1140 <p>
1141 It is the responsibility of the user to ensure that an FTS5 external content
1142 table (one with a non-empty content= option) is kept consistent with the
1143 content table itself (the table named by the content= option). If these are
1144 allowed to become inconsistent, then the results of queries against the FTS5
1145 table may become unintuitive and appear inconsistent.
1146
1147 </p><p>
1148 In these situations, the apparently inconsistent results produced by queries
1149 against the FTS5 external content table may be understood as follows:
1150
1151 </p><ul>
1152 <li><p> If the query does not use the full-text index - does not contain a
1153 MATCH operator or equivalent table-valued function syntax - then the
1154 query is effectively passed through to the external content table. In
1155 this case the contents of the FTS index have no effect on the results
1156 of the query.
1157
1158 </p></li><li><p> If the query does use the full text index, then the FTS5 module
1159 queries it for the set of rowid values corresponding to documents that match
1160 the query. For each such rowid, it then runs a query similar to the following
1161 to retrieve any required column values, where '?' is replaced by the rowid
1162 value, and &lt;content&gt; and &lt;content_rowid&gt; by the values specified
1163 for the content= and content_rowid= options:
1164 </p></li></ul>
1165
1166 <div class="codeblock"><pre>SELECT &lt;content_rowid&gt;, &lt;cols&gt; FROM &lt;content&gt; WHERE &lt;content_rowid&gt; = ?;
1167 </pre></div>
1168
1169 <p>
1170 For example, if a database is created using the following script:
1171
1172 </p><div class="codeblock"><pre><i>-- Create and populate a table. </i>
1173 CREATE TABLE tbl(a INTEGER PRIMARY KEY, t TEXT);
1174 INSERT INTO tbl VALUES(1, 'all that glitters');
1175 INSERT INTO tbl VALUES(2, 'is not gold');
1176
1177 <i>-- Create an external content FTS5 table </i>
1178 CREATE VIRTUAL TABLE ft USING fts5(t, content='tbl', content_rowid='a');
1179 </pre></div>
1180
1181 <p>then the content table contains two rows, but the FTS index contains no
1182 entries corresponding to them. In this case the following queries will return
1183 inconsistent results as follows:
1184
1185 </p><div class="codeblock"><pre><i>-- Returns 2 rows. Because the query does not use the FTS index, it is</i>
1186 <i>-- effectively executed against table 'tbl' directly, and so returns</i>
1187 <i>-- both rows.</i>
1188 SELECT * FROM t1;
1189
1190 <i>-- Returns 0 rows. This query does use the FTS index, which currently</i>
1191 <i>-- contains no entries. So it returns 0 rows.</i>
1192 SELECT rowid, t FROM t1('gold')
1193 </pre></div>
1194
1195 <p>
1196 Alternatively, if the database were created and populated as follows:
1197
1198 </p><div class="codeblock"><pre><i>-- Create and populate a table. </i>
1199 CREATE TABLE tbl(a INTEGER PRIMARY KEY, t TEXT);
1200
1201 <i>-- Create an external content FTS5 table </i>
1202 CREATE VIRTUAL TABLE ft USING fts5(t, content='tbl', content_rowid='a');
1203 INSERT INTO ft(rowid, t) VALUES(1, 'all that glitters');
1204 INSERT INTO ft(rowid, t) VALUES(2, 'is not gold');
1205 </pre></div>
1206
1207 <p>then the content table is empty, but the FTS index contains entries for
1208 6 different tokens. In this case the following queries will return
1209 inconsistent results as follows:
1210
1211 </p><div class="codeblock"><pre><i>-- Returns 0 rows. Since it does not use the FTS index, the query is</i>
1212 <i>-- passed directly through to table 'tbl', which contains no data.</i>
1213 SELECT * FROM t1;
1214
1215 <i>-- Returns 1 row. The "rowid" field of the returned row is 2, and</i>
1216 <i>-- the "t" field set to NULL. "t" is set to NULL because when the external</i>
1217 <i>-- content table "tbl" was queried for the data associated with the row</i>
1218 <i>-- with a=2 ("a" is the content_rowid column), none could be found.</i>
1219 SELECT rowid, t FROM t1('gold')
1220 </pre></div>
1221
1222 <p>As described in the previous section, triggers on the content table are
1223 a good way to ensure that an FTS5 external content table is kept consistent.
1224 However, triggers are only fired when rows are inserted, updated or deleted
1225 in the content table. This means that if, for example, a database is created
1226 as follows:
1227
1228 </p><div class="codeblock"><pre><i>-- Create and populate a table. </i>
1229 CREATE TABLE tbl(a INTEGER PRIMARY KEY, t TEXT);
1230 INSERT INTO tbl VALUES(1, 'all that glitters');
1231 INSERT INTO tbl VALUES(2, 'is not gold');
1232
1233 <i>-- Create an external content FTS5 table </i>
1234 CREATE VIRTUAL TABLE ft USING fts5(t, content='tbl', content_rowid='a');
1235
1236 <i>-- Create triggers to keep the FTS5 table up to date</i>
1237 CREATE TRIGGER tbl_ai AFTER INSERT ON tbl BEGIN
1238 INSERT INTO ft(rowid, t) VALUES (new.a, new.t);
1239 END;
1240 &lt;similar triggers for update + delete&gt;
1241 </pre></div>
1242
1243 <p>then the content table and external content FTS5 table are inconsistent, as
1244 creating the triggers does not copy existing rows from the content table
1245 into the FTS index. The triggers are only able to ensure that updates made to
1246 the content table after they are created are reflected in the FTS index.
1247
1248 </p><p>In this, and any other situation where the FTS index and its content table
1249 have become inconsistent, the <a href="#the_rebuild_command">'rebuild'</a>
1250 command may be used to completely discard the contents of the FTS index and
1251 rebuild it based on the current contents of the content table.
1252
1253 </p><a name="the_columnsize_option"></a>
1254 <h2 tags="FTS5 columnsize option" id="the_columnsize_option"><span>4.5. </span>The Columnsize Option</h2>
1255
1256 <p>Normally, FTS5 maintains a special backing table within the database that
1257 stores the size of each column value in tokens inserted into the main FTS5
1258 table in a separate table. This backing table is used by the
1259 <a href="#xColumnSize">xColumnSize</a><a> API function, which is in turn used by
1260 the built-in <a href="fts5.html#the_bm25_function">bm25 ranking function</a> (and is likely to be useful
1261 to other ranking functions as well).
1262
1263 </a></p><p>In order to save space, this backing table may be omitted by setting the
1264 columnsize option to zero. For example:
1265
1266 </p><div class="codeblock"><pre><i>-- A table without the xColumnSize() values stored on disk:</i>
1267 CREATE VIRTUAL TABLE ft USING fts5(a, b, c, columnsize=0);
1268
1269 <i>-- Three equivalent ways of creating a table that does store the</i>
1270 <i>-- xColumnSize() values on disk:</i>
1271 CREATE VIRTUAL TABLE ft USING fts5(a, b, c);
1272 CREATE VIRTUAL TABLE ft USING fts5(a, b, c, columnsize=1);
1273 CREATE VIRTUAL TABLE ft USING fts5(a, b, columnsize='1', c);
1274 </pre></div>
1275
1276 <p> It is an error to set the columnsize option to any value other than
1277 0 or 1.
1278
1279 </p><p> If an FTS5 table is configured with columnsize=0 but is not a
1280 <a href="fts5.html#contentless_tables">contentless table</a>, the xColumnSize API function
1281 still works, but runs much more slowly. In this case, instead of reading
1282 the value to return directly from the database, it reads the text value
1283 itself and count the tokens within it on demand.
1284
1285 </p><p>Or, if the table is also a <a href="fts5.html#contentless_tables">contentless table</a>,
1286 then the following apply:
1287
1288 </p><ul>
1289 <li> <p>The xColumnSize API always returns -1. There is no way to determine
1290 the number of tokens in a value stored within a contentless FTS5 table
1291 configured with columnsize=0.
1292
1293 </p></li><li> <p>Each inserted row must be accompanied by an explicitly specified rowid
1294 value. If a contentless table is configured with columnsize=0,
1295 attempting to insert a NULL value into the rowid is an SQLITE_MISMATCH
1296 error.
1297
1298 </p></li><li> <p>All queries on the table must be full-text queries. In other words,
1299 they must use the MATCH or = operator with the table-name column as the
1300 left-hand operand, or else use the table-valued function syntax. Any
1301 query that is not a full-text query results in an error.
1302 </p></li></ul>
1303
1304 <p> The name of the table in which the xColumnSize values are stored
1305 (unless columnsize=0 is specified) is "&lt;name&gt;_docsize", where
1306 &lt;name&gt; is the name of the FTS5 table itself. The
1307 <a href="https://www.sqlite.org/download.html">sqlite3_analyzer</a>
1308 tool may be used on an existing database in order to determine how much
1309 space might be saved by recreating an FTS5 table using columnsize=0.
1310
1311 </p><a name="the_detail_option"></a>
1312 <h2 tags="FTS5 detail option" id="the_detail_option"><span>4.6. </span>The Detail Option</h2>
1313
1314 <p> For each term in a document, the FTS index maintained by FTS5
1315 stores the rowid of the document, the column number of the column that contains
1316 the term and the offset of the term within the column value. The "detail"
1317 option may be used to omit some of this information. This reduces the space
1318 that the index consumes within the database file, but also reduces the
1319 capability and efficiency of the system.
1320
1321 </p><p> The detail option may be set to "full" (the default value), "column" or
1322 "none". For example:
1323
1324 </p><div class="codeblock"><pre><i>-- The following two lines are equivalent (because the default value</i>
1325 <i>-- of "detail" is "full". </i>
1326 CREATE VIRTUAL TABLE ft1 USING fts5(a, b, c);
1327 CREATE VIRTUAL TABLE ft1 USING fts5(a, b, c, detail=full);
1328
1329 CREATE VIRTUAL TABLE ft2 USING fts5(a, b, c, detail=column);
1330 CREATE VIRTUAL TABLE ft3 USING fts5(a, b, c, detail=none);
1331 </pre></div>
1332
1333 <p>If the detail option is set to <b>column</b>, then for each term the FTS
1334 index records the rowid and column number only, omitting the term offset
1335 information. This results in the following restrictions:
1336
1337 </p><ul>
1338 <li> NEAR queries are not available.
1339 </li><li> Phrase queries are not available.
1340 </li><li> Assuming the table is not also a
1341 <a href="fts5.html#contentless_tables">contentless table</a>, the
1342 <a href="#xInstCount">xInstCount</a>, <a href="#xInst">xInst</a>,
1343 <a href="#xPhraseFirst">xPhraseFirst</a> and <a href="#xPhraseNext">xPhraseNext</a>
1344 are slower than usual. This is because instead of reading the required data
1345 directly from the FTS index they have to load and tokenize the document text
1346 on demand.
1347 </li><li> If the table is also a contentless table, the xInstCount, xInst,
1348 xPhraseFirst and xPhraseNext APIs behave as if the current row contains no
1349 phrase matches at all (i.e. xInstCount() returns 0).
1350 </li></ul>
1351
1352 <p>If the detail option is set to <b>none</b>, then for each term the FTS
1353 index records just the rowid is stored. Both column and offset information
1354 are omitted. As well as the restrictions itemized above for detail=column
1355 mode, this imposes the following extra limitations:
1356
1357 </p><ul>
1358 <li> Column filter queries are not available.
1359 </li><li> Assuming the table is not also a contentless table, the
1360 <a href="#xPhraseFirstColumn">xPhraseFirstColumn</a> and
1361 <a href="#xPhraseNextColumn">xPhraseNextColumn</a> are slower than usual.
1362
1363 </li><li> If the table is also a contentless table, the xPhraseFirstColumn and
1364 xPhraseNextColumn APIs behave as if the current row contains no phrase
1365 matches at all (i.e. xPhraseFirstColumn() sets the iterator to EOF).
1366 </li></ul>
1367
1368 <p> In one test that indexed a large set of emails (1636 MiB on disk), the FTS
1369 index was 743 MiB on disk with detail=full, 340 MiB with detail=column and 134
1370 MiB with detail=none.
1371
1372 </p><a name="the_tokendata_option"></a>
1373 <h2 tags="FTS5 tokendata option" id="the_tokendata_option"><span>4.7. </span>The Tokendata Option</h2>
1374
1375 <p>This option is only useful to applications that implement
1376 <a href="#custom_tokenizers">custom tokenizers</a>. Usually, tokenizers may
1377 return tokens that consist of any sequence of bytes, including 0x00 bytes.
1378 However, if the table specifies the tokendata=1 option, then fts5 ignores
1379 the first 0x00 byte and any trailing data in the token for the purposes
1380 of matching. It still stores the entire token as returned by the tokenizer,
1381 but it is ignored by the fts5 core.
1382
1383 </p><p>The full version of the token, including any 0x00 byte and trailing data,
1384 is available to <a href="#custom_auxiliary_functions">custom auxiliary
1385 functions</a> via the <a href="#xQueryToken">xQueryToken</a> and
1386 <a href="#xInstToken">xInstToken</a> APIs.
1387
1388 </p><p>This may be useful for ranking functions. A custom tokenizer may
1389 add extra data to some document tokens allowing a ranking function to give
1390 more weight to hits of some tokens (e.g. those in document headings).
1391
1392 </p><p>Alternatively, the combination of a custom tokenizer and a custom auxiliary
1393 function may be used to implement
1394 <a href="https://www.unicode.org/reports/tr10/tr10-41.html#Asymmetric_Search">
1395 asymmetric search</a>. The tokenizer could (say) for each document token return
1396 the case-normalized and unmarked version of the token, followed by an 0x00
1397 byte, followed by the full text of the token from the document. When queried,
1398 fts5 would provide results as if all characters in the query were
1399 case-normalized and unmarked. The custom auxiliary function could then be used
1400 in the WHERE clause of the query to filter out any rows that do not match based
1401 on secondary or tertiary markings in the document or query terms.
1402
1403 </p><a name="_auxiliary_functions_"></a>
1404 <h1 tags="FTS5 auxiliary functions" id="_auxiliary_functions_"><span>5. </span> Auxiliary Functions </h1>
1405
1406 <p> Auxiliary functions are similar to <a href="lang_corefunc.html">SQL scalar functions</a>,
1407 except that they may only be used within full-text queries (those that use
1408 the MATCH operator, or LIKE/GLOB with the trigram tokenizer) on an FTS5 table.
1409 Their results are calculated based not only on the arguments passed to them,
1410 but also on the current match and matched row. For example, an auxiliary
1411 function may return a numeric value indicating the accuracy of the match (see
1412 the <a href="fts5.html#the_bm25_function">bm25()</a> function), or a fragment of text from the matched row
1413 that contains one or more instances of the search terms (see the <a href="fts5.html#the_snippet_function">snippet()</a> function).
1414
1415 </p><p>To invoke an auxiliary function, the name of the FTS5 table should be
1416 specified as the first argument. Other arguments may follow the first,
1417 depending on the specific auxiliary function being invoked. For example, to
1418 invoke the "highlight" function:
1419
1420 </p><div class="codeblock"><pre>SELECT highlight(email, 2, '&lt;b&gt;', '&lt;/b&gt;') FROM email WHERE email MATCH 'fts5'
1421 </pre></div>
1422
1423 <p>The built-in auxiliary functions provided as part of FTS5 are described in
1424 the following section. Applications may also implement
1425 <a href="fts5.html#custom_auxiliary_functions">custom auxiliary functions in C</a>.
1426
1427 </p><h2 id="built_in_auxiliary_functions"><span>5.1. </span>Built-in Auxiliary Functions</h2>
1428
1429 <p> FTS5 provides three built-in auxiliary functions:
1430
1431 </p><ul>
1432 <li> The <a href="fts5.html#the_bm25_function">bm25() auxiliary function</a> returns a real value
1433 reflecting the accuracy of the current match. Better matches are
1434 assigned numerically lower values.
1435
1436 </li><li> The <a href="fts5.html#the_highlight_function">highlight() auxiliary function</a> returns a copy
1437 of the text from one of the columns of the current match with each
1438 instance of a queried term within the result surrounded by specified
1439 markup (for example "&lt;b&gt;" and "&lt;/b&gt;").
1440
1441 </li><li> The <a href="fts5.html#the_snippet_function">snippet() auxiliary function</a> selects a short
1442 fragment of text from one of the columns of the matched row and returns
1443 it with each instance of a queried term surrounded by markup in
1444 the same manner as the highlight() function. The fragment of text is
1445 selected so as to maximize the number of distinct queried terms it
1446 contains. Higher weight is given to snippets that occur at the start
1447 of a column value, or that immediately follow "." or ":" characters
1448 in the text.
1449 </li></ul>
1450
1451 <a name="the_bm25_function"></a>
1452 <h3 tags="FTS5 bm25" id="the_bm25_function"><span>5.1.1. </span>The bm25() function</h3>
1453
1454 <p> The built-in auxiliary function bm25() returns a real value indicating
1455 how well the current row matches the full-text query. The better the match,
1456 the numerically smaller the value returned. A query such as the following may
1457 be used to return matches in order from best to worst match:
1458
1459 </p><div class="codeblock"><pre>SELECT * FROM fts WHERE fts MATCH ? ORDER BY bm25(fts)
1460 </pre></div>
1461
1462 <p> In order to calculate a documents score, the full-text query is separated
1463 into its component phrases. The bm25 score for document <i>D</i> and
1464 query <i>Q</i> is then calculated as follows:
1465
1466 </p><p> <img src="images/fts5_formula1.png" style="width:75ex;margin-left:5ex">
1467
1468 </p><p> In the above, <i>nPhrase</i> is the number of phrases in the query.
1469 <i>|D|</i> is the number of tokens in the current document, and
1470 <i>avgdl</i> is the average number of tokens in all documents within the
1471 FTS5 table. <i>k<sub>1</sub></i> and <i>b</i> are both constants,
1472 hard-coded at 1.2 and 0.75 respectively.
1473
1474 </p><p> The "-1" term at the start of the formula is not found in most
1475 implementations of the BM25 algorithm. Without it, a better match is assigned
1476 a numerically higher BM25 score. Since the default sorting order is
1477 "ascending", this means that appending "ORDER BY bm25(fts)" to a query would
1478 cause results to be returned in order from worst to best. The "DESC" keyword
1479 would be required in order to return the best matches first. In order to
1480 avoid this pitfall, the FTS5 implementation of BM25 multiplies the result
1481 by -1 before returning it, ensuring that better matches are assigned
1482 numerically lower scores.
1483
1484 </p><p> <i>IDF(q<sub>i</sub>)</i> is the inverse-document-frequency of query
1485 phrase <i>i</i>. It is calculated as follows, where <i>N</i> is the total
1486 number of rows in the FTS5 table and <i>n(q<sub>i</sub>)</i> is the total
1487 number of rows that contain at least one instance of phrase <i>i</i>:
1488
1489 </p><p> <img src="images/fts5_formula2.png" style="width:75ex;margin-left:5ex">
1490
1491 </p><p> Finally, <i>f(q<sub>i</sub>,D)</i> is the phrase frequency of phrase
1492 <i>i</i>. By default, this is simply the number of occurrences of the phrase
1493 within the current row. However, by passing extra real value arguments to
1494 the bm25() SQL function, each column of the table may be assigned a different
1495 weight and the phrase frequency calculated as follows:
1496
1497 </p><p> <img src="images/fts5_formula3.png" style="width:75ex;margin-left:5ex">
1498
1499 </p><p> where <i>w<sub>c</sub></i> is the weight assigned to column <i>c</i> and
1500 <i>n(q<sub>i</sub>,c)</i> is the number of occurrences of phrase <i>i</i> in
1501 column <i>c</i> of the current row. The first argument passed to bm25()
1502 following the table name is the weight assigned to the leftmost column of
1503 the FTS5 table. The second is the weight assigned to the second leftmost
1504 column, and so on. If there are not enough arguments for all table columns,
1505 remaining columns are assigned a weight of 1.0. If there are too many
1506 trailing arguments, the extras are ignored. For example:
1507
1508 </p><div class="codeblock"><pre><i>-- Assuming the following schema:</i>
1509 CREATE VIRTUAL TABLE email USING fts5(sender, title, body);
1510
1511 <i>-- Return results in bm25 order, with each phrase hit in the "sender"</i>
1512 <i>-- column considered the equal of 10 hits in the "body" column, and</i>
1513 <i>-- each hit in the "title" column considered as valuable as 5 hits in</i>
1514 <i>-- the "body" column.</i>
1515 SELECT * FROM email WHERE email MATCH ? ORDER BY bm25(email, 10.0, 5.0);
1516 </pre></div>
1517
1518 <p>Refer to wikipedia for
1519 <a href="https://en.wikipedia.org/wiki/Okapi_BM25">more information regarding
1520 BM25</a> and its variants.
1521
1522 </p><a name="the_highlight_function"></a>
1523 <h3 tags="FTS5 highlight" id="the_highlight_function"><span>5.1.2. </span>The highlight() function</h3>
1524
1525 <p> The highlight() function returns a copy of the text from a specified
1526 column of the current row with extra markup text inserted to mark the start
1527 and end of phrase matches.
1528
1529 </p><p>The highlight() must be invoked with exactly three arguments following
1530 the table name. To be interpreted as follows:
1531
1532 </p><ol>
1533 <li> An integer indicating the index of the FTS table column to read the
1534 text from. Columns are numbered from left to right starting at zero.
1535
1536 </li><li> The text to insert before each phrase match.
1537
1538 </li><li> The text to insert after each phrase match.
1539 </li></ol>
1540
1541 <p>For example:
1542
1543 </p><div class="codeblock"><pre><i>-- Return a copy of the text from the leftmost column of the current</i>
1544 <i>-- row, with phrase matches marked using html "b" tags.</i>
1545 SELECT highlight(fts, 0, '&lt;b&gt;', '&lt;/b&gt;') FROM fts WHERE fts MATCH ?
1546 </pre></div>
1547
1548 <p>In cases where two or more phrase instances overlap (share one or more
1549 tokens in common), a single open and close marker is inserted for each set
1550 of overlapping phrases. For example:
1551
1552 </p><div class="codeblock"><pre><i>-- Assuming this:</i>
1553 CREATE VIRTUAL TABLE ft USING fts5(a);
1554 INSERT INTO ft VALUES('a b c x c d e');
1555 INSERT INTO ft VALUES('a b c c d e');
1556 INSERT INTO ft VALUES('a b c d e');
1557
1558 <i>-- The following SELECT statement returns these three rows:</i>
1559 <i>-- '&#91;a b c&#93; x &#91;c d e&#93;'</i>
1560 <i>-- '&#91;a b c&#93; &#91;c d e&#93;'</i>
1561 <i>-- '&#91;a b c d e&#93;'</i>
1562 SELECT highlight(ft, 0, '&#91;', '&#93;') FROM ft WHERE ft MATCH 'a+b+c AND c+d+e';
1563 </pre></div>
1564
1565 <a name="the_snippet_function"></a>
1566 <h3 tags="FTS5 snippet" id="the_snippet_function"><span>5.1.3. </span>The snippet() function</h3>
1567
1568 <p>The snippet() function is similar to highlight(), except that instead of
1569 returning entire column values, it automatically selects and extracts a
1570 short fragment of document text to process and return. The snippet() function
1571 must be passed five parameters following the table name argument:
1572
1573 </p><ol>
1574 <li> An integer indicating the index of the FTS table column to select
1575 the returned text from. Columns are numbered from left to right
1576 starting at zero. A negative value indicates that the column should
1577 be automatically selected.
1578
1579 </li><li> The text to insert before each phrase match within the returned text.
1580
1581 </li><li> The text to insert after each phrase match within the returned text.
1582
1583 </li><li> The text to add to the start or end of the selected text to indicate
1584 that the returned text does not occur at the start or end of its column,
1585 respectively.
1586
1587 </li><li> The maximum number of tokens in the returned text. This must be greater
1588 than zero and equal to or less than 64.
1589 </li></ol>
1590
1591 <a name="sorting_by_auxiliary_function_results"></a>
1592 <h2 tags="auxiliary function mapping" id="sorting_by_auxiliary_function_results"><span>5.2. </span>Sorting by Auxiliary Function Results</h2>
1593
1594 <p> All FTS5 tables feature a special hidden column named "rank". If the
1595 current query is not a full-text query (i.e. if it does not include a MATCH
1596 operator), the value of the "rank" column is always NULL. Otherwise, in a
1597 full-text query, column rank contains by default the same value as would be
1598 returned by executing the bm25() auxiliary function with no trailing
1599 arguments.
1600
1601 </p><p> The difference between reading from the rank column and using the bm25()
1602 function directly within the query is only significant when sorting by the
1603 returned value. In this case, using "rank" is faster than using bm25().
1604
1605 </p><div class="codeblock"><pre><i>-- The following queries are logically equivalent. But the second may</i>
1606 <i>-- be faster, particularly if the caller abandons the query before</i>
1607 <i>-- all rows have been returned (or if the queries were modified to </i>
1608 <i>-- include LIMIT clauses).</i>
1609 SELECT * FROM fts WHERE fts MATCH ? ORDER BY bm25(fts);
1610 SELECT * FROM fts WHERE fts MATCH ? ORDER BY rank;
1611 </pre></div>
1612
1613 <p> Instead of using bm25() with no trailing arguments, the specific auxiliary
1614 function mapped to the rank column may be configured either on a per-query
1615 basis, or by setting a different persistent default for the FTS table.
1616
1617 </p><p> In order to change the mapping of the rank column for a single query,
1618 a term similar to either of the following is added to the WHERE clause of a
1619 query:
1620
1621 </p><div class="codeblock"><pre>rank MATCH 'auxiliary-function-name(arg1, arg2, ...)'
1622 rank = 'auxiliary-function-name(arg1, arg2, ...)'
1623 </pre></div>
1624
1625 <p> The right-hand-side of the MATCH or = operator must be a constant
1626 expression that evaluates to a string consisting of the auxiliary function to
1627 invoke, followed by zero or more comma separated arguments within parenthesis.
1628 Arguments must be SQL literals. For example:
1629
1630 </p><div class="codeblock"><pre><i>-- The following queries are logically equivalent. But the second may</i>
1631 <i>-- be faster. See above. </i>
1632 SELECT * FROM fts WHERE fts MATCH ? ORDER BY bm25(fts, 10.0, 5.0);
1633 SELECT * FROM fts WHERE fts MATCH ? AND rank MATCH 'bm25(10.0, 5.0)' ORDER BY rank;
1634 </pre></div>
1635
1636 <p> The table-valued function syntax may also be used to specify an alternative
1637 ranking function. In this case the text describing the ranking function should
1638 be specified as the second table-valued function argument. The following three
1639 queries are equivalent:
1640
1641 </p><div class="codeblock"><pre>SELECT * FROM fts WHERE fts MATCH ? AND rank MATCH 'bm25(10.0, 5.0)' ORDER BY rank;
1642 SELECT * FROM fts WHERE fts = ? AND rank = 'bm25(10.0, 5.0)' ORDER BY rank;
1643 SELECT * FROM fts WHERE fts(?, 'bm25(10.0, 5.0)') ORDER BY rank;
1644 </pre></div>
1645
1646 <p> The default mapping of the rank column for a table may be modified
1647 using the <a href="fts5.html#the_rank_configuration_option">FTS5 rank configuration option</a>.
1648
1649 </p><h1 id="special_insert_commands"><span>6. </span>Special INSERT Commands</h1>
1650
1651 <a name="the_automerge_configuration_option"></a>
1652 <h2 tags="FTS5 automerge option" id="the_automerge_configuration_option"><span>6.1. </span>The 'automerge' Configuration Option</h2>
1653
1654 <p>
1655 Instead of using a single data structure on disk to store the full-text
1656 index, FTS5 uses a series of b-trees. Each time a new transaction is
1657 committed, a new b-tree containing the contents of the committed transaction
1658 is written into the database file. When the full-text index is queried, each
1659 b-tree must be queried individually and the results merged before being
1660 returned to the user.
1661
1662 </p><p>
1663 In order to prevent the number of b-trees in the database from becoming too
1664 large (slowing down queries), smaller b-trees are periodically merged into
1665 single larger b-trees containing the same data. By default, this happens
1666 automatically within INSERT, UPDATE or DELETE statements that modify the
1667 full-text index. The 'automerge' parameter determines how many smaller
1668 b-trees are merged together at a time. Setting it to a small value can
1669 speed up queries (as they have to query and merge the results from fewer
1670 b-trees), but can also slow down writing to the database (as each INSERT,
1671 UPDATE or DELETE statement has to do more work as part of the automatic
1672 merging process).
1673
1674 </p><p>
1675 Each of the b-trees that make up the full-text index is assigned to a "level"
1676 based on its size. Level-0 b-trees are the smallest, as they contain the
1677 contents of a single transaction. Higher level b-trees are the result of
1678 merging two or more level-0 b-trees together and so they are larger. FTS5
1679 begins to merge b-trees together once there exist <i>M</i> or more b-trees
1680 with the same level, where <i>M</i> is the value of the 'automerge'
1681 parameter.
1682
1683 </p><p>
1684 The maximum allowed value for the 'automerge' parameter is 16. The default
1685 value is 4. Setting the 'automerge' parameter to 0 disables the automatic
1686 incremental merging of b-trees altogether.
1687
1688 </p><div class="codeblock"><pre>INSERT INTO ft(ft, rank) VALUES('automerge', 8);
1689 </pre></div>
1690
1691 <h2 id="the_crisismerge_configuration_option"><span>6.2. </span>The 'crisismerge' Configuration Option</h2>
1692
1693 <p>The 'crisismerge' option is similar to 'automerge', in that it determines
1694 how and how often the component b-trees that make up the full-text index are
1695 merged together. Once there exist <i>C</i> or more b-trees on a single level
1696 within the full-text index, where <i>C</i> is the value of the 'crisismerge'
1697 option, all b-trees on the level are immediately merged into a single b-tree.
1698
1699 </p><p>The difference between this option and the 'automerge' option is that when
1700 the 'automerge' limit is reached FTS5 only begins to merge the b-trees
1701 together. Most of the work is performed as part of subsequent INSERT,
1702 UPDATE or DELETE operations. Whereas when the 'crisismerge' limit is reached,
1703 the offending b-trees are all merged immediately. This means that an INSERT,
1704 UPDATE or DELETE that triggers a crisis-merge may take a long time to
1705 complete.
1706
1707 </p><p>The default 'crisismerge' value is 16. There is no maximum limit. Attempting
1708 to set the 'crisismerge' parameter to a value of 0 or 1 is equivalent to
1709 setting it to the default value (16). It is an error to attempt to set the
1710 'crisismerge' option to a negative value.
1711
1712 </p><div class="codeblock"><pre>INSERT INTO ft(ft, rank) VALUES('crisismerge', 16);
1713 </pre></div>
1714
1715 <a name="the_delete_command"></a>
1716 <h2 tags="FTS5 delete command" id="the_delete_command"><span>6.3. </span>The 'delete' Command</h2>
1717
1718 <p> This command is only available with <a href="fts5.html#external_content_tables">external content</a> and <a href="fts5.html#contentless_tables">contentless</a> tables. It
1719 is used to delete the index entries associated with a single row from the
1720 full-text index. This command and the <a href="fts5.html#the_delete_all_command">delete-all</a>
1721 command are the only ways to remove entries from the full-text index of a
1722 contentless table.
1723
1724 </p><p> In order to use this command to delete a row, the text value 'delete'
1725 must be inserted into the special column with the same name as the table.
1726 The rowid of the row to delete is inserted into the rowid column. The
1727 values inserted into the other columns must match the values currently
1728 stored in the table. For example:
1729
1730 </p><div class="codeblock"><pre><i>-- Insert a row with rowid=14 into the fts5 table.</i>
1731 INSERT INTO ft(rowid, a, b, c) VALUES(14, $a, $b, $c);
1732
1733 <i>-- Remove the same row from the fts5 table.</i>
1734 INSERT INTO ft(ft, rowid, a, b, c) VALUES('delete', 14, $a, $b, $c);
1735 </pre></div>
1736
1737 <p> If the values "inserted" into the text columns as part of a 'delete'
1738 command are not the same as those currently stored within the table, the
1739 results may be unpredictable.
1740
1741 </p><p> The reason for this is easy to understand: When a document is inserted
1742 into the FTS5 table, an entry is added to the full-text index to record the
1743 position of each token within the new document. When a document is removed,
1744 the original data is required in order to determine the set of entries that
1745 need to be removed from the full-text index. So if the data supplied to FTS5
1746 when a row is deleted using this command is different from that used to
1747 determine the set of token instances when it was inserted, some full-text
1748 index entries may not be correctly deleted, or FTS5 may try to remove index
1749 entries that do not exist. This can leave the full-text index in an
1750 unpredictable state, making future query results unreliable.
1751
1752 </p><a name="the_delete_all_command"></a>
1753 <h2 tags="FTS5 delete-all command" id="the_delete_all_command"><span>6.4. </span>The 'delete-all' Command</h2>
1754
1755 <p> This command is only available with <a href="fts5.html#external_content_tables">external content</a> and <a href="fts5.html#contentless_tables">contentless</a> tables (including
1756 <a href="fts5.html#contentless_delete_tables">contentless-delete</a> tables. It deletes all
1757 entries from the full-text index.
1758
1759 </p><div class="codeblock"><pre>INSERT INTO ft(ft) VALUES('delete-all');
1760 </pre></div>
1761
1762 <a name="the_deletemerge_configuration_option"></a>
1763 <h2 tags="deletemerge" id="the_deletemerge_configuration_option"><span>6.5. </span>The 'deletemerge' Configuration Option</h2>
1764
1765 <p> The 'deletemerge' option is only used by
1766 <a href="fts5.html#contentless_delete_tables">contentless-delete</a> tables.
1767
1768 </p><p> When a row is deleted from a contentless-delete table, the entries
1769 associated with its tokens are not immediately removed from the FTS index.
1770 Instead, a "tombstone" marker containing the rowid of the deleted row is
1771 attached to the b-tree that contains the row's FTS index entries. When the
1772 b-tree is queried, any query result rows for which there exist tombstone
1773 markers are omitted from the results. When the b-tree is merged with other
1774 b-trees, both the deleted rows and their tombstone markers are discarded.
1775
1776 </p><p> This option specifies a minimum percentage of rows in a b-tree that must
1777 have tombstone markers before the b-tree is made eligible for merging -
1778 either by <a href="#the_automerge_configuration_option">automatic</a> merges or
1779 explicit user <a href="the_merge_command">'merge'</a> commands - even if it
1780 does not meet the usual criteria as determined by the 'automerge' and
1781 <a href="#the_usermerge_configuration_option">'usermerge'</a> options.
1782
1783 </p><p> For example, to specify that FTS5 should consider merging a component
1784 b-tree after 15% of its rows have associated tombstone markers:
1785
1786 </p><div class="codeblock"><pre>INSERT INTO ft(ft, rank) VALUES('deletemerge', 15);
1787 </pre></div>
1788
1789 <p> The default value of this option is 10. Attempting to set it to less than
1790 zero restores the default value. Setting this option to 0 or to greater than
1791 100 ensures that b-trees are never made eligible for merging due to tombstone
1792 markers.
1793
1794 </p><h2 id="the_integrity_check_command"><span>6.6. </span>The 'integrity-check' Command</h2>
1795
1796 <p> This command is used to verify that the full-text index is internally
1797 consistent, and, optionally, that it is consistent with any
1798 <a href="fts5.html#external_content_tables">external content</a> table.
1799
1800 </p><p>The integrity-check command is invoked by inserting the text value
1801 'integrity-check' into the special column with the same name as the FTS5
1802 table. If a value is supplied for the "rank" column, it must be either
1803 0 or 1. For example:
1804
1805 </p><div class="codeblock"><pre>INSERT INTO ft(ft) VALUES('integrity-check');
1806 INSERT INTO ft(ft, rank) VALUES('integrity-check', 0);
1807 INSERT INTO ft(ft, rank) VALUES('integrity-check', 1);
1808 </pre></div>
1809
1810 <p>The three forms above are equivalent for all FTS tables that are
1811 not external content tables. They check that the index data structures are
1812 not corrupt, and, if the FTS table is not contentless, that the contents of
1813 the index match the contents of the table itself.
1814
1815 </p><p>For an external content table, the contents of the index are only
1816 compared to the contents of the external content table if the value
1817 specified for the rank column is 1.
1818
1819 </p><p>In all cases, if any discrepancies are found, the command fails
1820 with an <a href="rescode.html#corrupt_vtab">SQLITE_CORRUPT_VTAB</a> error.
1821
1822 </p><a name="the_merge_command"></a>
1823 <h2 tags="FTS5 merge command" id="the_merge_command"><span>6.7. </span>The 'merge' Command</h2>
1824
1825 <div class="codeblock"><pre>INSERT INTO ft(ft, rank) VALUES('merge', 500);
1826 </pre></div>
1827
1828 <p> This command merges b-tree structures together until roughly N pages
1829 of merged data have been written to the database, where N is the absolute
1830 value of the parameter specified as part of the 'merge' command. The size of
1831 each page is as configured by the <a href="fts5.html#the_pgsz_configuration_option">FTS5 pgsz option</a>.
1832
1833 </p><p> If the parameter is a positive value, B-tree structures are only eligible
1834 for merging if one of the following is true:
1835
1836 </p><ul>
1837 <li> There are U or more such b-trees on a
1838 single level (see the documentation for the <a href="fts5.html#the_automerge_configuration_option">FTS5 automerge option</a>
1839 for an explanation of b-tree levels), where U is the value assigned
1840 to the <a href="fts5.html#the_usermerge_configuration_option">FTS5 usermerge option</a> option.
1841 </li><li> A merge has already been started (perhaps by a 'merge' command that
1842 specified a negative parameter).
1843 </li></ul>
1844
1845 <p> It is possible to tell whether or not the 'merge' command found any
1846 b-trees to merge together by checking the value returned by the
1847 <a href="c3ref/total_changes.html">sqlite3_total_changes()</a> API before and after the command is executed. If
1848 the difference between the two values is 2 or greater, then work was performed.
1849 If the difference is less than 2, then the 'merge' command was a no-op. In this
1850 case there is no reason to execute the same 'merge' command again, at least
1851 until after the FTS table is next updated.
1852
1853 </p><p> If the parameter is negative, and there are B-tree structures on more than
1854 one level within the FTS index, all B-tree structures are assigned to the same
1855 level before the merge operation is commenced. Additionally, if the parameter
1856 is negative, the value of the usermerge configuration option is not
1857 respected - as few as two b-trees from the same level may be merged together.
1858
1859 </p><p> The above means that executing the 'merge' command with a negative
1860 parameter until the before and after difference in the return value of
1861 <a href="c3ref/total_changes.html">sqlite3_total_changes()</a> is less than two optimizes the FTS index in the
1862 same way as the <a href="fts5.html#the_optimize_command">FTS5 optimize command</a>. However, if a new b-tree is added
1863 to the FTS index while this process is ongoing, FTS5 will move the new
1864 b-tree to the same level as the existing b-trees and restart the merge. To
1865 avoid this, only the first call to 'merge' should specify a negative parameter.
1866 Each subsequent call to 'merge' should specify a positive value so that the
1867 merge started by the first call is run to completion even if new b-trees are
1868 added to the FTS index.
1869
1870 </p><a name="the_optimize_command"></a>
1871 <h2 tags="FTS5 optimize command" id="the_optimize_command"><span>6.8. </span>The 'optimize' Command</h2>
1872
1873 <p>This command merges all individual b-trees that currently make up the
1874 full-text index into a single large b-tree structure. This ensures that the
1875 full-text index consumes the minimum space within the database and is in the
1876 fastest form to query.
1877
1878 </p><p>Refer to the documentation for the <a href="fts5.html#the_automerge_configuration_option">FTS5 automerge option</a> for more details
1879 regarding the relationship between the full-text index and its component
1880 b-trees.
1881
1882 </p><div class="codeblock"><pre>INSERT INTO ft(ft) VALUES('optimize');
1883 </pre></div>
1884
1885 <p>Because it reorganizes the entire FTS index, the optimize command can
1886 take a long time to run. The <a href="fts5.html#the_merge_command">FTS5 merge command</a> can be used to divide
1887 the work of optimizing the FTS index into multiple steps. To do this:
1888
1889 </p><ul>
1890 <li> Invoke the 'merge' command once with the parameter set to -N, then
1891 </li><li> Invoke the 'merge' command zero or more times with the parameter set to N.
1892 </li></ul>
1893
1894 <p>where N is the number of pages of data to merge within each invocation of
1895 the merge command. The application should stop invoking merge when the
1896 difference in the value returned by the sqlite3_total_changes() function before
1897 and after the merge command drops to below two. The merge commands may be
1898 issued as part of the same or separate transactions, and by the same or
1899 different database clients. Refer to the documentation for the
1900 <a href="fts5.html#the_merge_command">merge command</a> for further details.
1901
1902 </p><a name="the_pgsz_configuration_option"></a>
1903 <h2 tags="FTS5 pgsz option" id="the_pgsz_configuration_option"><span>6.9. </span>The 'pgsz' Configuration Option</h2>
1904
1905 <p> This command is used to set the persistent "pgsz" option.
1906
1907 </p><p> The full-text index maintained by FTS5 is stored as a series of fixed-size
1908 blobs in a database table. It is not strictly necessary for all blobs that make
1909 up a full-text index to be the same size. The pgsz option determines the size
1910 of all blobs created by subsequent index writers. The default value is 1000.
1911
1912 </p><div class="codeblock"><pre>INSERT INTO ft(ft, rank) VALUES('pgsz', 4072);
1913 </pre></div>
1914
1915 <a name="the_rank_configuration_option"></a>
1916 <h2 tags="FTS5 rank configuration option" id="the_rank_configuration_option"><span>6.10. </span>The 'rank' Configuration Option</h2>
1917
1918 <p> This command is used to set the persistent "rank" option.
1919
1920 </p><p> The rank option is used to change the default auxiliary function mapping
1921 for the rank column. The option should be set to a text value in the same
1922 format as described for <a href="fts5.html#sorting_by_auxiliary_function_results">"rank MATCH ?"</a> terms
1923 above. For example:
1924
1925 </p><div class="codeblock"><pre>INSERT INTO ft(ft, rank) VALUES('rank', 'bm25(10.0, 5.0)');
1926 </pre></div>
1927
1928 <a name="the_rebuild_command"></a>
1929 <h2 tags="FTS5 rebuild command" id="the_rebuild_command"><span>6.11. </span>The 'rebuild' Command</h2>
1930
1931 <p> This command first deletes the entire full-text index, then rebuilds it
1932 based on the contents of the table or <a href="fts5.html#external_content_tables">content
1933 table</a>. It is not available with <a href="fts5.html#contentless_tables">contentless
1934 tables</a>.
1935
1936 </p><div class="codeblock"><pre>INSERT INTO ft(ft) VALUES('rebuild');
1937 </pre></div>
1938
1939 <a name="the_secure_delete_configuration_option"></a>
1940 <h2 tags="FTS5 secure-delete command" id="the_secure_delete_configuration_option"><span>6.12. </span>The 'secure-delete' Configuration Option</h2>
1941
1942 <p> This command is used to set the persistent boolean "secure-delete" option.
1943 For example:
1944
1945 </p><div class="codeblock"><pre>INSERT INTO ft(ft, rank) VALUES('secure-delete', 1);
1946 </pre></div>
1947
1948 <p> Normally, when an entry in an fts5 table is updated or deleted, instead
1949 of removing entries from the full-text index, delete-keys are added to the <a href="#the_automerge_configuration_option">new b-tree</a> created by the
1950 transaction. This is efficient, but it means that the old full-text index
1951 entries remain in the database file until they are eventually removed
1952 by merge operations on the full-text index. Anyone with access to the
1953 database can use these entries to trivially reconstruct the contents of
1954 deleted FTS5 table rows. However, if the 'secure-delete' option is set
1955 to 1, then full-text entries are actually removed from the database when
1956 existing FTS5 table rows are updated or deleted. This is slower, but
1957 it prevents old full-text entries from being used to reconstruct deleted
1958 table rows.
1959
1960 </p><p> This option ensures that old full-text entries are not available to
1961 attackers with SQL access to the database. To also ensure that they may
1962 not be recovered by attackers with access to the SQLite database file
1963 itself, the application must also enable the SQLite core secure-delete
1964 option with a command like <a href="pragma.html#pragma_secure_delete">
1965 "PRAGMA secure_delete = 1"</a>.
1966
1967 </p><p> <b>Warning:</b> Once one or more table rows have been updated or
1968 deleted with this option set, the FTS5 table may no longer be read or
1969 written by any version of FTS5 earlier than 3.42.0 (the first version
1970 in which this option was available). Attempting to do so results in
1971 an error, with an error message like "invalid fts5 file format (found 5,
1972 expected 4) - run 'rebuild'". The FTS5 file format may be reverted, so
1973 that it may be read by earlier versions of FTS5, by running the
1974 <a href="#the_rebuild_command">'rebuild' command</a> on the table using
1975 version 3.42.0 or later.
1976
1977 </p><p>The default value of the secure-delete option is 0.
1978
1979 </p><a name="the_usermerge_configuration_option"></a>
1980 <h2 tags="FTS5 usermerge option" id="the_usermerge_configuration_option"><span>6.13. </span>The 'usermerge' Configuration Option</h2>
1981
1982 <p> This command is used to set the persistent "usermerge" option.
1983
1984 </p><p> The usermerge option is similar to the automerge and crisismerge options.
1985 It is the minimum number of b-tree segments that will be merged together by
1986 a 'merge' command with a positive parameter. For example:
1987
1988 </p><div class="codeblock"><pre>INSERT INTO ft(ft, rank) VALUES('usermerge', 4);
1989 </pre></div>
1990
1991 <p> The default value of the usermerge option is 4. The minimum allowed value
1992 is 2, and the maximum 16.
1993
1994 </p><a name="extending_fts5"></a>
1995 <h1 tags="Extending FTS5" id="extending_fts5"><span>7. </span>Extending FTS5</h1>
1996
1997 <p>FTS5 features APIs allowing it to be extended by:
1998
1999 </p><ul>
2000 <li> Adding new auxiliary functions implemented in C, and
2001 </li><li> Adding new tokenizers, also implemented in C.
2002 </li></ul>
2003
2004 <p> The built-in tokenizers and auxiliary functions described in this
2005 document are all implemented using the publicly available API described
2006 below.
2007
2008 </p><p> Before a new auxiliary function or tokenizer implementation may be
2009 registered with FTS5, an application must obtain a pointer to the "fts5_api"
2010 structure. There is one fts5_api structure for each database connection with
2011 which the FTS5 extension is registered. To obtain the pointer, the application
2012 invokes the SQL user-defined function fts5() with a single argument. That
2013 argument must be set to a pointer to a pointer to an fts5_api object
2014 using the <a href="c3ref/bind_blob.html">sqlite3_bind_pointer()</a> interface.
2015 The following example code demonstrates the technique:
2016
2017 </p><div class="codeblock"><pre><i>/*
2018 ** Return a pointer to the fts5_api pointer for database connection db.
2019 ** If an error occurs, return NULL and leave an error in the database
2020 ** handle (accessible using sqlite3_errcode()/errmsg()).
2021 */</i>
2022 fts5_api *fts5_api_from_db(sqlite3 *db){
2023 fts5_api *pRet = 0;
2024 sqlite3_stmt *pStmt = 0;
2025
2026 if( SQLITE_OK==sqlite3_prepare(db, "SELECT fts5(?1)", -1, &pStmt, 0) ){
2027 sqlite3_bind_pointer(pStmt, 1, (void*)&pRet, "fts5_api_ptr", NULL);
2028 sqlite3_step(pStmt);
2029 }
2030 sqlite3_finalize(pStmt);
2031 return pRet;
2032 }
2033 </pre></div>
2034
2035 <p><b>Backwards Compatibility Warning:</b>
2036 Prior to SQLite version 3.20.0 (2017-08-01), the fts5() worked slightly
2037 differently. Older applications that extend FTS5 must be revised to use
2038 the new technique shown above.
2039
2040 </p><p> The fts5_api structure is defined as follows. It exposes three methods,
2041 one each for registering new auxiliary functions and tokenizers, and one for
2042 retrieving existing tokenizer. The latter is intended to facilitate the
2043 implementation of "tokenizer wrappers" similar to the built-in
2044 porter tokenizer.
2045
2046 </p><div class="codeblock"><pre>typedef struct fts5_api fts5_api;
2047 struct fts5_api {
2048 int iVersion; <i>/* Currently always set to 2 */</i>
2049
2050 <i>/* Create a new tokenizer */</i>
2051 int (*xCreateTokenizer)(
2052 fts5_api *pApi,
2053 const char *zName,
2054 void *pUserData,
2055 fts5_tokenizer *pTokenizer,
2056 void (*xDestroy)(void*)
2057 );
2058
2059 <i>/* Find an existing tokenizer */</i>
2060 int (*xFindTokenizer)(
2061 fts5_api *pApi,
2062 const char *zName,
2063 void **ppUserData,
2064 fts5_tokenizer *pTokenizer
2065 );
2066
2067 <i>/* Create a new auxiliary function */</i>
2068 int (*xCreateFunction)(
2069 fts5_api *pApi,
2070 const char *zName,
2071 void *pUserData,
2072 fts5_extension_function xFunction,
2073 void (*xDestroy)(void*)
2074 );
2075 };
2076 </pre></div>
2077
2078 <p> To invoke a method of the fts5_api object, the fts5_api pointer itself
2079 should be passed as the methods first argument followed by the other, method
2080 specific, arguments. For example:
2081
2082 </p><div class="codeblock"><pre>rc = pFts5Api->xCreateTokenizer(pFts5Api, ... other args ...);
2083 </pre></div>
2084
2085 <p> The fts5_api structure methods are described individually in the following
2086 sections.
2087
2088 </p><a name="custom_tokenizers"></a>
2089 <h2 tags="custom tokenizers" id="custom_tokenizers"><span>7.1. </span>Custom Tokenizers</h2>
2090
2091 <p> To create a custom tokenizer, an application must implement three
2092 functions: a tokenizer constructor (xCreate), a destructor (xDelete) and a
2093 function to do the actual tokenization (xTokenize). The type of each
2094 function is as for the member variables of the fts5_tokenizer struct:
2095
2096 </p><div class="codeblock"><pre>typedef struct Fts5Tokenizer Fts5Tokenizer;
2097 typedef struct fts5_tokenizer fts5_tokenizer;
2098 struct fts5_tokenizer {
2099 int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
2100 void (*xDelete)(Fts5Tokenizer*);
2101 int (*xTokenize)(Fts5Tokenizer*,
2102 void *pCtx,
2103 int flags, <i>/* Mask of FTS5_TOKENIZE_* flags */</i>
2104 const char *pText, int nText,
2105 int (*xToken)(
2106 void *pCtx, <i>/* Copy of 2nd argument to xTokenize() */</i>
2107 int tflags, <i>/* Mask of FTS5_TOKEN_* flags */</i>
2108 const char *pToken, <i>/* Pointer to buffer containing token */</i>
2109 int nToken, <i>/* Size of token in bytes */</i>
2110 int iStart, <i>/* Byte offset of token within input text */</i>
2111 int iEnd <i>/* Byte offset of end of token within input text */</i>
2112 )
2113 );
2114 };
2115
2116 <i>/* Flags that may be passed as the third argument to xTokenize() */</i>
2117 #define FTS5_TOKENIZE_QUERY 0x0001
2118 #define FTS5_TOKENIZE_PREFIX 0x0002
2119 #define FTS5_TOKENIZE_DOCUMENT 0x0004
2120 #define FTS5_TOKENIZE_AUX 0x0008
2121
2122 <i>/* Flags that may be passed by the tokenizer implementation back to FTS5
2123 ** as the third argument to the supplied xToken callback. */</i>
2124 #define FTS5_TOKEN_COLOCATED 0x0001 <i>/* Same position as prev. token */</i>
2125 </pre></div>
2126
2127 <p> The implementation is registered with the FTS5 module by calling the
2128 xCreateTokenizer() method of the fts5_api object. If there is already a
2129 tokenizer with the same name, it is replaced. If a non-NULL xDestroy parameter
2130 is passed to xCreateTokenizer(), it is invoked with a copy of the pUserData
2131 pointer passed as the only argument when the database handle is closed or when
2132 the tokenizer is replaced.
2133
2134 </p><p> If successful, xCreateTokenizer() returns SQLITE_OK. Otherwise, it
2135 returns an SQLite error code. In this case the xDestroy function is <b>not</b>
2136 invoked.
2137
2138 </p><p> When an FTS5 table uses the custom tokenizer, the FTS5 core calls xCreate()
2139 once to create a tokenizer, then xTokenize() zero or more times to tokenize
2140 strings, then xDelete() to free any resources allocated by xCreate(). More
2141 specifically:
2142
2143 </p><dl>
2144 <dt><b>xCreate:</b></dt><dd><p style="margin-top:0">
2145 This function is used to allocate and initialize a tokenizer instance.
2146 A tokenizer instance is required to actually tokenize text.
2147 </p><p>
2148 The first argument passed to this function is a copy of the (void*)
2149 pointer provided by the application when the fts5_tokenizer object
2150 was registered with FTS5 (the third argument to xCreateTokenizer()).
2151 The second and third arguments are an array of nul-terminated strings
2152 containing the tokenizer arguments, if any, specified following the
2153 tokenizer name as part of the CREATE VIRTUAL TABLE statement used
2154 to create the FTS5 table.
2155 </p><p>
2156 The final argument is an output variable. If successful, (*ppOut)
2157 should be set to point to the new tokenizer handle and SQLITE_OK
2158 returned. If an error occurs, some value other than SQLITE_OK should
2159 be returned. In this case, fts5 assumes that the final value of *ppOut
2160 is undefined.
2161 </p><p>
2162 </p></dd><dt><b> xDelete:</b></dt><dd><p style="margin-top:0">
2163 This function is invoked to delete a tokenizer handle previously
2164 allocated using xCreate(). Fts5 guarantees that this function will
2165 be invoked exactly once for each successful call to xCreate().
2166 </p><p>
2167 </p></dd><dt><b> xTokenize:</b></dt><dd><p style="margin-top:0">
2168 This function is expected to tokenize the nText byte string indicated
2169 by argument pText. pText may or may not be nul-terminated. The first
2170 argument passed to this function is a pointer to an Fts5Tokenizer object
2171 returned by an earlier call to xCreate().
2172 </p><p>
2173 The second argument indicates the reason that FTS5 is requesting
2174 tokenization of the supplied text. This is always one of the following
2175 four values:
2176 </p><p>
2177 </p><ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
2178 or removed from the FTS table. The tokenizer is being invoked to
2179 determine the set of tokens to add to (or delete from) the
2180 FTS index.
2181 <p>
2182 </p></li><li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
2183 against the FTS index. The tokenizer is being called to tokenize
2184 a bareword or quoted string specified as part of the query.
2185 <p>
2186 </p></li><li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
2187 FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
2188 followed by a "*" character, indicating that the last token
2189 returned by the tokenizer will be treated as a token prefix.
2190 <p>
2191 </p></li><li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
2192 satisfy an fts5_api.xTokenize() request made by an auxiliary
2193 function. Or an fts5_api.xColumnSize() request made by the same
2194 on a columnsize=0 database.
2195 </li></ul>
2196 <p>
2197 For each token in the input string, the supplied callback xToken() must
2198 be invoked. The first argument to it should be a copy of the pointer
2199 passed as the second argument to xTokenize(). The third and fourth
2200 arguments are a pointer to a buffer containing the token text, and the
2201 size of the token in bytes. The 4th and 5th arguments are the byte offsets
2202 of the first byte of and first byte immediately following the text from
2203 which the token is derived within the input.
2204 </p><p>
2205 The second argument passed to the xToken() callback ("tflags") should
2206 normally be set to 0. The exception is if the tokenizer supports
2207 synonyms. In this case see the discussion below for details.
2208 </p><p>
2209 FTS5 assumes the xToken() callback is invoked for each token in the
2210 order that they occur within the input text.
2211 </p><p>
2212 If an xToken() callback returns any value other than SQLITE_OK, then
2213 the tokenization should be abandoned and the xTokenize() method should
2214 immediately return a copy of the xToken() return value. Or, if the
2215 input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
2216 if an error occurs with the xTokenize() implementation itself, it
2217 may abandon the tokenization and return any error code other than
2218 SQLITE_OK or SQLITE_DONE.
2219 </p><p>
2220 </p></dd></dl><h3 id="synonym_support"><span>7.1.1. </span>Synonym Support</h3>
2221 <p>
2222 Custom tokenizers may also support synonyms. Consider a case in which a
2223 user wishes to query for a phrase such as "first place". Using the
2224 built-in tokenizers, the FTS5 query 'first + place' will match instances
2225 of "first place" within the document set, but not alternative forms
2226 such as "1st place". In some applications, it would be better to match
2227 all instances of "first place" or "1st place" regardless of which form
2228 the user specified in the MATCH query text.
2229 </p><p>
2230 There are several ways to approach this in FTS5:
2231 </p><p>
2232 </p><ol><li> By mapping all synonyms to a single token. In this case, using
2233 the above example, this means that the tokenizer returns the
2234 same token for inputs "first" and "1st". Say that token is in
2235 fact "first", so that when the user inserts the document "I won
2236 1st place" entries are added to the index for tokens "i", "won",
2237 "first" and "place". If the user then queries for '1st + place',
2238 the tokenizer substitutes "first" for "1st" and the query works
2239 as expected.
2240 <p>
2241 </p></li><li> By querying the index for all synonyms of each query term
2242 separately. In this case, when tokenizing query text, the
2243 tokenizer may provide multiple synonyms for a single term
2244 within the document. FTS5 then queries the index for each
2245 synonym individually. For example, faced with the query:
2246 <p>
2247 </p><div class="codeblock"><pre>... MATCH 'first place'
2248 </pre></div>
2249 <p>
2250 the tokenizer offers both "1st" and "first" as synonyms for the
2251 first token in the MATCH query and FTS5 effectively runs a query
2252 similar to:
2253 </p><p>
2254 </p><div class="codeblock"><pre>... MATCH '(first OR 1st) place'
2255 </pre></div>
2256 <p>
2257 except that, for the purposes of auxiliary functions, the query
2258 still appears to contain just two phrases - "(first OR 1st)"
2259 being treated as a single phrase.
2260 </p><p>
2261 </p></li><li> By adding multiple synonyms for a single term to the FTS index.
2262 Using this method, when tokenizing document text, the tokenizer
2263 provides multiple synonyms for each token. So that when a
2264 document such as "I won first place" is tokenized, entries are
2265 added to the FTS index for "i", "won", "first", "1st" and
2266 "place".
2267 <p>
2268 This way, even if the tokenizer does not provide synonyms
2269 when tokenizing query text (it should not - to do so would be
2270 inefficient), it doesn't matter if the user queries for
2271 'first + place' or '1st + place', as there are entries in the
2272 FTS index corresponding to both forms of the first token.
2273 </p></li></ol>
2274 <p>
2275 Whether it is parsing document or query text, any call to xToken that
2276 specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
2277 is considered to supply a synonym for the previous token. For example,
2278 when parsing the document "I won first place", a tokenizer that supports
2279 synonyms would call xToken() 5 times, as follows:
2280 </p><p>
2281 </p><div class="codeblock"><pre>xToken(pCtx, 0, "i", 1, 0, 1);
2282 xToken(pCtx, 0, "won", 3, 2, 5);
2283 xToken(pCtx, 0, "first", 5, 6, 11);
2284 xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
2285 xToken(pCtx, 0, "place", 5, 12, 17);
2286 </pre></div>
2287 <p>
2288 It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
2289 xToken() is called. Multiple synonyms may be specified for a single token
2290 by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
2291 There is no limit to the number of synonyms that may be provided for a
2292 single token.
2293 </p><p>
2294 In many cases, method (1) above is the best approach. It does not add
2295 extra data to the FTS index or require FTS5 to query for multiple terms,
2296 so it is efficient in terms of disk space and query speed. However, it
2297 does not support prefix queries very well. If, as suggested above, the
2298 token "first" is substituted for "1st" by the tokenizer, then the query:
2299 </p><p>
2300 </p><div class="codeblock"><pre>... MATCH '1s*'
2301 </pre></div>
2302 <p>
2303 will not match documents that contain the token "1st" (as the tokenizer
2304 will probably not map "1s" to any prefix of "first").
2305 </p><p>
2306 For full prefix support, method (3) may be preferred. In this case,
2307 because the index contains entries for both "first" and "1st", prefix
2308 queries such as 'fi*' or '1s*' will match correctly. However, because
2309 extra entries are added to the FTS index, this method uses more space
2310 within the database.
2311 </p><p>
2312 Method (2) offers a midpoint between (1) and (3). Using this method,
2313 a query such as '1s*' will match documents that contain the literal
2314 token "1st", but not "first" (assuming the tokenizer is not able to
2315 provide synonyms for prefixes). However, a non-prefix query like '1st'
2316 will match against "1st" and "first". This method does not require
2317 extra disk space, as no extra entries are added to the FTS index.
2318 On the other hand, it may require more CPU cycles to run MATCH queries,
2319 as separate queries of the FTS index are required for each synonym.
2320 </p><p>
2321 When using methods (2) or (3), it is important that the tokenizer only
2322 provide synonyms when tokenizing document text (method (3)) or query
2323 text (method (2)), not both. Doing so will not cause any errors, but is
2324 inefficient.
2325
2326
2327
2328 </p><a name="custom_auxiliary_functions"></a>
2329 <h2 tags="FTS5 custom auxiliary functions" id="custom_auxiliary_functions"><span>7.2. </span>Custom Auxiliary Functions</h2>
2330
2331 <p> Implementing a custom auxiliary function is similar to implementing a
2332 <a href="appfunc.html">scalar SQL function</a>. The implementation
2333 should be a C function of type fts5_extension_function, defined as follows:
2334
2335 </p><div class="codeblock"><pre>typedef struct Fts5ExtensionApi Fts5ExtensionApi;
2336 typedef struct Fts5Context Fts5Context;
2337 typedef struct Fts5PhraseIter Fts5PhraseIter;
2338
2339 typedef void (*fts5_extension_function)(
2340 const Fts5ExtensionApi *pApi, <i>/* API offered by current FTS version */</i>
2341 Fts5Context *pFts, <i>/* First arg to pass to pApi functions */</i>
2342 sqlite3_context *pCtx, <i>/* Context for returning result/error */</i>
2343 int nVal, <i>/* Number of values in apVal[] array */</i>
2344 sqlite3_value **apVal <i>/* Array of trailing arguments */</i>
2345 );
2346 </pre></div>
2347
2348 <p> The implementation is registered with the FTS5 module by calling the
2349 xCreateFunction() method of the fts5_api object. If there is already an
2350 auxiliary function with the same name, it is replaced by the new function.
2351 If a non-NULL xDestroy parameter is passed to xCreateFunction(), it is invoked
2352 with a copy of the pUserData pointer passed as the only argument when the
2353 database handle is closed or when the registered auxiliary function is
2354 replaced.
2355
2356 </p><p> If successful, xCreateFunction() returns SQLITE_OK. Otherwise, it
2357 returns an SQLite error code. In this case the xDestroy function is <b>not</b>
2358 invoked.
2359
2360 </p><p> The final three arguments passed to the auxiliary function callback
2361 (pCtx, nVal and apVal above) are similar to the three arguments passed to the
2362 implementation of a scalar SQL function. The apVal&#91;&#93; array contains all
2363 SQL arguments except the first passed to the auxiliary function. The
2364 implementation should return a result or error via the content handle pCtx.
2365
2366 </p><p> The first argument passed to an auxiliary function callback is a pointer
2367 to a structure (pApi above) containing methods that may be invoked
2368 in order to obtain information regarding the current query or row. The second
2369 argument is an opaque handle (pFts above) that should be passed as the
2370 first argument to any such method invocation. For example, the following
2371 auxiliary function returns the total number of tokens in all columns of the
2372 current row:
2373
2374 </p><div class="codeblock"><pre><i>/*
2375 ** Implementation of an auxiliary function that returns the number
2376 ** of tokens in the current row (including all columns).
2377 */</i>
2378 static void column_size_imp(
2379 const Fts5ExtensionApi *pApi,
2380 Fts5Context *pFts,
2381 sqlite3_context *pCtx,
2382 int nVal,
2383 sqlite3_value **apVal
2384 ){
2385 int rc;
2386 int nToken;
2387 rc = pApi->xColumnSize(pFts, -1, &nToken);
2388 if( rc==SQLITE_OK ){
2389 sqlite3_result_int(pCtx, nToken);
2390 }else{
2391 sqlite3_result_error_code(pCtx, rc);
2392 }
2393 }
2394 </pre></div>
2395
2396 <p>The following section describes the API offered to auxiliary function
2397 implementations in detail. Further examples may be found in the "fts5_aux.c"
2398 file of the source code.
2399
2400 </p><a name="custom_auxiliary_functions_api_overview"></a>
2401 <h3 tags="custom auxiliary overview" id="custom_auxiliary_functions_api_overview"><span>7.2.1. </span>Custom Auxiliary Functions API Overview</h3>
2402
2403 <p>This section provides an overview of the capabilities of the auxiliary
2404 function API. It does not describe every function. Refer to the <a href="#custom_auxiliary_functions_api_reference">reference text</a> below for a
2405 complete description.
2406
2407 </p><p>When invoked, an auxiliary function implementation has access to APIs that
2408 allow it to query FTS5 for various information. Some of these APIs return
2409 information relating to the current row of the FTS5 table being visited,
2410 some relating to the entire set of rows that will be visited by the FTS5
2411 query, and some relating to the FTS5 table. Given an FTS5 table populated as
2412 follows:
2413
2414 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE ft USING fts5(a, b);
2415 INSERT INTO ft(rowid, a, b) VALUES
2416 (1, 'ab cd', 'cd de one'),
2417 (2, 'de fg', 'fg gh'),
2418 (3, 'gh ij', 'ij ab three four');
2419 </pre></div>
2420
2421 <p>and the query:
2422
2423 </p><div class="codeblock"><pre>SELECT my_aux_function(ft) FROM ft('ab')
2424 </pre></div>
2425
2426 <p>then the custom auxiliary function will be invoked for rows 1 and 3 (all
2427 rows that contain the token "ab" and therefore match the query).
2428
2429 </p><p><b>Number of rows/columns in table: xRowCount, xColumnCount
2430
2431 </b></p><p>The system may be queried for the total number of rows in the FTS5 table
2432 using the <a href="#xRowCount">xRowCount</a> API. This provides the total number
2433 of rows in the table, not the number that match the current query.
2434
2435 </p><p>Table columns are numbered from left to right starting from 0. The
2436 "rowid" column does not count - only user declared columns - so in the example
2437 above column "a" is column 0 and column "b" is column 1. From within an
2438 auxiliary function implementation, the <a href="#xColumnCount">xColumnCount</a>
2439 API may be used to determine how many columns the table being queried has. If
2440 the xColumnCount() API is invoked from within the implementation of the
2441 auxiliary function my_aux_function in the example above, it returns 2.
2442
2443 </p><p><b>Data From Current Row: xColumnText, xRowid
2444
2445 </b></p><p>The <a href="#xRowid">xRowid</a> API may be used to find the rowid value
2446 for the current row. The <a href="#xColumnText">xColumnText</a> may be used
2447 to obtain the text stored in a specified column of the current row.
2448
2449 </p><p><b>Token Counts: xColumnSize, xColumnTotalSize
2450
2451 </b></p><p>FTS5 divides documents inserted into an fts table into tokens. These are
2452 usually just words, perhaps folded to either upper or lower case and with any
2453 punctuation removed. For example, the default
2454 <a href="#unicode61_tokenizer">unicode61 tokenizer</a> tokenizes the text "The
2455 tokenizer is case-insensitive" to a list of 5 tokens - "the", "tokenizer", is",
2456 "case" and "insensitive". Exactly how tokens are extracted from text is
2457 determined by the <a href="#tokenizers">tokenizer</a>.
2458
2459 </p><p>The auxiliary functions API provides functions to query for both the number
2460 of tokens in a specified column of the current row (the
2461 <a href="#xColumnSize">xColumnSize</a> API), or for the number of tokens in a
2462 specified column of all rows of the table (the <a href="#xColumnTotalSize">xColumnTotalSize</a> API). For the example at the
2463 top of this section, when visiting row 1, xColumnSize returns 2 for column 0
2464 and 3 for column 1. xColumnTotalSize returns 6 for column 0 and 9 for column 1
2465 regardless of the current row.
2466
2467 </p><p><b>The Current Full-Text Query: xPhraseCount, xPhraseSize, xQueryToken
2468
2469 </b></p><p>An FTS5 query contains one or more <a href="#fts5_phrases">phrases</a>. The
2470 <a href="#xPhraseCount">xPhraseCount</a>, <a href="#xPhraseSize">xPhraseSize</a>
2471 and <a href="#xQueryToken">xQueryToken</a> APIs allow an auxiliary function
2472 implementation to query the system for details of the current query. The
2473 xPhraseCount API returns the number of phrases in the current query. For
2474 example, if an FTS5 table is queried as follows:
2475
2476 </p><div class="codeblock"><pre>SELECT my_aux_function(ft) FROM ft('ab AND "cd ef gh" OR ij + kl')
2477 </pre></div>
2478
2479 <p>and the xPhraseCount() API invoked from within the implementation of the
2480 auxiliary function, it returns 3 (the three phrases being "ab", "ce ef gh" and
2481 "ij kl").
2482
2483 </p><p>Phrases are numbered in order of appearance within a query starting from 0.
2484 The xPhraseSize() API may be used to query for the number of tokens in a
2485 specified phrase of the query. In the example above, phrase 0 contains 1 token,
2486 phrase 1 contains 3 tokens, and phrase 2 contains 2.
2487
2488 </p><p>The xQueryToken API may be used to access the text of a specified token
2489 within a specified phrase of the query. Tokens are numbered within their
2490 phrases from left to right starting from 0. For example, if the xQueryToken
2491 API is used to request token 1 of phrase 2 in the example above, it returns
2492 the text "kl". Token 0 of phrase 0 is "ab".
2493
2494 </p><p><b>Phrase Hits in the Current Row: xPhraseFirst, xPhraseNext
2495
2496 </b></p><p>These two API functions may be used to iterate through the matches for
2497 a specified phrase of the query within the current row. Phrase matches are
2498 identified by the column and token offset within the current row. For
2499 example, say the following example table:
2500
2501 </p><div class="codeblock"><pre>CREATE VIRTUAL TABLE ft2 USING fts5(x, y);
2502 INSERT INTO ft2(rowid, x, y) VALUES
2503 (1, 'xxx one two xxx five xxx six', 'seven four'),
2504 (2, 'five four four xxx six', 'three four five six four five six');
2505 </pre></div>
2506
2507 <p>is queried with:
2508
2509 </p><div class="codeblock"><pre>SELECT my_aux_function(ft2) FROM ft2(
2510 '("one two" OR "three") AND y:four NEAR(five six, 2)'
2511 );
2512 </pre></div>
2513
2514 <p>The query above contains 5 phrases - "one two", "three", "four",
2515 "five" and "six". It matches all rows of the table, so the auxiliary
2516 function is invoked for each row.
2517
2518 </p><p>In row 1, for phrase 0, "one two", there is exactly one match to iterate
2519 through - at column 0 token offset 1. The column number is 0 because the
2520 match appears in the left most column. The token offset is 1 because there
2521 is exactly one token ("xxx") before the phrase match in the column value.
2522 For phrase 1, "three", there are no matches. Phrase 2, "four", has one
2523 match, at column 1, token offset 0. Phrase 3, "five", has one match at
2524 column 0, token offset 4, and phrase 4, "six", has one match at column 0
2525 token offset 6.
2526
2527 </p><p>The set of matches for each phrase in each row of the example is presented
2528 in the table below. Each match is notated as (column-number, token-offset):
2529
2530 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
2531 <tr style="text-align:left"><th>Row</th><th>Phrase 0</th><th>Phrase 1</th><th>Phrase 2</th><th>Phrase 3</th><th>Phrase 4
2532 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td>1</td><td>(0, 1) </td><td></td><td>(1, 1)</td><td>(0, 4)</td><td>(0, 6)
2533 </td></tr><tr style="text-align:left"><td>2</td><td></td><td>(1,0)</td><td>(1, 1), (1,4)</td><td>(1, 2), (1, 5)</td><td>(1, 3), (1, 6)
2534 </td></tr></table>
2535
2536 <p>The second row is slightly more complicated. There were no occurrences of
2537 phrase 0. Phrase 1 ("three") appears once, at column 1 token offset 0. Although
2538 there are instances of phrase 2 ("four") in column 0, none of them are reported
2539 by the API, as phrase 4 has a <a href="#fts5_column_filters">column filter</a> -
2540 "y:". Matches that are filtered out by column filters do not count. Similarly,
2541 although phrases 3 and 4 do occur in column "x" of row 2, they are filtered
2542 out by the <a href="#fts5_near_queries">NEAR filter</a>. Matches that are
2543 filtered out by NEAR filters do not count either.
2544
2545 </p><p><b>Phrase Hits in the Current Row (2): xInstCount, xInst
2546
2547 </b></p><p>The <a href="#xInstCount">xInstCount</a> and <a href="#xInst">xInst</a> APIs
2548 provide access to the same information as the xPhraseFirst and xPhraseNext
2549 described above. The difference is that instead of iterating through the
2550 matches for a single, specified phrase, the xInstCount/xInst APIs collate
2551 all matches into a single flat array, sorted in order of occurrence within
2552 the current row. Elements of this array may then be accessed randomly.
2553
2554 </p><p>Each array element consists of three values:
2555
2556 </p><ul>
2557 <li> A phrase number,
2558 </li><li> A column number, and
2559 </li><li> A token offset
2560 </li></ul>
2561
2562 <p>Using the same example data and query as for xPhraseFirst/xPhraseNext
2563 above, the array accessible via xInstCount/xInst consists of the following
2564 entries for each row:
2565
2566 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
2567 <tr style="text-align:left"><th>Row</th><th>xInstCount/xInst array
2568 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td>1</td><td>(0, 0, 1), (3, 0, 4), (4, 0, 6), (2, 1, 1)
2569 </td></tr><tr style="text-align:left"><td>2</td><td>(1, 1, 0), (2, 1, 1), (3, 1, 2), (4, 1, 3), (2, 1, 4), (3, 1, 5), (4, 1, 6)
2570 </td></tr></table>
2571
2572 <p>Each entry of the array is called a phrase match. Phrase matches are
2573 numbered in order, starting from 0. So, in the example above, in row 2, phrase
2574 match 3 is (4, 1, 3) - phrase 4 of the query matches at column 1, token offset
2575 3.
2576
2577 </p><a name="custom_auxiliary_functions_api_reference"></a>
2578 <h3 tags="custom auxiliary functions" id="custom_auxiliary_functions_api_reference"><span>7.2.2. </span>Custom Auxiliary Functions API Reference</h3>
2579
2580 <div class="codeblock"><pre>struct Fts5ExtensionApi {
2581 int iVersion; <i>/* Currently always set to 3 */</i>
2582
2583 void *(*<a href="#xUserData">xUserData</a>)(Fts5Context*);
2584
2585 int (*<a href="#xColumnCount">xColumnCount</a>)(Fts5Context*);
2586 int (*<a href="#xRowCount">xRowCount</a>)(Fts5Context*, sqlite3_int64 *pnRow);
2587 int (*<a href="#xColumnTotalSize">xColumnTotalSize</a>)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
2588
2589 int (*<a href="#xTokenize">xTokenize</a>)(Fts5Context*,
2590 const char *pText, int nText, <i>/* Text to tokenize */</i>
2591 void *pCtx, <i>/* Context passed to xToken() */</i>
2592 int (*xToken)(void*, int, const char*, int, int, int) <i>/* Callback */</i>
2593 );
2594
2595 int (*<a href="#xPhraseCount">xPhraseCount</a>)(Fts5Context*);
2596 int (*<a href="#xPhraseSize">xPhraseSize</a>)(Fts5Context*, int iPhrase);
2597
2598 int (*<a href="#xInstCount">xInstCount</a>)(Fts5Context*, int *pnInst);
2599 int (*<a href="#xInst">xInst</a>)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
2600
2601 sqlite3_int64 (*<a href="#xRowid">xRowid</a>)(Fts5Context*);
2602 int (*<a href="#xColumnText">xColumnText</a>)(Fts5Context*, int iCol, const char **pz, int *pn);
2603 int (*<a href="#xColumnSize">xColumnSize</a>)(Fts5Context*, int iCol, int *pnToken);
2604
2605 int (*<a href="#xQueryPhrase">xQueryPhrase</a>)(Fts5Context*, int iPhrase, void *pUserData,
2606 int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
2607 );
2608 int (*<a href="#xSetAuxdata">xSetAuxdata</a>)(Fts5Context*, void *pAux, void(*xDelete)(void*));
2609 void *(*<a href="#xGetAuxdata">xGetAuxdata</a>)(Fts5Context*, int bClear);
2610
2611 int (*<a href="#xPhraseFirst">xPhraseFirst</a>)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
2612 void (*<a href="#xPhraseNext">xPhraseNext</a>)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
2613
2614 int (*<a href="#xPhraseFirstColumn">xPhraseFirstColumn</a>)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
2615 void (*<a href="#xPhraseNextColumn">xPhraseNextColumn</a>)(Fts5Context*, Fts5PhraseIter*, int *piCol);
2616
2617 <i>/* Below this point are iVersion>=3 only */</i>
2618 int (*<a href="#xQueryToken">xQueryToken</a>)(Fts5Context*,
2619 int iPhrase, int iToken,
2620 const char **ppToken, int *pnToken
2621 );
2622 int (*<a href="#xInstToken">xInstToken</a>)(Fts5Context*, int iIdx, int iToken, const char**, int*);
2623 };
2624 </pre></div>
2625
2626 <dl>
2627 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xUserData">
2628 <b>void *(*xUserData)(Fts5Context*)</b></dt><dd>
2629 <p style="margin-top:0.1em">
2630 Return a copy of the pUserData pointer passed to the xCreateFunction()
2631 API when the extension function was registered.
2632 </p>
2633 </dd>
2634 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xColumnTotalSize">
2635 <b>int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken)</b></dt><dd>
2636 <p style="margin-top:0.1em">
2637 If parameter iCol is less than zero, set output variable *pnToken
2638 to the total number of tokens in the FTS5 table. Or, if iCol is
2639 non-negative but less than the number of columns in the table, return
2640 the total number of tokens in column iCol, considering all rows in
2641 the FTS5 table.
2642 </p>
2643
2644 <p>
2645 If parameter iCol is greater than or equal to the number of columns
2646 in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
2647 an OOM condition or IO error), an appropriate SQLite error code is
2648 returned.
2649 </p>
2650 </dd>
2651 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xColumnCount">
2652 <b>int (*xColumnCount)(Fts5Context*)</b></dt><dd>
2653 <p style="margin-top:0.1em">
2654 Return the number of columns in the table.
2655 </p>
2656 </dd>
2657 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xColumnSize">
2658 <b>int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken)</b></dt><dd>
2659 <p style="margin-top:0.1em">
2660 If parameter iCol is less than zero, set output variable *pnToken
2661 to the total number of tokens in the current row. Or, if iCol is
2662 non-negative but less than the number of columns in the table, set
2663 *pnToken to the number of tokens in column iCol of the current row.
2664 </p>
2665
2666 <p>
2667 If parameter iCol is greater than or equal to the number of columns
2668 in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
2669 an OOM condition or IO error), an appropriate SQLite error code is
2670 returned.
2671 </p>
2672
2673 <p>
2674 This function may be quite inefficient if used with an FTS5 table
2675 created with the "columnsize=0" option.
2676 </p>
2677 </dd>
2678 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xColumnText">
2679 <b>int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn)</b></dt><dd>
2680 <p style="margin-top:0.1em">
2681 If parameter iCol is less than zero, or greater than or equal to the
2682 number of columns in the table, SQLITE_RANGE is returned.
2683 </p>
2684
2685 <p>
2686 Otherwise, this function attempts to retrieve the text of column iCol of
2687 the current document. If successful, (*pz) is set to point to a buffer
2688 containing the text in utf-8 encoding, (*pn) is set to the size in bytes
2689 (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
2690 if an error occurs, an SQLite error code is returned and the final values
2691 of (*pz) and (*pn) are undefined.
2692 </p>
2693 </dd>
2694 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xPhraseCount">
2695 <b>int (*xPhraseCount)(Fts5Context*)</b></dt><dd>
2696 <p style="margin-top:0.1em">
2697 Returns the number of phrases in the current query expression.
2698 </p>
2699 </dd>
2700 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xPhraseSize">
2701 <b>int (*xPhraseSize)(Fts5Context*, int iPhrase)</b></dt><dd>
2702 <p style="margin-top:0.1em">
2703 If parameter iCol is less than zero, or greater than or equal to the
2704 number of phrases in the current query, as returned by xPhraseCount,
2705 0 is returned. Otherwise, this function returns the number of tokens in
2706 phrase iPhrase of the query. Phrases are numbered starting from zero.
2707 </p>
2708 </dd>
2709 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xInstCount">
2710 <b>int (*xInstCount)(Fts5Context*, int *pnInst)</b></dt><dd>
2711 <p style="margin-top:0.1em">
2712 Set *pnInst to the total number of occurrences of all phrases within
2713 the query within the current row. Return SQLITE_OK if successful, or
2714 an error code (i.e. SQLITE_NOMEM) if an error occurs.
2715 </p>
2716
2717 <p>
2718 This API can be quite slow if used with an FTS5 table created with the
2719 "detail=none" or "detail=column" option. If the FTS5 table is created
2720 with either "detail=none" or "detail=column" and "content=" option
2721 (i.e. if it is a contentless table), then this API always returns 0.
2722 </p>
2723 </dd>
2724 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xInst">
2725 <b>int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff)</b></dt><dd>
2726 <p style="margin-top:0.1em">
2727 Query for the details of phrase match iIdx within the current row.
2728 Phrase matches are numbered starting from zero, so the iIdx argument
2729 should be greater than or equal to zero and smaller than the value
2730 output by xInstCount(). If iIdx is less than zero or greater than
2731 or equal to the value returned by xInstCount(), SQLITE_RANGE is returned.
2732 </p>
2733
2734 <p>
2735 Otherwise, output parameter *piPhrase is set to the phrase number, *piCol
2736 to the column in which it occurs and *piOff the token offset of the
2737 first token of the phrase. SQLITE_OK is returned if successful, or an
2738 error code (i.e. SQLITE_NOMEM) if an error occurs.
2739 </p>
2740
2741 <p>
2742 This API can be quite slow if used with an FTS5 table created with the
2743 "detail=none" or "detail=column" option.
2744 </p>
2745 </dd>
2746 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xRowid">
2747 <b>sqlite3_int64 (*xRowid)(Fts5Context*)</b></dt><dd>
2748 <p style="margin-top:0.1em">
2749 Returns the rowid of the current row.
2750 </p>
2751 </dd>
2752 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xTokenize">
2753 <b>int (*xTokenize)(Fts5Context*,
2754 const char *pText, int nText,
2755 void *pCtx,
2756 int (*xToken)(void*, int, const char*, int, int, int)
2757 )</b></dt><dd>
2758 <p style="margin-top:0.1em">
2759 Tokenize text using the tokenizer belonging to the FTS5 table.
2760 </p>
2761 </dd>
2762 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xQueryPhrase">
2763 <b>int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
2764 int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
2765 )</b></dt><dd>
2766 <p style="margin-top:0.1em">
2767 This API function is used to query the FTS table for phrase iPhrase
2768 of the current query. Specifically, a query equivalent to:
2769 </p>
2770
2771 <div class="codeblock"><pre>... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
2772 </pre></div>
2773
2774 <p>
2775 with $p set to a phrase equivalent to the phrase iPhrase of the
2776 current query is executed. Any column filter that applies to
2777 phrase iPhrase of the current query is included in $p. For each
2778 row visited, the callback function passed as the fourth argument
2779 is invoked. The context and API objects passed to the callback
2780 function may be used to access the properties of each matched row.
2781 Invoking Api.xUserData() returns a copy of the pointer passed as
2782 the third argument to pUserData.
2783 </p>
2784
2785 <p>
2786 If parameter iPhrase is less than zero, or greater than or equal to
2787 the number of phrases in the query, as returned by xPhraseCount(),
2788 this function returns SQLITE_RANGE.
2789 </p>
2790
2791 <p>
2792 If the callback function returns any value other than SQLITE_OK, the
2793 query is abandoned and the xQueryPhrase function returns immediately.
2794 If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
2795 Otherwise, the error code is propagated upwards.
2796 </p>
2797
2798 <p>
2799 If the query runs to completion without incident, SQLITE_OK is returned.
2800 Or, if some error occurs before the query completes or is aborted by
2801 the callback, an SQLite error code is returned.
2802 </p>
2803 </dd>
2804 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xSetAuxdata">
2805 <b>int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*))</b></dt><dd>
2806 <p style="margin-top:0.1em">
2807 Save the pointer passed as the second argument as the extension function's
2808 "auxiliary data". The pointer may then be retrieved by the current or any
2809 future invocation of the same fts5 extension function made as part of
2810 the same MATCH query using the xGetAuxdata() API.
2811 </p>
2812
2813 <p>
2814 Each extension function is allocated a single auxiliary data slot for
2815 each FTS query (MATCH expression). If the extension function is invoked
2816 more than once for a single FTS query, then all invocations share a
2817 single auxiliary data context.
2818 </p>
2819
2820 <p>
2821 If there is already an auxiliary data pointer when this function is
2822 invoked, then it is replaced by the new pointer. If an xDelete callback
2823 was specified along with the original pointer, it is invoked at this
2824 point.
2825 </p>
2826
2827 <p>
2828 The xDelete callback, if one is specified, is also invoked on the
2829 auxiliary data pointer after the FTS5 query has finished.
2830 </p>
2831
2832 <p>
2833 If an error (e.g. an OOM condition) occurs within this function,
2834 the auxiliary data is set to NULL and an error code returned. If the
2835 xDelete parameter was not NULL, it is invoked on the auxiliary data
2836 pointer before returning.
2837 </p>
2838 </dd>
2839 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xGetAuxdata">
2840 <b>void *(*xGetAuxdata)(Fts5Context*, int bClear)</b></dt><dd>
2841 <p style="margin-top:0.1em">
2842 Returns the current auxiliary data pointer for the fts5 extension
2843 function. See the xSetAuxdata() method for details.
2844 </p>
2845
2846 <p>
2847 If the bClear argument is non-zero, then the auxiliary data is cleared
2848 (set to NULL) before this function returns. In this case the xDelete,
2849 if any, is not invoked.
2850 </p>
2851 </dd>
2852 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xRowCount">
2853 <b>int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow)</b></dt><dd>
2854 <p style="margin-top:0.1em">
2855 This function is used to retrieve the total number of rows in the table.
2856 In other words, the same value that would be returned by:
2857 </p>
2858
2859 <div class="codeblock"><pre>SELECT count(*) FROM ftstable;
2860 </pre></div>
2861 </dd>
2862 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xPhraseFirst">
2863 <b>int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*)</b></dt><dd>
2864 <p style="margin-top:0.1em">
2865 This function is used, along with type Fts5PhraseIter and the xPhraseNext
2866 method, to iterate through all instances of a single query phrase within
2867 the current row. This is the same information as is accessible via the
2868 xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
2869 to use, this API may be faster under some circumstances. To iterate
2870 through instances of phrase iPhrase, use the following code:
2871 </p>
2872
2873 <div class="codeblock"><pre>Fts5PhraseIter iter;
2874 int iCol, iOff;
2875 for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
2876 iCol>=0;
2877 pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
2878 ){
2879 // An instance of phrase iPhrase at offset iOff of column iCol
2880 }
2881 </pre></div>
2882
2883 <p>
2884 The Fts5PhraseIter structure is defined above. Applications should not
2885 modify this structure directly - it should only be used as shown above
2886 with the xPhraseFirst() and xPhraseNext() API methods (and by
2887 xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
2888 </p>
2889
2890 <p>
2891 This API can be quite slow if used with an FTS5 table created with the
2892 "detail=none" or "detail=column" option. If the FTS5 table is created
2893 with either "detail=none" or "detail=column" and "content=" option
2894 (i.e. if it is a contentless table), then this API always iterates
2895 through an empty set (all calls to xPhraseFirst() set iCol to -1).
2896 </p>
2897 </dd>
2898 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xPhraseNext">
2899 <b>void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff)</b></dt><dd>
2900 <p style="margin-top:0.1em">
2901 See xPhraseFirst above.
2902 </p>
2903 </dd>
2904 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xPhraseFirstColumn">
2905 <b>int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*)</b></dt><dd>
2906 <p style="margin-top:0.1em">
2907 This function and xPhraseNextColumn() are similar to the xPhraseFirst()
2908 and xPhraseNext() APIs described above. The difference is that instead
2909 of iterating through all instances of a phrase in the current row, these
2910 APIs are used to iterate through the set of columns in the current row
2911 that contain one or more instances of a specified phrase. For example:
2912 </p>
2913
2914 <div class="codeblock"><pre>Fts5PhraseIter iter;
2915 int iCol;
2916 for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
2917 iCol>=0;
2918 pApi->xPhraseNextColumn(pFts, &iter, &iCol)
2919 ){
2920 // Column iCol contains at least one instance of phrase iPhrase
2921 }
2922 </pre></div>
2923
2924 <p>
2925 This API can be quite slow if used with an FTS5 table created with the
2926 "detail=none" option. If the FTS5 table is created with either
2927 "detail=none" "content=" option (i.e. if it is a contentless table),
2928 then this API always iterates through an empty set (all calls to
2929 xPhraseFirstColumn() set iCol to -1).
2930 </p>
2931
2932 <p>
2933 The information accessed using this API and its companion
2934 xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
2935 (or xInst/xInstCount). The chief advantage of this API is that it is
2936 significantly more efficient than those alternatives when used with
2937 "detail=column" tables.
2938 </p>
2939 </dd>
2940 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xPhraseNextColumn">
2941 <b>void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol)</b></dt><dd>
2942 <p style="margin-top:0.1em">
2943 See xPhraseFirstColumn above.
2944 </p>
2945 </dd>
2946 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xQueryToken">
2947 <b>int (*xQueryToken)(Fts5Context*,
2948 int iPhrase, int iToken,
2949 const char **ppToken, int *pnToken
2950 )</b></dt><dd>
2951 <p style="margin-top:0.1em">
2952 This is used to access token iToken of phrase iPhrase of the current
2953 query. Before returning, output parameter *ppToken is set to point
2954 to a buffer containing the requested token, and *pnToken to the
2955 size of this buffer in bytes.
2956 </p>
2957
2958 <p>
2959 If iPhrase or iToken are less than zero, or if iPhrase is greater than
2960 or equal to the number of phrases in the query as reported by
2961 xPhraseCount(), or if iToken is equal to or greater than the number of
2962 tokens in the phrase, SQLITE_RANGE is returned and *ppToken and *pnToken
2963 are both zeroed.
2964 </p>
2965
2966 <p>
2967 The output text is not a copy of the query text that specified the
2968 token. It is the output of the tokenizer module. For tokendata=1
2969 tables, this includes any embedded 0x00 and trailing data.
2970 </p>
2971 </dd>
2972 <dt style="white-space:pre;font-family:monospace;font-size:120%" id="xInstToken">
2973 <b>int (*xInstToken)(Fts5Context*, int iIdx, int iToken, const char**, int*)</b></dt><dd>
2974 <p style="margin-top:0.1em">
2975 This is used to access token iToken of phrase hit iIdx within the
2976 current row. If iIdx is less than zero or greater than or equal to the
2977 value returned by xInstCount(), SQLITE_RANGE is returned. Otherwise,
2978 output variable (*ppToken) is set to point to a buffer containing the
2979 matching document token, and (*pnToken) to the size of that buffer in
2980 bytes. This API is not available if the specified token matches a
2981 prefix query term. In that case both output variables are always set
2982 to 0.
2983 </p>
2984
2985 <p>
2986 The output text is not a copy of the document text that was tokenized.
2987 It is the output of the tokenizer module. For tokendata=1 tables, this
2988 includes any embedded 0x00 and trailing data.
2989 </p>
2990
2991 <p>
2992 This API can be quite slow if used with an FTS5 table created with the
2993 "detail=none" or "detail=column" option.
2994 </p>
2995 </dd>
2996 </dl>
2997
2998
2999 <a name="the_fts5vocab_virtual_table_module"></a>
3000 <h1 tags="fts5vocab" id="the_fts5vocab_virtual_table_module"><span>8. </span>The fts5vocab Virtual Table Module</h1>
3001
3002 <p> The fts5vocab virtual table module allows users to extract information from
3003 an FTS5 full-text index directly. The fts5vocab module is a part of FTS5 - it
3004 is available whenever FTS5 is.
3005
3006 </p><p> Each fts5vocab table is associated with a single FTS5 table. An fts5vocab
3007 table is usually created by specifying two arguments in place of column names
3008 in the CREATE VIRTUAL TABLE statement - the name of the associated FTS5 table
3009 and the type of fts5vocab table. Currently there are three types of fts5vocab
3010 table; "row", "col" and "instance". Unless the fts5vocab table is created
3011 within the "temp" database, it must be part of the same database as the
3012 associated FTS5 table.
3013
3014 </p><div class="codeblock"><pre><i>-- Create an fts5vocab "row" table to query the full-text index belonging
3015 -- to FTS5 table "ft1".</i>
3016 CREATE VIRTUAL TABLE ft1_v USING fts5vocab('ft1', 'row');
3017
3018 <i>-- Create an fts5vocab "col" table to query the full-text index belonging
3019 -- to FTS5 table "ft2".</i>
3020 CREATE VIRTUAL TABLE ft2_v USING fts5vocab(ft2, col);
3021
3022 <i>-- Create an fts5vocab "instance" table to query the full-text index
3023 -- belonging to FTS5 table "ft3".</i>
3024 CREATE VIRTUAL TABLE ft3_v USING fts5vocab(ft3, instance);
3025 </pre></div>
3026
3027 <p> If an fts5vocab table is created in the temp database, it may be associated
3028 with an FTS5 table in any attached database. In order to attach the fts5vocab
3029 table to an FTS5 table located in a database other than "temp", the name of the
3030 database is inserted before the FTS5 table name in the CREATE VIRTUAL TABLE
3031 arguments. For example:
3032
3033 </p><div class="codeblock"><pre><i>-- Create an fts5vocab "row" table to query the full-text index belonging
3034 -- to FTS5 table "ft1" in database "main".</i>
3035 CREATE VIRTUAL TABLE temp.ft1_v USING fts5vocab(main, 'ft1', 'row');
3036
3037 <i>-- Create an fts5vocab "col" table to query the full-text index belonging
3038 -- to FTS5 table "ft2" in attached database "aux".</i>
3039 CREATE VIRTUAL TABLE temp.ft2_v USING fts5vocab('aux', ft2, col);
3040
3041 <i>-- Create an fts5vocab "instance" table to query the full-text index
3042 -- belonging to FTS5 table "ft3" in attached database "other".</i>
3043 CREATE VIRTUAL TABLE temp.ft2_v USING fts5vocab('aux', ft3, 'instance');
3044 </pre></div>
3045
3046 <p> Specifying three arguments when creating an fts5vocab table in any database
3047 other than "temp" results in an error.
3048
3049 </p><p> An fts5vocab table of type "row" contains one row for each distinct term
3050 in the associated FTS5 table. The table columns are as follows:
3051
3052 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
3053 <tr style="text-align:left"><th>Column</th><th>Contents
3054 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td>term</td><td> The term, as stored in the FTS5 index.
3055 </td></tr><tr style="text-align:left"><td>doc</td><td> The number of rows that contain at least one instance of the term.
3056 </td></tr><tr style="text-align:left;background-color:#DDDDDD"><td>cnt</td><td> The total number of instances of the term in the entire FTS5 table.
3057 </td></tr></table>
3058
3059 <p> An fts5vocab table of type "col" contains one row for each distinct term/column
3060 combination in the associated FTS5 table. Table columns are as follows:
3061
3062 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
3063 <tr style="text-align:left"><th>Column</th><th>Contents
3064 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td>term</td><td> The term, as stored in the FTS5 index.
3065 </td></tr><tr style="text-align:left"><td>col</td><td> The name of the FTS5 table column that contains the term.
3066 </td></tr><tr style="text-align:left;background-color:#DDDDDD"><td>doc</td><td> The number of rows in the FTS5 table for which column $col
3067 contains at least one instance of the term.
3068 </td></tr><tr style="text-align:left"><td>cnt</td><td> The total number of instances of the term that appear in
3069 column $col of the FTS5 table (considering all rows).
3070 </td></tr></table>
3071
3072 <p> An fts5vocab table of type "instance" contains one row for each term
3073 instance stored in the associated FTS index. Assuming the FTS5 table is
3074 created with the 'detail' option set to 'full', table columns are as follows:
3075
3076 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
3077 <tr style="text-align:left"><th>Column</th><th>Contents
3078 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td>term</td><td> The term, as stored in the FTS5 index.
3079 </td></tr><tr style="text-align:left"><td>doc</td><td> The rowid of the document that contains the term instance.
3080 </td></tr><tr style="text-align:left;background-color:#DDDDDD"><td>col</td><td> The name of the column that contains the term instance.
3081 </td></tr><tr style="text-align:left"><td>offset</td><td> The index of the term instance within its column. Terms
3082 are numbered in order of occurrence starting from 0.
3083 </td></tr></table>
3084
3085 <p> If the FTS5 table is created with the 'detail' option set to 'col', then
3086 the <i>offset</i> column of an instance virtual table always contains NULL.
3087 In this case there is one row in the table for each unique term/doc/col
3088 combination. Or, if the FTS5 table is created with 'detail' set to 'none',
3089 then both <i>offset</i> and <i>col</i> always contain NULL values. For
3090 detail=none FTS5 tables, there is one row in the fts5vocab table for each
3091 unique term/doc combination.
3092
3093 </p><p>Example:
3094
3095 </p><div class="codeblock"><pre><i>-- Assuming a database created using:</i>
3096 CREATE VIRTUAL TABLE ft1 USING fts5(c1, c2);
3097 INSERT INTO ft1 VALUES('apple banana cherry', 'banana banana cherry');
3098 INSERT INTO ft1 VALUES('cherry cherry cherry', 'date date date');
3099
3100 <i>-- Then querying the following fts5vocab table (type "col") returns:
3101 --
3102 -- apple | c1 | 1 | 1
3103 -- banana | c1 | 1 | 1
3104 -- banana | c2 | 1 | 2
3105 -- cherry | c1 | 2 | 4
3106 -- cherry | c2 | 1 | 1
3107 -- date | c3 | 1 | 3
3108 --</i>
3109 CREATE VIRTUAL TABLE ft1_v_col USING fts5vocab(ft1, col);
3110
3111 <i>-- Querying an fts5vocab table of type "row" returns:
3112 --
3113 -- apple | 1 | 1
3114 -- banana | 1 | 3
3115 -- cherry | 2 | 5
3116 -- date | 1 | 3
3117 --</i>
3118 CREATE VIRTUAL TABLE ft1_v_row USING fts5vocab(ft1, row);
3119
3120 <i>-- And, for type "instance"
3121 INSERT INTO ft1 VALUES('apple banana cherry', 'banana banana cherry');
3122 INSERT INTO ft1 VALUES('cherry cherry cherry', 'date date date');
3123 --
3124 -- apple | 1 | c1 | 0
3125 -- banana | 1 | c1 | 1
3126 -- banana | 1 | c2 | 0
3127 -- banana | 1 | c2 | 1
3128 -- cherry | 1 | c1 | 2
3129 -- cherry | 1 | c2 | 2
3130 -- cherry | 2 | c1 | 0
3131 -- cherry | 2 | c1 | 1
3132 -- cherry | 2 | c1 | 2
3133 -- date | 2 | c2 | 0
3134 -- date | 2 | c2 | 1
3135 -- date | 2 | c2 | 2
3136 --</i>
3137 CREATE VIRTUAL TABLE ft1_v_instance USING fts5vocab(ft1, instance);
3138 </pre></div>
3139
3140 <a name="fts5shadowtables"></a>
3141
3142 <h1 id="fts5_data_structures"><span>9. </span>FTS5 Data Structures</h1>
3143
3144 <p>This section describes at a high-level the way the FTS module stores its
3145 index and content in the database. It is not necessary to read or understand
3146 the material in this section in order to use FTS in an application. However, it
3147 may be useful to application developers attempting to analyze and understand
3148 FTS performance characteristics, or to developers contemplating enhancements to
3149 the existing FTS feature set.
3150
3151 </p><p>
3152 When an FTS5 virtual table is created in a database, between 3 and 5 real
3153 tables are created in the database. These are known as "<a href="vtab.html#xshadowname">shadow tables</a>", and
3154 are used by the virtual table module to store persistent data. They should not
3155 be accessed directly by the user. Many other virtual table modules, including
3156 <a href="fts3.html">FTS3</a> and <a href="rtree.html">rtree</a>, also create and use shadow tables.
3157
3158 </p><p>FTS5 creates the following shadow tables. In each case the actual table name
3159 is based on the name of the FTS5 virtual table (in the following, replace
3160 % with the name of the virtual table to find the actual shadow table name).
3161
3162 </p><div class="codeblock"><pre><i>-- This table contains most of the full-text index data. </i>
3163 CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
3164
3165 <i>-- This table contains the remainder of the full-text index data. </i>
3166 <i>-- It is almost always much smaller than the %_data table. </i>
3167 CREATE TABLE %_idx(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID;
3168
3169 <i>-- Contains the values of persistent configuration parameters.</i>
3170 CREATE TABLE %_config(k PRIMARY KEY, v) WITHOUT ROWID;
3171
3172 <i>-- Contains the size of each column of each row in the virtual table</i>
3173 <i>-- in tokens. This shadow table is not present if the "columnsize"</i>
3174 <i>-- option is set to 0.</i>
3175 CREATE TABLE %_docsize(id INTEGER PRIMARY KEY, sz BLOB);
3176
3177 <i>-- Contains the actual data inserted into the FTS5 table. There</i>
3178 <i>-- is one "cN" column for each indexed column in the FTS5 table.</i>
3179 <i>-- This shadow table is not present for contentless or external </i>
3180 <i>-- content FTS5 tables. </i>
3181 CREATE TABLE %_content(id INTEGER PRIMARY KEY, c0, c1...);
3182 </pre></div>
3183
3184 <p>The following sections describe in more detail how these five tables are
3185 used to store FTS5 data.
3186
3187 </p><h2 id="varint_format"><span>9.1. </span>Varint Format</h2>
3188
3189 <p>The sections below refer to 64-bit signed integers stored in "varint" form.
3190 FTS5 uses the same varint format as used in various places by the SQLite core.
3191
3192 </p><p>A varint is between 1 and 9 bytes in length. The varint consists of either
3193 zero or more bytes which have the high-order bit set followed by a single byte
3194 with the high-order bit clear, or nine bytes, whichever is shorter. The lower
3195 seven bits of each of the first eight bytes and all 8 bits of the ninth byte
3196 are used to reconstruct the 64-bit twos-complement integer. Varints are
3197 big-endian: bits taken from the earlier byte of the varint are more significant
3198 than bits taken from the later bytes.
3199
3200 </p><h2 id="the_fts_index_idx_and_data_tables_"><span>9.2. </span>The FTS Index (%_idx and %_data tables)</h2>
3201
3202 <p>The FTS index is an ordered key-value store where the keys are document
3203 terms or term prefixes and the associated values are "doclists". A doclist is a
3204 packed array of varints that encodes the position of each instance of the term
3205 within the FTS5 table. The position of a single term instance is defined as the
3206 combination of:
3207
3208 </p><ul>
3209 <li> The rowid of the FTS5 table row it appears in,
3210 </li><li> The index of the column the term instance appears in (columns are
3211 numbered from left to right starting from zero), and
3212 </li><li> The offset of the term within the column value (i.e. the number of
3213 tokens that appear within the column value before this one).
3214 </li></ul>
3215
3216 <p>The FTS index contains up to (nPrefix+1) entries for each token in the
3217 data set, where nPrefix is the number of defined <a href="#prefix_indexes">
3218 prefix indexes</a>.
3219
3220 </p><p>Keys associated with the main FTS index (the one that is not a prefix
3221 index) are prefixed with the character "0". Keys for the first prefix
3222 index are prefixed with "1". Keys for the second prefix index are
3223 prefixed with "2", and so on. For example, if the token "document" is
3224 inserted into an FTS5 table with <a href="#prefix_indexes">prefix indexes</a>
3225 specified by prefix="2 4", then the keys added to the FTS index would be
3226 "0document", "1do" and "2docu".
3227
3228 </p><p>The FTS index entries are not stored in a single tree or hash table
3229 structure. Instead, they are stored in a series of immutable b-tree like
3230 structures referred to as "segment b-trees". Each time a write to the FTS5
3231 table is committed, one or more (but usually just one) new segment b-trees
3232 are added containing both the new entries and tombstones for any deleted
3233 entries. When the FTS index is queried, the reader queries each segment
3234 b-tree in turn and merges the results, giving priority to newer data.
3235
3236 </p><p>Each segment b-tree is assigned a numerical level. When a new segment
3237 b-tree is written to the database as part of committing a transaction,
3238 it is assigned to level 0. Segment b-trees belonging to a single level are
3239 periodically merged together to create a single, larger segment b-tree
3240 that is assigned to the next level (i.e. level 0 segment b-trees are
3241 merged to become a single level 1 segment b-tree). Thus the numerically
3242 larger levels contain older data in (usually) larger segment b-trees.
3243 Refer to the
3244 <a href="#the_automerge_configuration_option">'automerge'</a>,
3245 <a href="#the_crisismerge_configuration_option">'crisismerge'</a> and
3246 <a href="#the_usermerge_configuration_option">'usermerge'</a> options, along
3247 with the
3248 <a href="#the_merge_command">'merge'</a> and
3249 <a href="#the_optimize_command">'optimize'</a> commands for details on how to
3250 control the merging.
3251
3252 </p><p>In cases where the doclist associated with a term or term prefix is very
3253 large, there may be an associated <a href="#doclist_index_format">doclist
3254 index</a>. A doclist index is similar to the set of internal nodes of a b-tree.
3255 It allows a large doclist to be efficiently queried for rowids or ranges of
3256 rowids. For example, when processing a query like:
3257
3258 </p><div class="codeblock"><pre>SELECT ... FROM fts_table('term') WHERE rowid BETWEEN ? AND ?
3259 </pre></div>
3260
3261 <p>FTS5 uses the segment b-tree index to locate the doclist for term "term",
3262 then uses its doclist index (assuming it is present) to efficiently identify
3263 the subset of matches with rowids in the required range.
3264
3265 </p><h3 id="data_structure"><span>9.2.1. </span>The %_data Table Rowid Space</h3>
3266
3267 <div class="codeblock"><pre>CREATE TABLE %_data(
3268 id INTEGER PRIMARY KEY,
3269 block BLOB
3270 );
3271 </pre></div>
3272
3273 <p>The %_data table is used to store three types of records:
3274
3275 </p><ul>
3276 <li> The special <a href="#structure_record_format">structure record</a>,
3277 stored with id=10.
3278 </li><li> The special <a href="#averages_record_format">averages record</a>,
3279 stored with id=1.
3280 </li><li> A record to store each <a href="#segment_b_tree_format">segment b-tree</a>
3281 leaf and <a href="#doclist_index_format">doclist index</a> leaf and
3282 internal node. See below for how id values are calculated for these
3283 records.
3284 </li></ul>
3285
3286 <p>Each segment b-tree in the system is assigned a unique 16-bit segment id.
3287 Segment ids may only be reused after the original owner segment b-tree is
3288 completely merged into a higher level segment b-tree. Within a segment b-tree,
3289 each leaf page is assigned a unique page number - 1 for the first leaf page, 2
3290 for the second, and so on.
3291
3292 </p><p>Each doclist index leaf page is also assigned a page number. The first
3293 (leftmost) leaf page in a doclist index is assigned the same page number as
3294 the segment b-tree leaf page on which its term appears (because doclist indexes
3295 are only created for terms with very long doclists, at most one term per
3296 segment b-tree leaf has an associated doclist index). Call this page number P.
3297 If the doclist is so large that it requires a second leaf, the second leaf is
3298 assigned page number P+1. The third leaf P+2. Each tier of a doclist index
3299 b-tree (leaves, parents of leaves, grandparents etc.) is assigned page numbers
3300 in this fashion, starting with page number P.
3301
3302 </p><p>The "id" value used in the %_data table to store any given segment b-tree
3303 leaf or doclist index leaf or node is composed as follows:
3304
3305 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
3306 <tr style="text-align:left"><th>Rowid&nbsp;Bits </th><th>Contents
3307 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td>38..43 </td><td> (16 bit) Segment b-tree id value.
3308 </td></tr><tr style="text-align:left"><td>37 </td><td> (1 bit) Doclist index flag. Set for doclist index pages, clear
3309 for segment b-tree leaves.
3310 </td></tr><tr style="text-align:left;background-color:#DDDDDD"><td>32..36 </td><td> (5 bits) Height in tree. This is set to 0 for segment b-tree
3311 and doclist index leaves, to 1 for the parents of doclist
3312 index leaves, 2 for the grandparents, etc.
3313 </td></tr><tr style="text-align:left"><td>0..31 </td><td> (32 bits) Page number
3314 </td></tr></table>
3315
3316 <h3 id="structure_record_format"><span>9.2.2. </span>Structure Record Format</h3>
3317
3318 <p>The structure record identifies the set of segment b-trees that make up the
3319 current FTS index, along with details of any ongoing incremental merge
3320 operations. It is stored in the %_data table with id=10.
3321
3322 A structure record begins with a single 32-bit unsigned value - the cookie
3323 value. This value is incremented each time the structure is modified.
3324 Following the cookie value are three varint values, as follows:
3325
3326 </p><ul>
3327 <li> The number of levels in the index (i.e. the maximum level associated
3328 with any segment b-tree plus one).
3329 </li><li> The total number of segment b-trees in the index.
3330 </li><li> The total number of segment b-tree leaves written to level 0 trees
3331 since the FTS5 table was created.
3332 </li></ul>
3333
3334 <p>Then, for each level from 0 to nLevel:
3335
3336 </p><ul>
3337 <li> The number of input segments from the previous level being used as
3338 inputs for the current incremental merge, or zero if there is no
3339 ongoing incremental merge to create a new segment b-tree for this level.
3340 </li><li> The total number of segment b-trees on the level.
3341 </li><li> Then, for each segment b-tree, from oldest to newest:
3342 <ul>
3343 <li> The segment id.
3344 </li><li> Page number of first leaf (often 1, always >0).
3345 </li><li> Page number of last leaf (always >0).
3346 </li></ul>
3347 </li></ul>
3348
3349 <h3 id="averages_record_format"><span>9.2.3. </span>Averages Record Format</h3>
3350
3351 <p>The averages record, which is always stored with id=1 in the %_data table,
3352 does not store the average of anything. Instead, it contains a vector of
3353 (nCol+1) packed varint values, where nCol is the number of columns in the FTS5
3354 table, including unindexed columns. The first varint contains the total
3355 number of rows in the FTS5 table. The second contains the total number of
3356 tokens in all values stored in the leftmost FTS5 table column. The third the
3357 number of tokens in all values for the next leftmost, and so on. The value for
3358 unindexed columns is always zero.
3359
3360 </p><h3 id="segment_b_tree_format"><span>9.2.4. </span>Segment B-Tree Format</h3>
3361
3362 <h4 id="the_key_doclist_format"><span>9.2.4.1. </span>The Key/Doclist Format</h4>
3363
3364 <p>The key/doclist format is a format used to store a series of keys (document
3365 terms or term prefixes prefixed by a single character to indentify the specific
3366 index to which they belong) in sorted order, each with their associated
3367 doclist. The format consists of alternating keys and doclists packed together.
3368
3369 </p><p>The first key is stored as:
3370 </p><ul>
3371 <li> A varint indicating the number of bytes in the key (N), followed by
3372 </li><li> The key data itself (N bytes).
3373 </li></ul>
3374
3375 <p>Each subsequent key is stored as:
3376 </p><ul>
3377 <li> A varint indicating the size of the prefix that the key has in common
3378 with the previous key in bytes,
3379 </li><li> A varint indicating the number of bytes in the key following the
3380 common prefix (N), followed by
3381 </li><li> The key suffix data itself (N bytes).
3382 </li></ul>
3383
3384 <p>For example, if the first two keys in an FTS5 key/doclist record are
3385 "0challenger" and "0chandelier", then the first key is stored as varint 11
3386 followed by the 11 bytes "0challenger", and the second key is stored as varints
3387 4 and 7, followed by the 7 bytes "ndelier".
3388
3389 </p><center><div style="max-width:956px;"><svg xmlns='http://www.w3.org/2000/svg' class="pikchr" viewBox="0 0 956.102 126.72">
3390 <path d="M62,77L91,77L91,48L62,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3391 <path d="M91,77L149,77L149,48L91,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3392 <path d="M149,77L437,77L437,48L149,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3393 <text x="293" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">doclist 0</text>
3394 <path d="M437,77L466,77L466,48L437,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3395 <path d="M466,77L494,77L494,48L466,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3396 <path d="M494,77L538,77L538,48L494,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3397 <path d="M538,77L826,77L826,48L538,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3398 <text x="682" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">doclist 1</text>
3399 <text x="892" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">key/doclist 2...</text>
3400 <path d="M826,48L883,48" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3401 <path d="M826,77L883,77" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3402 <text x="120" y="114" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">key 0 data</text>
3403 <polygon points="120,77 124,89 116,89" style="fill:rgb(0,0,0)"/>
3404 <path d="M120,99L120,83" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3405 <text x="77" y="12" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">key 0 size (varint)</text>
3406 <polygon points="77,48 72,37 81,37" style="fill:rgb(0,0,0)"/>
3407 <path d="M77,27L77,43" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3408 <text x="358" y="114" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">key 1 prefix size (varint)</text>
3409 <polygon points="451,77 441,84 439,76" style="fill:rgb(0,0,0)"/>
3410 <path d="M358,99L446,79" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3411 <text x="480" y="12" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">key 1 suffix size (varint)</text>
3412 <polygon points="480,48 476,37 484,37" style="fill:rgb(0,0,0)"/>
3413 <path d="M480,27L480,43" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3414 <text x="585" y="114" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">key 1 prefix data</text>
3415 <polygon points="516,77 528,77 526,85" style="fill:rgb(0,0,0)"/>
3416 <path d="M585,99L521,79" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3417 </svg>
3418 </div>
3419 <p><i>Figure 1 - Term/Doclist Format
3420 </i></p></center>
3421
3422 <p>Each doclist identifies the rows (by their rowid values) that contain at
3423 least one instance of the term or term prefix and an associated position list,
3424 or "poslist" enumerating the position of each term instance within the row. In
3425 this sense a "position" is defined as a column number and term offset within
3426 the column value.
3427
3428 </p><p>Within a doclist, documents are always stored in order sorted by rowid. The
3429 first rowid in a doclist is stored as is, as a varint. It is immediately
3430 followed by its associated position list. Following this, the difference
3431 between the first rowid and the second, as a varint, followed by the doclist
3432 associated with the second rowid in the doclist. And so on.
3433
3434 </p><p>There is no way to determine the size of a doclist by parsing it. This must
3435 be stored externally. See the <a href="#data_pagination">section below</a> for
3436 details of how this is accomplished in FTS5.
3437
3438 </p><center><div style="max-width:889px;"><svg xmlns='http://www.w3.org/2000/svg' class="pikchr" viewBox="0 0 889.459 79.92">
3439 <path d="M46,77L89,77L89,48L46,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3440 <path d="M89,77L377,77L377,48L89,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3441 <text x="233" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">position list 0</text>
3442 <path d="M377,77L420,77L420,48L377,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3443 <path d="M420,77L708,77L708,48L420,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3444 <text x="564" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">position list 1</text>
3445 <path d="M708,77L751,77L751,48L708,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3446 <text x="822" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">position list 2...</text>
3447 <path d="M751,48L809,48" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3448 <path d="M751,77L809,77" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3449 <text x="67" y="12" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">rowid 0 (varint)</text>
3450 <polygon points="67,48 63,37 72,37" style="fill:rgb(0,0,0)"/>
3451 <path d="M67,27L67,43" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3452 <text x="398" y="12" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">rowid 1 (delta-encoded varint)</text>
3453 <polygon points="398,48 394,37 403,37" style="fill:rgb(0,0,0)"/>
3454 <path d="M398,27L398,43" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3455 <text x="730" y="12" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">rowid 3 (delta-encoded varint)</text>
3456 <polygon points="730,48 725,37 734,37" style="fill:rgb(0,0,0)"/>
3457 <path d="M730,27L730,43" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3458 </svg>
3459 </div>
3460 <p><i>Figure 2 - Doclist Format
3461 </i></p></center>
3462
3463 <p>A position list - often shortened to "poslist" - identifies the column
3464 and token offset within the row of each instance of the token in question.
3465 The format of a poslist is:
3466
3467 </p><ul>
3468 <li> Varint set to twice the size of the poslist, not including this field,
3469 plus one if the "delete" flag is set on the entry.
3470 </li><li> A (possibly empty) list of offsets for column 0 (the leftmost column) of
3471 the row. Each offset is stored as a varint. The first varint contains
3472 the value of the first offset, plus 2. The second variant contains the
3473 difference between the second and first offsets, plus 2. etc. For
3474 example, if the offset list is to contain offsets 0, 10, 15 and 16, it
3475 is encoded by packing the following values, encoded as varints, end to
3476 end:
3477 <pre>
3478 2, 12, 7, 3
3479 </pre>
3480 </li><li> For each column other than column 0 that contains one of more instances
3481 of the token:
3482 <ul>
3483 <li> Byte value 0x01.
3484 </li><li> The column number, as a varint.
3485 </li><li> An offset list, in the same format as the offset list for column 0.
3486 </li></ul>
3487 </li></ul>
3488
3489 <center><div style="max-width:785px;"><svg xmlns='http://www.w3.org/2000/svg' class="pikchr" viewBox="0 0 785.606 133.92">
3490 <path d="M77,77L121,77L121,48L77,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3491 <path d="M121,77L409,77L409,48L121,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3492 <text x="265" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">col 0 offset-list</text>
3493 <path d="M409,77L452,77L452,48L409,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3494 <text x="430" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">0x01</text>
3495 <path d="M452,77L495,77L495,48L452,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3496 <path d="M495,77L783,77L783,48L495,48Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3497 <text x="639" y="63" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">col i offset-list</text>
3498 <text x="99" y="12" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">nSize*2 + bDel (varint)</text>
3499 <polygon points="99,48 95,37 103,37" style="fill:rgb(0,0,0)"/>
3500 <path d="M99,27L99,43" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3501 <text x="473" y="12" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">column number (i)</text>
3502 <polygon points="473,48 469,37 478,37" style="fill:rgb(0,0,0)"/>
3503 <path d="M473,27L473,43" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3504 <path d="M121,92L121,106L783,106L783,92" style="fill:none;stroke-width:2.16;stroke-linejoin:round;stroke:rgb(0,0,0);" />
3505 <text x="452" y="121" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">nSize bytes</text>
3506 </svg>
3507 </div>
3508 <p><i>Figure 3 - Position List (poslist) With Offsets in Columns 0 and i
3509 </i></p></center>
3510
3511 <h4 id="data_pagination"><span>9.2.4.2. </span>Pagination</h4>
3512
3513 <p>If it is small enough (by default this means smaller than 4000 bytes), the
3514 entire contents of a segment b-tree may be stored in the key/doclist format
3515 described in the previous section as a single blob within the %_data table.
3516 Otherwise, the key/doclist is split into pages (by default, of approximately
3517 4000 bytes each) and stored in a contiguous set of entries in the %_data table
3518 (<a href="#data_structure">see above</a> for details).
3519
3520 </p><p>When a key/doclist is divided into pages, the following modifications are
3521 made to the format:
3522
3523 </p><ul>
3524 <li> A single varint or key data field never spans two pages.
3525 </li><li> The first key on each page is not prefix-compressed. It is stored in
3526 the format described above for the first key of a doclist - its size as
3527 a varint followed by the key data.
3528 </li><li> If there are one or more rowids on a page before the first key, then
3529 the first of them is not delta compressed. It is stored as is, just as
3530 if it were the first rowid of its doclist (which it may or may not be).
3531 </li></ul>
3532
3533 <p>Each page also has fixed-size 4-byte header and a variably-sized footer.
3534 The header is divided into 2 16-bit big-endian integer fields. They
3535 contain:
3536
3537 </p><ul>
3538 <li> The byte offset of the first rowid value on the page, if it occurs
3539 before the first key, or 0 otherwise.
3540 </li><li> The byte offset of the page footer.
3541 </li></ul>
3542
3543 <p>The page footer consists of a series of varints containing the byte offset
3544 of each key that appears on the page. The page footer is zero bytes in size
3545 if there are no keys on the page.
3546
3547 </p><center><div style="max-width:721px;"><svg xmlns='http://www.w3.org/2000/svg' class="pikchr" viewBox="0 0 721.267 79.92">
3548 <path d="M10,30L54,30L54,2L10,2Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3549 <text x="32" y="16" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">hdr</text>
3550 <path d="M54,30L630,30L630,2L54,2Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3551 <text x="342" y="16" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">modified key/doclist data</text>
3552 <path d="M630,30L702,30L702,2L630,2Z" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3553 <text x="666" y="16" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">footer</text>
3554 <text x="32" y="67" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">4 bytes</text>
3555 <text x="666" y="67" text-anchor="middle" fill="rgb(0,0,0)" dominant-baseline="central">variable size</text>
3556 <polygon points="32,30 36,42 28,42" style="fill:rgb(0,0,0)"/>
3557 <path d="M32,52L32,36" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3558 <polygon points="666,30 670,42 661,42" style="fill:rgb(0,0,0)"/>
3559 <path d="M666,52L666,36" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
3560 </svg>
3561 </div>
3562 <p><i>Figure 4 - Page Format
3563 </i></p></center>
3564
3565 <h4 id="data_term_index"><span>9.2.4.3. </span>Segment Index Format</h4>
3566
3567 <p>The result of formatting the contents of the segment b-tree in the
3568 key/doclist format and then splitting it into pages is something very
3569 similar to the leaves of a b+tree. Instead of creating a format for
3570 the internal nodes of this b+tree and storing them in the %_data table
3571 alongside the leaves, the keys that would have been stored on such nodes are
3572 added to the %_idx table, defined as:
3573
3574 </p><div class="codeblock"><pre>CREATE TABLE %_idx(
3575 segid INTEGER, <i>-- segment id</i>
3576 term TEXT, <i>-- prefix of first key on page</i>
3577 pgno INTEGER, <i>-- (2*pgno + bDoclistIndex)</i>
3578 PRIMARY KEY(segid, term)
3579 );
3580 </pre></div>
3581
3582 <p>For each "leaf" page that contains at least one key, an entry is added
3583 to the %_idx table. Fields are set as follows:
3584
3585 </p><table striped="1" style="margin:1em auto; width:80%; border-spacing:0">
3586 <tr style="text-align:left"><th>Column</th><th>Contents
3587 </th></tr><tr style="text-align:left;background-color:#DDDDDD"><td>segid</td><td> The integer segment id.
3588 </td></tr><tr style="text-align:left"><td>term</td><td> The smallest prefix of the first key on the page that
3589 is larger than all keys on the previous page. For the
3590 first page in a segment, this prefix is zero bytes in
3591 size.
3592 </td></tr><tr style="text-align:left;background-color:#DDDDDD"><td>pgno</td><td> This field encodes both the page number (within the
3593 segment - starting from 1) and the doclist index flag.
3594 The doclist index flag is set if the final key on the
3595 page has an <a href="#doclist_index_format">associated
3596 doclist index</a>. The value of this field is:
3597 <pre>
3598 (pgno*2 + bDoclistIndexFlag)
3599 </pre>
3600 </td></tr></table>
3601
3602 <p>Then, to find the leaf for segment i that may contain term t, instead of
3603 searching through internal nodes, FTS5 runs the query:
3604
3605 </p><div class="codeblock"><pre>SELECT pgno FROM %_idx WHERE segid=$i AND term>=$t ORDER BY term LIMIT 1
3606 </pre></div>
3607
3608 <h4 id="doclist_index_format"><span>9.2.4.4. </span>Doclist Index Format</h4>
3609
3610 <p>The segment index described in the <a href="#data_term_index">previous
3611 section</a> allows a segment b-tree to be efficiently queried by term or,
3612 assuming there is a prefix index of the required size, a term prefix. The data
3613 structure described in this section, doclist indexes, allows FTS5 to
3614 efficiently search for a rowid or range or rowids within the doclist associated
3615 with a single term or term prefix.
3616
3617 </p><p>Not all keys have associated doclists indexes. By default, a doclist index
3618 is only added for a key if its doclist spans more than 4 segment b-tree leaf
3619 pages. Doclist indexes are themselves b-trees, with both leaves and internal
3620 nodes stored as entries in the %_data table, but in practice most doclists are
3621 small enough to fit on a single leaf. FTS5 uses the same rough size for doclist
3622 index node and leaves as it does for segment b-tree leaves (by default 4000
3623 bytes).
3624
3625 </p><p>Doclist index leaves and internal nodes use the same page format. The first
3626 byte is a "flags" byte. This is set to 0x00 for the root page of the doclist
3627 index b-tree, and 0x01 for all other pages. The remainder of the page is a
3628 series of tightly packed varints, as follows:
3629
3630 </p><ul>
3631 <li> page number of leftmost child page, followed by
3632 </li><li> the smallest rowid value on the left most child page, followed by
3633 </li><li> one varint for each subsequent child page, containing the value:
3634 <ul>
3635 <li> 0x00 if there are no rowids on the child page (this can only happen
3636 when the "child" page is actually a segment b-tree leaf), or
3637 </li><li> the difference between the smallest rowid on the child page and
3638 the previous rowid value stored on the doclist index page.
3639 </li></ul>
3640 </li></ul>
3641
3642 <p>For the leftmost doclist index leaf in a doclist index, the leftmost child
3643 page is the first segment b-tree leaf after the one that contains the key
3644 itself.
3645
3646 </p><h2 id="document_sizes_table_docsize_table_"><span>9.3. </span>Document Sizes Table (%_docsize table)</h2>
3647
3648 <div class="codeblock"><pre>CREATE TABLE %_docsize(
3649 id INTEGER PRIMARY KEY, -- id of FTS5 row this record pertains to
3650 sz BLOB -- blob containing nCol packed varints
3651 );
3652 </pre></div>
3653
3654 <p>Many common search result ranking functions require as an input the size
3655 in tokens of the result document (as a search term hit in a short document is
3656 considered more significant than one in a long document). To provide fast
3657 access to this information, for each row in the FTS5 table there exists a
3658 corresponding record (with the same rowid) in the %_docsize shadow table
3659 that contains the size of each column value in the row, in tokens.
3660
3661 </p><p>The column value sizes are stored in a blob containing one packed varint for
3662 each column of the FTS5 table, from left to right. The varint contains, of
3663 course, the total number of tokens in the corresponding column value. Unindexed
3664 columns are included in this vector of varints; for them the value is always
3665 set to zero.
3666
3667 </p><p>This table is used by the <a href="#xColumnSize">xColumnSize</a> API. It can
3668 be omitted altogether by specifying the
3669 <a href="#the_columnsize_option">columnsize=0</a> option. In that case the
3670 xColumnSize API is still available to auxiliary functions, but runs much more
3671 slowly.
3672
3673 </p><h2 id="the_table_contents_content_table_"><span>9.4. </span>The Table Contents (%_content table)</h2>
3674
3675 <div class="codeblock"><pre>CREATE TABLE %_content(id INTEGER PRIMARY KEY, c0, c1...);
3676 </pre></div>
3677
3678 <p>The actual table content - the values inserted into the FTS5 table, is
3679 stored in the %_content table. This table is created with one "c*" column for
3680 each column of the FTS5 table, including any unindexed columns. The values for
3681 the leftmost FTS5 table column are stored in column "c0" of the %_content
3682 table, the values from the next FTS5 table column in column "c1", and so on.
3683
3684 </p><p>This table is omitted completely for
3685 <a href="#external_content_and_contentless_tables">
3686 external content or contentless</a> FTS5 tables.
3687 tables.
3688
3689 </p><h2 id="configuration_options_config_table_"><span>9.5. </span>Configuration Options (%_config table)</h2>
3690
3691 <div class="codeblock"><pre>CREATE TABLE %_config(k PRIMARY KEY, v) WITHOUT ROWID;
3692 </pre></div>
3693
3694 <p>This table stores the values of any persistent configuration options.
3695 Column "k" stores the name of the option (text) and column "v" the value.
3696 Example contents:
3697
3698 </p><div class="codeblock"><pre>sqlite> SELECT * FROM fts_tbl_config;
3699 ┌─────────────┬──────┐
3700 │ k │ v │
3701 ├─────────────┼──────┤
3702 │ crisismerge │ 8 │
3703 │ pgsz │ 8000 │
3704 │ usermerge │ 4 │
3705 │ version │ 4 │
3706 └─────────────┴──────┘
3707 </pre></div>
3708
3709 <a name="appendix_a"></a>
3710 <h1 id="appendix_a" nonumber="1" tags="comparison with fts4">
3711 Appendix A: Comparison with FTS3/4
3712 </h1>
3713
3714 <p> Also available is the similar but more mature <a href="fts3.html">FTS3/4</a> module.
3715 FTS5 is a new version of FTS4 that includes various fixes and solutions for
3716 problems that could not be fixed in FTS4 without sacrificing backwards
3717 compatibility. Some of these problems are
3718 <a href="fts5.html#_summary_of_technical_differences_">described below</a>.
3719
3720 </p><h2 nonumber="1" id="_application_porting_guide_"> Application Porting Guide </h2>
3721
3722 <p> In order to use FTS5 instead of FTS3 or FTS4, applications usually require
3723 minimal modifications. Most of these fall into three categories - changes
3724 required to the CREATE VIRTUAL TABLE statement used to create the FTS table,
3725 changes required to SELECT queries used to execute queries against the table,
3726 and changes required to applications that use <a href="fts3.html#snippet">FTS auxiliary functions</a>.
3727
3728 </p><h3 nonumber="1" id="_changes_to_create_virtual_table_statements_"> Changes to CREATE VIRTUAL TABLE statements </h3>
3729
3730 <ol>
3731 <li> <p>The module name must be changed from "fts3" or "fts4" to "fts5".
3732
3733 </p></li><li> <p>All type information or constraint specifications must be removed from
3734 column definitions. FTS3/4 ignores everything following the column name in
3735 a column definition, FTS5 attempts to parse it (and will report an error
3736 if it fails to).
3737
3738 </p></li><li> <p>The "matchinfo=fts3" option is not available. The
3739 <a href="fts5.html#the_columnsize_option">"columnsize=0"</a> option is equivalent.
3740
3741 </p></li><li> <p>The notindexed= option is not available. Adding <a href="fts5.html#the_unindexed_column_option">UNINDEXED</a>
3742 to the column definition is equivalent.
3743
3744 </p></li><li> <p>The ICU tokenizer is not available.
3745
3746 </p></li><li> <p>The compress=, uncompress= and languageid= options are not available.
3747 There is as of yet no equivalent for their functionality.
3748 </p></li></ol>
3749
3750 <div class="codeblock"><pre><i> -- FTS3/4 statement </i>
3751 CREATE VIRTUAL TABLE t1 USING fts4(
3752 linkid INTEGER,
3753 header CHAR(20),
3754 text VARCHAR,
3755 notindexed=linkid,
3756 matchinfo=fts3,
3757 tokenizer=unicode61
3758 );
3759
3760 <i> -- FTS5 equivalent (note - the "tokenizer=unicode61" option is not</i>
3761 <i> -- required as this is the default for FTS5 anyway)</i>
3762 CREATE VIRTUAL TABLE t1 USING fts5(
3763 linkid UNINDEXED,
3764 header,
3765 text,
3766 columnsize=0
3767 );
3768 </pre></div>
3769
3770 <h3 nonumber="1" id="_changes_to_select_statements_"> Changes to SELECT statements </h3>
3771
3772 <ol>
3773 <li> <p>The "docid" alias does not exist. Applications must use "rowid"
3774 instead.
3775
3776 </p></li><li> <p>The behaviour of queries when a column-filter is specified both as
3777 part of the FTS query and by using a column as the LHS of a MATCH
3778 operator is slightly different. For a table with columns "a" and "b"
3779 and a query similar to:
3780 </p><div class="codeblock"><pre>... a MATCH 'b: string'
3781 </pre></div>
3782 <p>FTS3/4 searches for matches in column "b". However, FTS5 always
3783 returns zero rows, as results are first filtered for column "b", then
3784 for column "a", leaving no results. In other words, in FTS3/4 the
3785 inner filter overrides the outer, in FTS5 both filters are applied.
3786
3787 </p></li><li> <p>The FTS query syntax (right hand side of the MATCH operator) has
3788 changed in some ways. The FTS5 syntax is quite close to the FTS4
3789 "enhanced syntax". The main difference is that FTS5 is fussier
3790 about unrecognized punctuation characters and similar within query
3791 strings. Most queries that work with FTS3/4 should also work with
3792 FTS5, and those that do not should return parse errors.
3793 </p></li></ol>
3794
3795 <h3 nonumber="1" id="_auxiliary_function_changes_"> Auxiliary Function Changes </h3>
3796
3797 <p> FTS5 has no matchinfo() or offsets() function, and the snippet() function
3798 is not as fully-featured as in FTS3/4. However, since FTS5 does provide
3799 an API allowing applications to create <a href="fts5.html#custom_auxiliary_functions_api_reference">custom auxiliary functions</a>, any
3800 required functionality may be implemented within the application code.
3801
3802 </p><p> The set of built-in auxiliary functions provided by FTS5 may be
3803 improved upon in the future.
3804
3805 </p><h3 nonumber="1" id="_other_issues"> Other Issues</h3>
3806
3807 <ol>
3808 <li><p> The functionality provided by the fts4aux module is now provided
3809 by <a href="fts5.html#the_fts5vocab_virtual_table_module">fts5vocab</a>. The schema of these two tables is slightly different.
3810
3811 </p></li><li><p> The FTS3/4 "merge=X,Y" command has been replaced by the
3812 <a href="fts5.html#the_merge_command">FTS5 merge command</a>.
3813
3814 </p></li><li><p> The FTS3/4 "automerge=X" command has been replaced by the
3815 <a href="fts5.html#the_automerge_configuration_option">FTS5 automerge option</a>.
3816 </p></li></ol>
3817
3818 <a name="_summary_of_technical_differences_"></a>
3819 <h2 nonumber="1" tags="fts5 technical differences" id="_summary_of_technical_differences_">
3820 Summary of Technical Differences
3821 </h2>
3822
3823 <p>FTS5 is similar to FTS3/4 in that the primary task of each is to maintain
3824 an index mapping from each unique token to a list of instances of that token
3825 within a set of documents, where each instance is identified by the document
3826 in which it appears and its position within that document. For example:
3827
3828 </p><div class="codeblock"><pre><i>-- Given the following SQL:</i>
3829 CREATE VIRTUAL TABLE ft USING fts5(a, b);
3830 INSERT INTO ft(rowid, a, b) VALUES(1, 'X Y', 'Y Z');
3831 INSERT INTO ft(rowid, a, b) VALUES(2, 'A Z', 'Y Y');
3832
3833 <i>-- The FTS5 module creates the following mapping on disk:</i>
3834 A --&gt; (2, 0, 0)
3835 X --&gt; (1, 0, 0)
3836 Y --&gt; (1, 0, 1) (1, 1, 0) (2, 1, 0) (2, 1, 1)
3837 Z --&gt; (1, 1, 1) (2, 0, 1)
3838 </pre></div>
3839
3840 <p>In the example above, each triple identifies the location of a token
3841 instance by rowid, column number (columns are numbered sequentially
3842 starting at 0 from left to right) and position within the column value (the
3843 first token in a column value is 0, the second is 1, and so on). Using this
3844 index, FTS5 is able to provide timely answers to queries such as "the set
3845 of all documents that contain the token 'A'", or "the set of all documents
3846 that contain the sequence 'Y Z'". The list of instances associated with a
3847 single token is called an "instance-list".
3848
3849 </p><p>The principle difference between FTS3/4 and FTS5 is that in FTS3/4,
3850 each instance-list is stored as a single large database record, whereas
3851 in FTS5 large instance-lists are divided between multiple database records.
3852 This has the following implications for dealing with large databases that
3853 contain large lists:
3854
3855 </p><ul>
3856 <li> <p>FTS5 is able to load instance-lists into memory incrementally in
3857 order to reduce memory usage and peak allocation size. FTS3/4 very
3858 often loads entire instance-lists into memory.
3859
3860 </p></li><li> <p>When processing queries that feature more than one token, FTS5 is
3861 sometimes able to determine that the query can be answered by
3862 inspecting a subset of a large instance-list. FTS3/4 almost always
3863 has to traverse entire instance-lists.
3864
3865 </p></li><li> If an instance-list grows so large that it exceeds
3866 the <a href="limits.html#max_length">SQLITE_MAX_LENGTH</a> limit, FTS3/4 is unable to handle it. FTS5
3867 does not have this problem.
3868 </li></ul>
3869
3870 <p>For these reasons, many complex queries may use less memory and run faster
3871 using FTS5.
3872
3873 </p><p>Some other ways in which FTS5 differs from FTS3/4 are:
3874
3875 </p><ul>
3876 <li> <p>FTS5 supports "ORDER BY rank" for returning results in order of
3877 decreasing relevancy.
3878
3879 </p></li><li> <p>FTS5 features an API allowing users to create custom auxiliary
3880 functions for advanced ranking and text processing applications. The
3881 special "rank" column may be mapped to a custom auxiliary function
3882 so that adding "ORDER BY rank" to a query works as expected.
3883
3884 </p></li><li> <p>FTS5 recognizes unicode separator characters and case equivalence by
3885 default. This is also possible using FTS3/4, but must be explicitly
3886 enabled.
3887
3888 </p></li><li> <p>The query syntax has been revised where necessary to remove
3889 ambiguities and to make it possible to escape special characters
3890 in query terms.
3891
3892 </p></li><li> <p>By default, FTS3/4 occasionally merges together two or more of the
3893 b-trees that make up its full-text index within an INSERT, UPDATE or
3894 DELETE statement executed by the user. This means that any operation
3895 on an FTS3/4 table may turn out to be surprisingly slow, as FTS3/4
3896 may unpredictably choose to merge together two or more large b-trees
3897 within it. FTS5 uses incremental merging by default, which limits
3898 the amount of processing that may take place within any given
3899 INSERT, UPDATE or DELETE operation.
3900 </p></li></ul>
3901 <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/fts5.in?m=36e82d9638">2024-07-24 12:26:57</a> UTC </small></i></p>
3902