Debian Codegraph @

storage/innobase/fts/fts0que.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 2007, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file fts/fts0que.cc
29 Full Text Search functionality.
30
31 Created 2007/03/27 Sunny Bains
32 Completed 2011/7/10 Sunny and Jimmy Yang
33 *******************************************************/
34
35 #include <math.h>
36 #include <sys/types.h>
37 #include <iomanip>
38 #include <limits>
39 #include <vector>
40
41 #include "dict0dict.h"
42 #include "fts0ast.h"
43 #include "fts0fts.h"
44 #include "fts0pars.h"
45 #include "fts0plugin.h"
46 #include "fts0priv.h"
47 #include "fts0types.h"
48 #include "ha_prototypes.h"
49 #include "lob0lob.h"
50 #include "my_dbug.h"
51 #include "row0sel.h"
52 #include "ut0new.h"
53 #include "ut0rbt.h"
54
55 #define FTS_ELEM(t, n, i, j) (t[(i)*n + (j)])
56
57 #define RANK_DOWNGRADE (-1.0F)
58 #define RANK_UPGRADE (1.0F)
59
60 /* Maximum number of words supported in a phrase or proximity search. */
61 #define MAX_PROXIMITY_ITEM 128
62
63 /* Memory used by rbt itself for create and node add */
64 #define SIZEOF_RBT_CREATE sizeof(ib_rbt_t) + sizeof(ib_rbt_node_t) * 2
65 #define SIZEOF_RBT_NODE_ADD sizeof(ib_rbt_node_t)
66
67 /*Initial byte length for 'words' in fts_ranking_t */
68 #define RANKING_WORDS_INIT_LEN 4
69
70 /** Compare two FTS character strings case insensitively according to their
71 charset. This assumes that s1 is already in lower case.
72 @param[in] cs character set
73 @param[in] s1 key
74 @param[in] s2 node
75 @return 0 if the two strings are equal */
76 int innobase_fts_nocase_compare(const CHARSET_INFO *cs, const fts_string_t *s1,
77 const fts_string_t *s2);
78
79 // FIXME: Need to have a generic iterator that traverses the ilist.
80
81 typedef std::vector<fts_string_t, ut::allocator<fts_string_t>> word_vector_t;
82
83 struct fts_word_freq_t;
84
85 /** State of an FTS query. */
86 struct fts_query_t {
87 mem_heap_t *heap; /*!< Heap to use for allocations */
88
89 trx_t *trx; /*!< The query transaction */
90
91 dict_index_t *index; /*!< The FTS index to search */
92 /*!< FTS auxiliary common table def */
93
94 fts_table_t fts_common_table;
95
96 fts_table_t fts_index_table; /*!< FTS auxiliary index table def */
97
98 ulint total_size; /*!< total memory size used by query */
99
100 fts_doc_ids_t *deleted; /*!< Deleted doc ids that need to be
101 filtered from the output */
102
103 fts_ast_node_t *root; /*!< Abstract syntax tree */
104
105 fts_ast_node_t *cur_node; /*!< Current tree node */
106
107 ib_rbt_t *word_map; /*!< Matched word map for
108 searching by word*/
109
110 word_vector_t *word_vector; /*!< Matched word vector for
111 searching by index */
112
113 ib_rbt_t *doc_ids; /*!< The current set of matching
114 doc ids, elements are of
115 type fts_ranking_t */
116
117 ib_rbt_t *intersection; /*!< The doc ids that were found in
118 doc_ids, this tree will become
119 the new doc_ids, elements are of type
120 fts_ranking_t */
121
122 /*!< Prepared statement to read the
123 nodes from the FTS INDEX */
124 que_t *read_nodes_graph;
125
126 fts_ast_oper_t oper; /*!< Current boolean mode operator */
127
128 /*!< true if we want to collect the
129 word positions within the document */
130 bool collect_positions;
131
132 ulint flags; /*!< Specify the full text search type,
133 such as boolean search, phrase
134 search, proximity search etc. */
135
136 ulint distance; /*!< The proximity distance of a
137 phrase search. */
138
139 /*!< These doc ids are used as a
140 boundary condition when searching the
141 FTS index rows */
142
143 doc_id_t lower_doc_id; /*!< Lowest doc id in doc_ids */
144
145 doc_id_t upper_doc_id; /*!< Highest doc id in doc_ids */
146
147 bool boolean_mode; /*!< true if boolean mode query */
148
149 ib_vector_t *matched; /*!< Array of matching documents
150 (fts_match_t) to search for a phrase */
151
152 ib_vector_t **match_array; /*!< Used for proximity search, contains
153 position info for each matched word
154 in the word list */
155
156 uint64_t total_docs; /*!< The total number of documents */
157
158 ulint total_words; /*!< The total number of words */
159
160 dberr_t error; /*!< Error code if any, that is
161 encountered during query processing */
162
163 ib_rbt_t *word_freqs; /*!< RB tree of word frequencies per
164 document, its elements are of type
165 fts_word_freq_t */
166
167 ib_rbt_t *wildcard_words; /*!< words with wildcard */
168
169 bool multi_exist; /*!< multiple FTS_EXIST oper */
170
171 st_mysql_ftparser *parser; /*!< fts plugin parser */
172
173 /** limit value for the fts query */
174 ulonglong limit;
175
176 /** number of docs fetched by query. This is to restrict the
177 result with limit value */
178 ulonglong n_docs;
179 ulint nested_exp_count; /*!< number of nested sub expression limit */
180 };
181
182 /** For phrase matching, first we collect the documents and the positions
183 then we match. */
184 struct fts_match_t {
185 doc_id_t doc_id; /*!< Document id */
186
187 ulint start; /*!< Start the phrase match from
188 this offset within the positions
189 vector. */
190
191 ib_vector_t *positions; /*!< Offsets of a word in a
192 document */
193 };
194
195 /** For matching tokens in a phrase search. We use this data structure in
196 the callback that determines whether a document should be accepted or
197 rejected for a phrase search. */
198 struct fts_select_t {
199 doc_id_t doc_id; /*!< The document id to match */
200
201 ulint min_pos; /*!< For found to be true at least
202 one position must be greater than
203 min_pos. */
204
205 bool found; /*!< true if found */
206
207 fts_word_freq_t *word_freq; /*!< Word frequency instance of the
208 current word being looked up in
209 the FTS index */
210 };
211
212 typedef std::vector<ulint, ut::allocator<ulint>> pos_vector_t;
213
214 /** structure defines a set of ranges for original documents, each of which
215 has a minimum position and maximum position. Text in such range should
216 contain all words in the proximity search. We will need to count the
217 words in such range to make sure it is less than the specified distance
218 of the proximity search */
219 struct fts_proximity_t {
220 ulint n_pos; /*!< number of position set, defines
221 a range (min to max) containing all
222 matching words */
223 pos_vector_t min_pos; /*!< the minimum position (in bytes)
224 of the range */
225 pos_vector_t max_pos; /*!< the maximum position (in bytes)
226 of the range */
227 };
228
229 /** The match positions and tokesn to match */
230 struct fts_phrase_t {
231 fts_phrase_t(const dict_table_t *table)
232 : found(false),
233 match(nullptr),
234 tokens(nullptr),
235 distance(0),
236 charset(nullptr),
237 heap(nullptr),
238 page_size(dict_table_page_size(table)),
239 proximity_pos(nullptr),
240 parser(nullptr) {}
241
242 /** Match result */
243 bool found;
244
245 /** Positions within text */
246 const fts_match_t *match;
247
248 /** Tokens to match */
249 const ib_vector_t *tokens;
250
251 /** For matching on proximity distance. Can be 0 for exact match */
252 ulint distance;
253
254 /** Phrase match charset */
255 CHARSET_INFO *charset;
256
257 /** Heap for word processing */
258 mem_heap_t *heap;
259
260 /** Row page size */
261 const page_size_t page_size;
262
263 /** Position info for proximity search verification. Records the
264 min and max position of words matched */
265 fts_proximity_t *proximity_pos;
266
267 /** FTS plugin parser */
268 st_mysql_ftparser *parser;
269 };
270
271 /** Parameter passed to fts phrase match by parser */
272 struct fts_phrase_param_t {
273 fts_phrase_t *phrase; /*!< Match phrase instance */
274 ulint token_index; /*!< Index of token to match next */
275 mem_heap_t *heap; /*!< Heap for word processing */
276 };
277
278 /** For storing the frequency of a word/term in a document */
279 struct fts_doc_freq_t {
280 doc_id_t doc_id; /*!< Document id */
281 ulint freq; /*!< Frequency of a word in a document */
282 };
283
284 /** To determine the word frequency per document. */
285 struct fts_word_freq_t {
286 fts_string_t word; /*!< Word for which we need the freq,
287 it's allocated on the query heap */
288
289 ib_rbt_t *doc_freqs; /*!< RB Tree for storing per document
290 word frequencies. The elements are
291 of type fts_doc_freq_t */
292 uint64_t doc_count; /*!< Total number of documents that
293 contain this word */
294 double idf; /*!< Inverse document frequency */
295 };
296
297 static ib_rbt_compare fts_ranking_doc_id_cmp =
298 fts_doc_id_field_cmp<fts_ranking_t>;
299
300 /********************************************************************
301 Callback function to fetch the rows in an FTS INDEX record.
302 @return always true */
303 static bool fts_query_index_fetch_nodes(
304 void *row, /*!< in: sel_node_t* */
305 void *user_arg); /*!< in: pointer to ib_vector_t */
306
307 /********************************************************************
308 Read and filter nodes.
309 @return fts_node_t instance */
310 static dberr_t fts_query_filter_doc_ids(
311 fts_query_t *query, /*!< in: query instance */
312 const fts_string_t *word, /*!< in: the current word */
313 fts_word_freq_t *word_freq, /*!< in/out: word frequency */
314 const fts_node_t *node, /*!< in: current FTS node */
315 void *data, /*!< in: doc id ilist */
316 ulint len, /*!< in: doc id ilist size */
317 bool calc_doc_count); /*!< in: whether to remember doc
318 count */
319
320 /** Process (nested) sub-expression, create a new result set to store the
321 sub-expression result by processing nodes under current sub-expression
322 list. Merge the sub-expression result with that of parent expression list.
323 @param[in,out] node current root node
324 @param[in,out] visitor callback function
325 @param[in,out] arg argument for callback
326 @return DB_SUCCESS if all go well */
327 static dberr_t fts_ast_visit_sub_exp(fts_ast_node_t *node,
328 fts_ast_callback visitor, void *arg);
329
330 #if 0
331 /*****************************************************************//***
332 Find a doc_id in a word's ilist.
333 @return true if found. */
334 static
335 bool
336 fts_query_find_doc_id(
337 fts_select_t* select, /*!< in/out: search the doc id selected,
338 update the frequency if found. */
339 void* data, /*!< in: doc id ilist */
340 ulint len); /*!< in: doc id ilist size */
341 #endif
342
343 /** This function implements a simple "blind" query expansion search:
344 words in documents found in the first search pass will be used as
345 search arguments to search the document again, thus "expand"
346 the search result set.
347 @return DB_SUCCESS if success, otherwise the error code */
348 [[nodiscard]] static dberr_t fts_expand_query(
349 dict_index_t *index, /*!< in: FTS index to search */
350 fts_query_t *query); /*!< in: query result, to be freed
351 by the client */
352
353 static bool fts_search_docs_containing_all_tokens(fts_query_t *query,
354 ib_vector_t *tokens);
355
356 /** This function checks whether words in result documents are close to
357 each other (within proximity range as specified by "distance").
358 If "distance" is MAX_ULINT, then it will find all combinations of
359 positions of matching words and store min and max positions
360 in the "qualified_pos" for later verification.
361 @return true if words are close to each other, false if otherwise */
362 static bool fts_proximity_get_positions(
363 fts_match_t **match, /*!< in: query instance */
364 ulint num_match, /*!< in: number of matching
365 items */
366 ulint distance, /*!< in: distance value
367 for proximity search */
368 fts_proximity_t *qualified_pos); /*!< out: the position info
369 records ranges containing
370 all matching words. */
371 #if 0
372 /********************************************************************
373 Get the total number of words in a documents. */
374 static
375 ulint
376 fts_query_terms_in_document(
377 /*!< out: DB_SUCCESS if all go well
378 else error code */
379 fts_query_t* query, /*!< in: FTS query state */
380 doc_id_t doc_id, /*!< in: the word to check */
381 ulint* total); /*!< out: total words in document */
382
383 /*******************************************************************//**
384 Print the table used for calculating LCS. */
385 static
386 void
387 fts_print_lcs_table(
388 const ulint* table, /*!< in: array to print */
389 ulint n_rows, /*!< in: total no. of rows */
390 ulint n_cols) /*!< in: total no. of cols */
391 {
392 ulint i;
393
394 for (i = 0; i < n_rows; ++i) {
395 ulint j;
396
397 printf("\n");
398
399 for (j = 0; j < n_cols; ++j) {
400
401 printf("%2lu ", FTS_ELEM(table, n_cols, i, j));
402 }
403 }
404 }
405
406 /********************************************************************
407 Find the longest common subsequence between the query string and
408 the document. */
409 static
410 ulint
411 fts_query_lcs(
412 /*!< out: LCS (length) between
413 two ilists */
414 const ulint* p1, /*!< in: word positions of query */
415 ulint len_p1, /*!< in: no. of elements in p1 */
416 const ulint* p2, /*!< in: word positions within document */
417 ulint len_p2) /*!< in: no. of elements in p2 */
418 {
419 int i;
420 ulint len = 0;
421 ulint r = len_p1;
422 ulint c = len_p2;
423 ulint size = (r + 1) * (c + 1) * sizeof(ulint);
424 ulint* table = (ulint*) ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, size);
425
426 /* Traverse the table backwards, from the last row to the first and
427 also from the last column to the first. We compute the smaller
428 common subsequences first, then use the calculated values to determine
429 the longest common subsequence. The result will be in TABLE[0][0]. */
430 for (i = r; i >= 0; --i) {
431 int j;
432
433 for (j = c; j >= 0; --j) {
434
435 if (p1[i] == (ulint) -1 || p2[j] == (ulint) -1) {
436
437 FTS_ELEM(table, c, i, j) = 0;
438
439 } else if (p1[i] == p2[j]) {
440
441 FTS_ELEM(table, c, i, j) = FTS_ELEM(
442 table, c, i + 1, j + 1) + 1;
443
444 } else {
445
446 ulint value;
447
448 value = std::max(
449 FTS_ELEM(table, c, i + 1, j),
450 FTS_ELEM(table, c, i, j + 1));
451
452 FTS_ELEM(table, c, i, j) = value;
453 }
454 }
455 }
456
457 len = FTS_ELEM(table, c, 0, 0);
458
459 fts_print_lcs_table(table, r, c);
460 printf("\nLen=%lu\n", len);
461
462 ut::free(table);
463
464 return(len);
465 }
466 #endif
467
468 /** Compare two fts_ranking_t instance on their rank value and doc ids in
469 descending order on the rank and ascending order on doc id.
470 @return 0 if p1 == p2, < 0 if p1 < p2, > 0 if p1 > p2 */
471 static int fts_query_compare_rank(const void *p1, /*!< in: pointer to elem */
472 const void *p2) /*!< in: pointer to elem */
473 {
474 const fts_ranking_t *r1 = (const fts_ranking_t *)p1;
475 const fts_ranking_t *r2 = (const fts_ranking_t *)p2;
476
477 if (r2->rank < r1->rank) {
478 return (-1);
479 } else if (r2->rank == r1->rank) {
480 if (r1->doc_id < r2->doc_id) {
481 return (1);
482 } else if (r1->doc_id > r2->doc_id) {
483 return (1);
484 }
485
486 return (0);
487 }
488
489 return (1);
490 }
491
492 /** Create words in ranking */
493 static void fts_ranking_words_create(
494 fts_query_t *query, /*!< in: query instance */
495 fts_ranking_t *ranking) /*!< in: ranking instance */
496 {
497 ranking->words =
498 static_cast<byte *>(mem_heap_zalloc(query->heap, RANKING_WORDS_INIT_LEN));
499 ranking->words_len = RANKING_WORDS_INIT_LEN;
500 }
501
502 /*
503 The optimization here is using a char array(bitmap) to replace words rb tree
504 in fts_ranking_t.
505
506 It can save lots of memory except in some cases of QUERY EXPANSION.
507
508 'word_map' is used as a word dictionary, in which the key is a word, the value
509 is a number. In 'fts_ranking_words_add', we first check if the word is in
510 'word_map'. if not, we add it into 'word_map', and give it a position(actually a
511 number). then we set the corresponding bit to '1' at the position in the char
512 array 'words'.
513
514 'word_vector' is a useful backup of 'word_map', and we can get a word by its
515 position, more quickly than searching by value in 'word_map'. we use
516 'word_vector' in 'fts_query_calculate_ranking' and 'fts_expand_query'. In the
517 two functions, we need to scan the bitmap 'words', and get a word when a bit is
518 '1', then we get word_freq by the word.
519 */
520
521 /** Add a word into ranking */
522 static void fts_ranking_words_add(
523 fts_query_t *query, /*!< in: query instance */
524 fts_ranking_t *ranking, /*!< in: ranking instance */
525 const fts_string_t *word) /*!< in: term/word to add */
526 {
527 ulint pos;
528 ulint byte_offset;
529 ulint bit_offset;
530 ib_rbt_bound_t parent;
531
532 /* Note: we suppose the word map and vector are append-only. */
533 ut_ad(query->word_vector->size() == rbt_size(query->word_map));
534
535 /* We use ib_rbt to simulate a map, f_n_char means position. */
536 if (rbt_search(query->word_map, &parent, word) == 0) {
537 fts_string_t *result_word;
538
539 result_word = rbt_value(fts_string_t, parent.last);
540 pos = result_word->f_n_char;
541 ut_ad(pos < rbt_size(query->word_map));
542 } else {
543 /* Add the word to map. */
544 fts_string_t new_word;
545
546 pos = rbt_size(query->word_map);
547
548 fts_string_dup(&new_word, word, query->heap);
549 new_word.f_n_char = pos;
550
551 rbt_add_node(query->word_map, &parent, &new_word);
552 ut_ad(rbt_validate(query->word_map));
553 query->word_vector->push_back(new_word);
554 }
555
556 /* Check words len */
557 byte_offset = pos / CHAR_BIT;
558 if (byte_offset >= ranking->words_len) {
559 byte *words = ranking->words;
560 ulint words_len = ranking->words_len;
561
562 while (byte_offset >= words_len) {
563 words_len *= 2;
564 }
565
566 ranking->words =
567 static_cast<byte *>(mem_heap_zalloc(query->heap, words_len));
568 ut_memcpy(ranking->words, words, ranking->words_len);
569 ranking->words_len = words_len;
570 }
571
572 /* Set ranking words */
573 ut_ad(byte_offset < ranking->words_len);
574 bit_offset = pos % CHAR_BIT;
575 ranking->words[byte_offset] |= 1 << bit_offset;
576 }
577
578 /** Get a word from a ranking
579 @return true if it's successful */
580 static bool fts_ranking_words_get_next(
581 const fts_query_t *query, /*!< in: query instance */
582 fts_ranking_t *ranking, /*!< in: ranking instance */
583 ulint *pos, /*!< in/out: word start pos */
584 fts_string_t *word) /*!< in/out: term/word to add */
585 {
586 bool ret = false;
587 ulint max_pos = ranking->words_len * CHAR_BIT;
588
589 /* Search for next word */
590 while (*pos < max_pos) {
591 ulint byte_offset = *pos / CHAR_BIT;
592 ulint bit_offset = *pos % CHAR_BIT;
593
594 if (ranking->words[byte_offset] & (1 << bit_offset)) {
595 ret = true;
596 break;
597 }
598
599 *pos += 1;
600 };
601
602 /* Get next word from word vector */
603 if (ret) {
604 ut_ad(*pos < query->word_vector->size());
605 *word = query->word_vector->at((size_t)*pos);
606 *pos += 1;
607 }
608
609 return ret;
610 }
611
612 /** Add a word if it doesn't exist, to the term freq RB tree. We store
613 a pointer to the word that is passed in as the argument.
614 @return pointer to word */
615 static fts_word_freq_t *fts_query_add_word_freq(
616 fts_query_t *query, /*!< in: query instance */
617 const fts_string_t *word) /*!< in: term/word to add */
618 {
619 ib_rbt_bound_t parent;
620
621 /* Lookup the word in our rb tree and add if it doesn't exist. */
622 if (rbt_search(query->word_freqs, &parent, word) != 0) {
623 fts_word_freq_t word_freq;
624
625 memset(&word_freq, 0, sizeof(word_freq));
626
627 fts_string_dup(&word_freq.word, word, query->heap);
628
629 word_freq.doc_count = 0;
630
631 word_freq.doc_freqs = rbt_create(sizeof(fts_doc_freq_t),
632 fts_doc_id_field_cmp<fts_doc_freq_t>);
633
634 parent.last = rbt_add_node(query->word_freqs, &parent, &word_freq);
635
636 query->total_size += word->f_len + SIZEOF_RBT_CREATE + SIZEOF_RBT_NODE_ADD +
637 sizeof(fts_word_freq_t);
638 }
639
640 return (rbt_value(fts_word_freq_t, parent.last));
641 }
642
643 /** Add a doc id if it doesn't exist, to the doc freq RB tree.
644 @return pointer to word */
645 static fts_doc_freq_t *fts_query_add_doc_freq(
646 fts_query_t *query, /*!< in: query instance */
647 ib_rbt_t *doc_freqs, /*!< in: rb tree of fts_doc_freq_t */
648 doc_id_t doc_id) /*!< in: doc id to add */
649 {
650 ib_rbt_bound_t parent;
651
652 /* Lookup the doc id in our rb tree and add if it doesn't exist. */
653 if (rbt_search(doc_freqs, &parent, &doc_id) != 0) {
654 fts_doc_freq_t doc_freq;
655
656 memset(&doc_freq, 0, sizeof(doc_freq));
657
658 doc_freq.freq = 0;
659 doc_freq.doc_id = doc_id;
660
661 parent.last = rbt_add_node(doc_freqs, &parent, &doc_freq);
662
663 query->total_size += SIZEOF_RBT_NODE_ADD + sizeof(fts_doc_freq_t);
664 }
665
666 return (rbt_value(fts_doc_freq_t, parent.last));
667 }
668
669 /** Add the doc id to the query set only if it's not in the
670 deleted array. */
671 static void fts_query_union_doc_id(
672 fts_query_t *query, /*!< in: query instance */
673 doc_id_t doc_id, /*!< in: the doc id to add */
674 fts_rank_t rank) /*!< in: if non-zero, it is the
675 rank associated with the doc_id */
676 {
677 ib_rbt_bound_t parent;
678 ulint size = ib_vector_size(query->deleted->doc_ids);
679 fts_update_t *array = (fts_update_t *)query->deleted->doc_ids->data;
680
681 /* Check if the doc id is deleted and it's not already in our set. */
682 if (fts_bsearch(array, 0, static_cast<int>(size), doc_id) < 0 &&
683 rbt_search(query->doc_ids, &parent, &doc_id) != 0) {
684 fts_ranking_t ranking;
685
686 ranking.rank = rank;
687 ranking.doc_id = doc_id;
688 fts_ranking_words_create(query, &ranking);
689
690 rbt_add_node(query->doc_ids, &parent, &ranking);
691
692 query->total_size +=
693 SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t) + RANKING_WORDS_INIT_LEN;
694 }
695 }
696
697 /** Remove the doc id from the query set only if it's not in the
698 deleted set. */
699 static void fts_query_remove_doc_id(
700 fts_query_t *query, /*!< in: query instance */
701 doc_id_t doc_id) /*!< in: the doc id to add */
702 {
703 ib_rbt_bound_t parent;
704 ulint size = ib_vector_size(query->deleted->doc_ids);
705 fts_update_t *array = (fts_update_t *)query->deleted->doc_ids->data;
706
707 /* Check if the doc id is deleted and it's in our set. */
708 if (fts_bsearch(array, 0, static_cast<int>(size), doc_id) < 0 &&
709 rbt_search(query->doc_ids, &parent, &doc_id) == 0) {
710 ut::free(rbt_remove_node(query->doc_ids, parent.last));
711
712 ut_ad(query->total_size >= SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t));
713 query->total_size -= SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t);
714 }
715 }
716
717 /** Find the doc id in the query set but not in the deleted set, artificialy
718 downgrade or upgrade its ranking by a value and make/initialize its ranking
719 under or above its normal range 0 to 1. This is used for Boolean Search
720 operator such as Negation operator, which makes word's contribution to the
721 row's relevance to be negative */
722 static void fts_query_change_ranking(
723 fts_query_t *query, /*!< in: query instance */
724 doc_id_t doc_id, /*!< in: the doc id to add */
725 bool downgrade) /*!< in: Whether to downgrade ranking */
726 {
727 ib_rbt_bound_t parent;
728 ulint size = ib_vector_size(query->deleted->doc_ids);
729 fts_update_t *array = (fts_update_t *)query->deleted->doc_ids->data;
730
731 /* Check if the doc id is deleted and it's in our set. */
732 if (fts_bsearch(array, 0, static_cast<int>(size), doc_id) < 0 &&
733 rbt_search(query->doc_ids, &parent, &doc_id) == 0) {
734 fts_ranking_t *ranking;
735
736 ranking = rbt_value(fts_ranking_t, parent.last);
737
738 ranking->rank += downgrade ? RANK_DOWNGRADE : RANK_UPGRADE;
739
740 /* Allow at most 2 adjustment by RANK_DOWNGRADE (-0.5)
741 and RANK_UPGRADE (0.5) */
742 if (ranking->rank >= 1.0F) {
743 ranking->rank = 1.0F;
744 } else if (ranking->rank <= -1.0F) {
745 ranking->rank = -1.0F;
746 }
747 }
748 }
749
750 /** Check the doc id in the query set only if it's not in the
751 deleted array. The doc ids that were found are stored in
752 another rb tree (fts_query_t::intersect). */
753 static void fts_query_intersect_doc_id(
754 fts_query_t *query, /*!< in: query instance */
755 doc_id_t doc_id, /*!< in: the doc id to add */
756 fts_rank_t rank) /*!< in: if non-zero, it is the
757 rank associated with the doc_id */
758 {
759 ib_rbt_bound_t parent;
760 ulint size = ib_vector_size(query->deleted->doc_ids);
761 fts_update_t *array = (fts_update_t *)query->deleted->doc_ids->data;
762 fts_ranking_t *ranking = nullptr;
763
764 /* There are three types of intersect:
765 1. '+a': doc_ids is empty, add doc into intersect if it matches 'a'.
766 2. 'a +b': docs match 'a' is in doc_ids, add doc into intersect
767 if it matches 'b'. if the doc is also in doc_ids, then change the
768 doc's rank, and add 'a' in doc's words.
769 3. '+a +b': docs matching '+a' is in doc_ids, add doc into intsersect
770 if it matches 'b' and it's in doc_ids.(multi_exist = true). */
771
772 /* Check if the doc id is deleted and it's in our set */
773 if (fts_bsearch(array, 0, static_cast<int>(size), doc_id) < 0) {
774 fts_ranking_t new_ranking;
775
776 if (rbt_search(query->doc_ids, &parent, &doc_id) != 0) {
777 if (query->multi_exist) {
778 return;
779 } else {
780 new_ranking.words = nullptr;
781 }
782 } else {
783 ranking = rbt_value(fts_ranking_t, parent.last);
784
785 /* We've just checked the doc id before */
786 if (ranking->words == nullptr) {
787 ut_ad(rbt_search(query->intersection, &parent, ranking) == 0);
788 return;
789 }
790
791 /* Merge rank */
792 rank += ranking->rank;
793 if (rank >= 1.0F) {
794 rank = 1.0F;
795 } else if (rank <= -1.0F) {
796 rank = -1.0F;
797 }
798
799 /* Take words */
800 new_ranking.words = ranking->words;
801 new_ranking.words_len = ranking->words_len;
802 }
803
804 new_ranking.rank = rank;
805 new_ranking.doc_id = doc_id;
806
807 if (rbt_search(query->intersection, &parent, &new_ranking) != 0) {
808 if (new_ranking.words == nullptr) {
809 fts_ranking_words_create(query, &new_ranking);
810
811 query->total_size += RANKING_WORDS_INIT_LEN;
812 } else {
813 /* Note that the intersection has taken
814 ownership of the ranking data. */
815 ranking->words = nullptr;
816 }
817
818 rbt_add_node(query->intersection, &parent, &new_ranking);
819
820 query->total_size += SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t);
821 }
822 }
823 }
824
825 /** Free the document ranking rb tree. */
826 static void fts_query_free_doc_ids(
827 fts_query_t *query, /*!< in: query instance */
828 ib_rbt_t *doc_ids) /*!< in: rb tree to free */
829 {
830 const ib_rbt_node_t *node;
831
832 for (node = rbt_first(doc_ids); node; node = rbt_first(doc_ids)) {
833 fts_ranking_t *ranking;
834
835 ranking = rbt_value(fts_ranking_t, node);
836
837 if (ranking->words) {
838 ranking->words = nullptr;
839 }
840
841 ut::free(rbt_remove_node(doc_ids, node));
842
843 ut_ad(query->total_size >= SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t));
844 query->total_size -= SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t);
845 }
846
847 rbt_free(doc_ids);
848
849 ut_ad(query->total_size >= SIZEOF_RBT_CREATE);
850 query->total_size -= SIZEOF_RBT_CREATE;
851 }
852
853 /** Add the word to the documents "list" of matching words from
854 the query. We make a copy of the word from the query heap. */
855 static void fts_query_add_word_to_document(
856 fts_query_t *query, /*!< in: query to update */
857 doc_id_t doc_id, /*!< in: the document to update */
858 const fts_string_t *word) /*!< in: the token to add */
859 {
860 ib_rbt_bound_t parent;
861 fts_ranking_t *ranking = nullptr;
862
863 if (query->flags == FTS_OPT_RANKING) {
864 return;
865 }
866
867 /* First we search the intersection RB tree as it could have
868 taken ownership of the words rb tree instance. */
869 if (query->intersection &&
870 rbt_search(query->intersection, &parent, &doc_id) == 0) {
871 ranking = rbt_value(fts_ranking_t, parent.last);
872 }
873
874 if (ranking == nullptr && rbt_search(query->doc_ids, &parent, &doc_id) == 0) {
875 ranking = rbt_value(fts_ranking_t, parent.last);
876 }
877
878 if (ranking != nullptr) {
879 fts_ranking_words_add(query, ranking, word);
880 }
881 }
882
883 /** Check the node ilist. */
884 static void fts_query_check_node(
885 fts_query_t *query, /*!< in: query to update */
886 const fts_string_t *token, /*!< in: the token to search */
887 const fts_node_t *node) /*!< in: node to check */
888 {
889 /* Skip nodes whose doc ids are out range. */
890 if (query->oper == FTS_EXIST &&
891 ((query->upper_doc_id > 0 && node->first_doc_id > query->upper_doc_id) ||
892 (query->lower_doc_id > 0 && node->last_doc_id < query->lower_doc_id))) {
893 /* Ignore */
894
895 } else {
896 int ret;
897 ib_rbt_bound_t parent;
898 ulint ilist_size = node->ilist_size;
899 fts_word_freq_t *word_freqs;
900
901 /* The word must exist. */
902 ret = rbt_search(query->word_freqs, &parent, token);
903 ut_a(ret == 0);
904
905 word_freqs = rbt_value(fts_word_freq_t, parent.last);
906
907 query->error = fts_query_filter_doc_ids(query, token, word_freqs, node,
908 node->ilist, ilist_size, true);
909 }
910 }
911
912 /** Search index cache for word with wildcard match.
913 @return number of words matched */
914 static ulint fts_cache_find_wildcard(
915 fts_query_t *query, /*!< in: query instance */
916 const fts_index_cache_t *index_cache, /*!< in: cache to search */
917 const fts_string_t *token) /*!< in: token to search */
918 {
919 ib_rbt_bound_t parent;
920 const ib_vector_t *nodes = nullptr;
921 fts_string_t srch_text;
922 byte term[FTS_MAX_WORD_LEN + 1];
923 ulint num_word = 0;
924
925 srch_text.f_len =
926 (token->f_str[token->f_len - 1] == '%') ? token->f_len - 1 : token->f_len;
927
928 strncpy((char *)term, (char *)token->f_str, srch_text.f_len);
929 term[srch_text.f_len] = '\0';
930 srch_text.f_str = term;
931
932 /* Lookup the word in the rb tree */
933 if (rbt_search_cmp(index_cache->words, &parent, &srch_text, nullptr,
934 innobase_fts_text_cmp_prefix) == 0) {
935 const fts_tokenizer_word_t *word;
936 ulint i;
937 const ib_rbt_node_t *cur_node;
938 bool forward = false;
939
940 word = rbt_value(fts_tokenizer_word_t, parent.last);
941 cur_node = parent.last;
942
943 while (innobase_fts_text_cmp_prefix(index_cache->charset, &srch_text,
944 &word->text) == 0) {
945 nodes = word->nodes;
946
947 for (i = 0; nodes && i < ib_vector_size(nodes); ++i) {
948 int ret;
949 const fts_node_t *node;
950 ib_rbt_bound_t freq_parent;
951 fts_word_freq_t *word_freqs;
952
953 node = static_cast<const fts_node_t *>(ib_vector_get_const(nodes, i));
954
955 ret = rbt_search(query->word_freqs, &freq_parent, &srch_text);
956
957 ut_a(ret == 0);
958
959 word_freqs = rbt_value(fts_word_freq_t, freq_parent.last);
960
961 query->error =
962 fts_query_filter_doc_ids(query, &srch_text, word_freqs, node,
963 node->ilist, node->ilist_size, true);
964
965 if (query->error != DB_SUCCESS) {
966 return (0);
967 }
968 }
969
970 num_word++;
971
972 if (!forward) {
973 cur_node = rbt_prev(index_cache->words, cur_node);
974 } else {
975 cont_search:
976 cur_node = rbt_next(index_cache->words, cur_node);
977 }
978
979 if (!cur_node) {
980 break;
981 }
982
983 word = rbt_value(fts_tokenizer_word_t, cur_node);
984 }
985
986 if (!forward) {
987 forward = true;
988 cur_node = parent.last;
989 goto cont_search;
990 }
991 }
992
993 return (num_word);
994 }
995
996 /** Set difference.
997 @return DB_SUCCESS if all go well */
998 [[nodiscard]] static dberr_t fts_query_difference(
999 fts_query_t *query, /*!< in: query instance */
1000 const fts_string_t *token) /*!< in: token to search */
1001 {
1002 ulint n_doc_ids = 0;
1003 trx_t *trx = query->trx;
1004 dict_table_t *table = query->index->table;
1005
1006 ut_a(query->oper == FTS_IGNORE);
1007
1008 #ifdef FTS_INTERNAL_DIAG_PRINT
1009 {
1010 ib::info out(ER_IB_MSG_1221);
1011 out << "DIFFERENCE: Searching: '";
1012 out.write(token->f_str, token->f_len);
1013 out << "'";
1014 }
1015 #endif
1016
1017 if (query->doc_ids) {
1018 n_doc_ids = rbt_size(query->doc_ids);
1019 }
1020
1021 /* There is nothing we can subtract from an empty set. */
1022 if (query->doc_ids && !rbt_empty(query->doc_ids)) {
1023 ulint i;
1024 fts_fetch_t fetch;
1025 const ib_vector_t *nodes;
1026 const fts_index_cache_t *index_cache;
1027 que_t *graph = nullptr;
1028 fts_cache_t *cache = table->fts->cache;
1029 dberr_t error;
1030
1031 rw_lock_x_lock(&cache->lock, UT_LOCATION_HERE);
1032
1033 index_cache = fts_find_index_cache(cache, query->index);
1034
1035 /* Must find the index cache */
1036 ut_a(index_cache != nullptr);
1037
1038 /* Search the cache for a matching word first. */
1039 if (query->cur_node->term.wildcard && query->flags != FTS_PROXIMITY &&
1040 query->flags != FTS_PHRASE) {
1041 fts_cache_find_wildcard(query, index_cache, token);
1042 } else {
1043 nodes = fts_cache_find_word(index_cache, token);
1044
1045 for (i = 0;
1046 nodes && i < ib_vector_size(nodes) && query->error == DB_SUCCESS;
1047 ++i) {
1048 const fts_node_t *node;
1049
1050 node = static_cast<const fts_node_t *>(ib_vector_get_const(nodes, i));
1051
1052 fts_query_check_node(query, token, node);
1053 }
1054 }
1055
1056 rw_lock_x_unlock(&cache->lock);
1057
1058 /* error is passed by 'query->error' */
1059 if (query->error != DB_SUCCESS) {
1060 ut_ad(query->error == DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
1061 return (query->error);
1062 }
1063
1064 /* Setup the callback args for filtering and
1065 consolidating the ilist. */
1066 fetch.read_arg = query;
1067 fetch.read_record = fts_query_index_fetch_nodes;
1068
1069 error = fts_index_fetch_nodes(trx, &graph, &query->fts_index_table, token,
1070 &fetch);
1071
1072 /* DB_FTS_EXCEED_RESULT_CACHE_LIMIT passed by 'query->error' */
1073 ut_ad(!(query->error != DB_SUCCESS && error != DB_SUCCESS));
1074 if (error != DB_SUCCESS) {
1075 query->error = error;
1076 }
1077
1078 fts_que_graph_free(graph);
1079 }
1080
1081 /* The size can't increase. */
1082 ut_a(rbt_size(query->doc_ids) <= n_doc_ids);
1083
1084 return (query->error);
1085 }
1086
1087 /** Intersect the token doc ids with the current set.
1088 @return DB_SUCCESS if all go well */
1089 [[nodiscard]] static dberr_t fts_query_intersect(
1090 fts_query_t *query, /*!< in: query instance */
1091 const fts_string_t *token) /*!< in: the token to search */
1092 {
1093 trx_t *trx = query->trx;
1094 dict_table_t *table = query->index->table;
1095
1096 ut_a(query->oper == FTS_EXIST);
1097
1098 #ifdef FTS_INTERNAL_DIAG_PRINT
1099 {
1100 ib::info out(ER_IB_MSG_1222);
1101 out << "INTERSECT: Searching: '";
1102 out.write(token->f_str, token->f_len);
1103 out << "'";
1104 }
1105 #endif
1106
1107 /* If the words set is not empty and multi exist is true,
1108 we know the intersection set is empty in advance. */
1109 if (!(rbt_empty(query->doc_ids) && query->multi_exist)) {
1110 ulint n_doc_ids = 0;
1111 ulint i;
1112 fts_fetch_t fetch;
1113 const ib_vector_t *nodes;
1114 const fts_index_cache_t *index_cache;
1115 que_t *graph = nullptr;
1116 fts_cache_t *cache = table->fts->cache;
1117 dberr_t error;
1118
1119 ut_a(!query->intersection);
1120
1121 n_doc_ids = rbt_size(query->doc_ids);
1122
1123 /* Create the rb tree that will hold the doc ids of
1124 the intersection. */
1125 query->intersection =
1126 rbt_create(sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
1127
1128 query->total_size += SIZEOF_RBT_CREATE;
1129
1130 /* This is to avoid decompressing the ilist if the
1131 node's ilist doc ids are out of range. */
1132 if (!rbt_empty(query->doc_ids) && query->multi_exist) {
1133 const ib_rbt_node_t *node;
1134 doc_id_t *doc_id;
1135
1136 node = rbt_first(query->doc_ids);
1137 doc_id = rbt_value(doc_id_t, node);
1138 query->lower_doc_id = *doc_id;
1139
1140 node = rbt_last(query->doc_ids);
1141 doc_id = rbt_value(doc_id_t, node);
1142 query->upper_doc_id = *doc_id;
1143
1144 } else {
1145 query->lower_doc_id = 0;
1146 query->upper_doc_id = 0;
1147 }
1148
1149 /* Search the cache for a matching word first. */
1150
1151 rw_lock_x_lock(&cache->lock, UT_LOCATION_HERE);
1152
1153 /* Search for the index specific cache. */
1154 index_cache = fts_find_index_cache(cache, query->index);
1155
1156 /* Must find the index cache. */
1157 ut_a(index_cache != nullptr);
1158
1159 if (query->cur_node->term.wildcard) {
1160 /* Wildcard search the index cache */
1161 fts_cache_find_wildcard(query, index_cache, token);
1162 } else {
1163 nodes = fts_cache_find_word(index_cache, token);
1164
1165 for (i = 0;
1166 nodes && i < ib_vector_size(nodes) && query->error == DB_SUCCESS;
1167 ++i) {
1168 const fts_node_t *node;
1169
1170 node = static_cast<const fts_node_t *>(ib_vector_get_const(nodes, i));
1171
1172 fts_query_check_node(query, token, node);
1173 }
1174 }
1175
1176 rw_lock_x_unlock(&cache->lock);
1177
1178 /* error is passed by 'query->error' */
1179 if (query->error != DB_SUCCESS) {
1180 ut_ad(query->error == DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
1181 return (query->error);
1182 }
1183
1184 /* Setup the callback args for filtering and
1185 consolidating the ilist. */
1186 fetch.read_arg = query;
1187 fetch.read_record = fts_query_index_fetch_nodes;
1188
1189 error = fts_index_fetch_nodes(trx, &graph, &query->fts_index_table, token,
1190 &fetch);
1191
1192 /* DB_FTS_EXCEED_RESULT_CACHE_LIMIT passed by 'query->error' */
1193 ut_ad(!(query->error != DB_SUCCESS && error != DB_SUCCESS));
1194 if (error != DB_SUCCESS) {
1195 query->error = error;
1196 }
1197
1198 fts_que_graph_free(graph);
1199
1200 if (query->error == DB_SUCCESS) {
1201 /* Make the intesection (rb tree) the current doc id
1202 set and free the old set. */
1203 fts_query_free_doc_ids(query, query->doc_ids);
1204 query->doc_ids = query->intersection;
1205 query->intersection = nullptr;
1206
1207 ut_a(!query->multi_exist ||
1208 (query->multi_exist && rbt_size(query->doc_ids) <= n_doc_ids));
1209 }
1210 }
1211
1212 return (query->error);
1213 }
1214
1215 /** Query index cache.
1216 @return DB_SUCCESS if all go well */
1217 static dberr_t fts_query_cache(
1218 fts_query_t *query, /*!< in/out: query instance */
1219 const fts_string_t *token) /*!< in: token to search */
1220 {
1221 const fts_index_cache_t *index_cache;
1222 dict_table_t *table = query->index->table;
1223 fts_cache_t *cache = table->fts->cache;
1224
1225 /* Search the cache for a matching word first. */
1226 rw_lock_x_lock(&cache->lock, UT_LOCATION_HERE);
1227
1228 /* Search for the index specific cache. */
1229 index_cache = fts_find_index_cache(cache, query->index);
1230
1231 /* Must find the index cache. */
1232 ut_a(index_cache != nullptr);
1233
1234 if (query->cur_node->term.wildcard && query->flags != FTS_PROXIMITY &&
1235 query->flags != FTS_PHRASE) {
1236 /* Wildcard search the index cache */
1237 fts_cache_find_wildcard(query, index_cache, token);
1238 } else {
1239 const ib_vector_t *nodes;
1240 ulint i;
1241
1242 nodes = fts_cache_find_word(index_cache, token);
1243
1244 for (i = 0;
1245 nodes && i < ib_vector_size(nodes) && query->error == DB_SUCCESS;
1246 ++i) {
1247 const fts_node_t *node;
1248
1249 node = static_cast<const fts_node_t *>(ib_vector_get_const(nodes, i));
1250
1251 fts_query_check_node(query, token, node);
1252 }
1253 }
1254
1255 rw_lock_x_unlock(&cache->lock);
1256
1257 return (query->error);
1258 }
1259
1260 /** Set union.
1261 @return DB_SUCCESS if all go well */
1262 [[nodiscard]] static dberr_t fts_query_union(
1263 fts_query_t *query, /*!< in: query instance */
1264 fts_string_t *token) /*!< in: token to search */
1265 {
1266 fts_fetch_t fetch;
1267 ulint n_doc_ids = 0;
1268 trx_t *trx = query->trx;
1269 que_t *graph = nullptr;
1270 dberr_t error;
1271
1272 ut_a(query->oper == FTS_NONE || query->oper == FTS_DECR_RATING ||
1273 query->oper == FTS_NEGATE || query->oper == FTS_INCR_RATING);
1274
1275 #ifdef FTS_INTERNAL_DIAG_PRINT
1276 {
1277 ib::info out(ER_IB_MSG_1223);
1278 out << "UNION: Searching: '";
1279 out.write(token->f_str, token->f_len);
1280 out << "'";
1281 }
1282 #endif
1283
1284 if (query->doc_ids) {
1285 n_doc_ids = rbt_size(query->doc_ids);
1286 }
1287
1288 if (token->f_len == 0) {
1289 return (query->error);
1290 }
1291
1292 fts_query_cache(query, token);
1293
1294 /* Setup the callback args for filtering and
1295 consolidating the ilist. */
1296 fetch.read_arg = query;
1297 fetch.read_record = fts_query_index_fetch_nodes;
1298
1299 /* Read the nodes from disk. */
1300 error = fts_index_fetch_nodes(trx, &graph, &query->fts_index_table, token,
1301 &fetch);
1302
1303 /* DB_FTS_EXCEED_RESULT_CACHE_LIMIT passed by 'query->error' */
1304 ut_ad(!(query->error != DB_SUCCESS && error != DB_SUCCESS));
1305 if (error != DB_SUCCESS) {
1306 query->error = error;
1307 }
1308
1309 fts_que_graph_free(graph);
1310
1311 if (query->error == DB_SUCCESS) {
1312 /* The size can't decrease. */
1313 ut_a(rbt_size(query->doc_ids) >= n_doc_ids);
1314
1315 /* Calculate the number of doc ids that were added to
1316 the current doc id set. */
1317 if (query->doc_ids) {
1318 n_doc_ids = rbt_size(query->doc_ids) - n_doc_ids;
1319 }
1320 }
1321
1322 return (query->error);
1323 }
1324
1325 /** Depending upon the current query operator process the doc id.
1326 return DB_SUCCESS if all go well
1327 or return DB_FTS_EXCEED_RESULT_CACHE_LIMIT */
1328 static dberr_t fts_query_process_doc_id(
1329 fts_query_t *query, /*!< in: query instance */
1330 doc_id_t doc_id, /*!< in: doc id to process */
1331 fts_rank_t rank) /*!< in: if non-zero, it is the
1332 rank associated with the doc_id */
1333 {
1334 if (query->flags == FTS_OPT_RANKING) {
1335 return (DB_SUCCESS);
1336 }
1337
1338 switch (query->oper) {
1339 case FTS_NONE:
1340 fts_query_union_doc_id(query, doc_id, rank);
1341 break;
1342
1343 case FTS_EXIST:
1344 fts_query_intersect_doc_id(query, doc_id, rank);
1345 break;
1346
1347 case FTS_IGNORE:
1348 fts_query_remove_doc_id(query, doc_id);
1349 break;
1350
1351 case FTS_NEGATE:
1352 fts_query_change_ranking(query, doc_id, true);
1353 break;
1354
1355 case FTS_DECR_RATING:
1356 fts_query_union_doc_id(query, doc_id, rank);
1357 fts_query_change_ranking(query, doc_id, true);
1358 break;
1359
1360 case FTS_INCR_RATING:
1361 fts_query_union_doc_id(query, doc_id, rank);
1362 fts_query_change_ranking(query, doc_id, false);
1363 break;
1364
1365 default:
1366 ut_error;
1367 }
1368
1369 if (query->total_size > fts_result_cache_limit) {
1370 return (DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
1371 } else {
1372 return (DB_SUCCESS);
1373 }
1374 }
1375
1376 /** Merge two result sets. */
1377 static dberr_t fts_merge_doc_ids(
1378 fts_query_t *query, /*!< in,out: query instance */
1379 const ib_rbt_t *doc_ids) /*!< in: result set to merge */
1380 {
1381 const ib_rbt_node_t *node;
1382
1383 DBUG_TRACE;
1384
1385 ut_a(!query->intersection);
1386
1387 /* To process FTS_EXIST operation (intersection), we need
1388 to create a new result set for fts_query_intersect(). */
1389 if (query->oper == FTS_EXIST) {
1390 query->intersection =
1391 rbt_create(sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
1392
1393 query->total_size += SIZEOF_RBT_CREATE;
1394 }
1395
1396 /* Merge the elements to the result set. */
1397 for (node = rbt_first(doc_ids); node; node = rbt_next(doc_ids, node)) {
1398 fts_ranking_t *ranking;
1399 ulint pos = 0;
1400 fts_string_t word;
1401
1402 ranking = rbt_value(fts_ranking_t, node);
1403
1404 query->error =
1405 fts_query_process_doc_id(query, ranking->doc_id, ranking->rank);
1406
1407 if (query->error != DB_SUCCESS) {
1408 return query->error;
1409 }
1410
1411 /* Merge words. Don't need to take operator into account. */
1412 ut_a(ranking->words);
1413 while (fts_ranking_words_get_next(query, ranking, &pos, &word)) {
1414 fts_query_add_word_to_document(query, ranking->doc_id, &word);
1415 }
1416 }
1417
1418 /* If it is an intersection operation, reset query->doc_ids
1419 to query->intersection and free the old result list. */
1420 if (query->oper == FTS_EXIST && query->intersection != nullptr) {
1421 fts_query_free_doc_ids(query, query->doc_ids);
1422 query->doc_ids = query->intersection;
1423 query->intersection = nullptr;
1424 }
1425
1426 return DB_SUCCESS;
1427 }
1428
1429 /** Skip non-whitespace in a string. Move ptr to the next word boundary.
1430 @return pointer to first whitespace character or end */
1431 static inline byte *fts_query_skip_word(
1432 byte *ptr, /*!< in: start of scan */
1433 const byte *end) /*!< in: pointer to end of string */
1434 {
1435 /* TODO: Does this have to be UTF-8 too ? */
1436 while (ptr < end && !(ispunct(*ptr) || isspace(*ptr))) {
1437 ++ptr;
1438 }
1439
1440 return (ptr);
1441 }
1442
1443 /** Check whether the remaining terms in the phrase match the text.
1444 @return true if matched else false */
1445 static bool fts_query_match_phrase_terms(
1446 fts_phrase_t *phrase, /*!< in: phrase to match */
1447 byte **start, /*!< in/out: text to search, we can't
1448 make this const because we need to
1449 first convert the string to
1450 lowercase */
1451 const byte *end, /*!< in: pointer to the end of
1452 the string to search */
1453 mem_heap_t *heap) /*!< in: heap */
1454 {
1455 ulint i;
1456 byte *ptr = *start;
1457 const ib_vector_t *tokens = phrase->tokens;
1458 ulint distance = phrase->distance;
1459
1460 /* We check only from the second term onwards, since the first
1461 must have matched otherwise we wouldn't be here. */
1462 for (i = 1; ptr < end && i < ib_vector_size(tokens); /* No op */) {
1463 fts_string_t match;
1464 fts_string_t cmp_str;
1465 const fts_string_t *token;
1466 int result;
1467 ulint ret;
1468
1469 ret = innobase_mysql_fts_get_token(phrase->charset, ptr,
1470 const_cast<byte *>(end), &match);
1471
1472 if (match.f_len > 0) {
1473 /* Get next token to match. */
1474 token = static_cast<const fts_string_t *>(ib_vector_get_const(tokens, i));
1475
1476 fts_string_dup(&cmp_str, &match, heap);
1477
1478 result = innobase_fts_nocase_compare(phrase->charset, token, &cmp_str);
1479
1480 /* Skip the rest of the tokens if this one doesn't
1481 match and the proximity distance is exceeded. */
1482 if (result && (distance == ULINT_UNDEFINED || distance == 0)) {
1483 break;
1484 }
1485
1486 /* This token matched move to the next token. */
1487 if (result == 0) {
1488 /* Advance the text to search by the length
1489 of the last token. */
1490 ptr += ret;
1491
1492 /* Advance to the next token. */
1493 ++i;
1494 } else {
1495 ut_a(distance != ULINT_UNDEFINED);
1496
1497 ptr = fts_query_skip_word(ptr, end);
1498 }
1499
1500 /* Distance can be 0 for exact matches. */
1501 if (distance != ULINT_UNDEFINED && distance > 0) {
1502 --distance;
1503 }
1504 } else {
1505 ptr += ret;
1506 }
1507 }
1508
1509 *start = ptr;
1510
1511 /* Can't be greater than the number of elements. */
1512 ut_a(i <= ib_vector_size(tokens));
1513
1514 /* This is the case for multiple words. */
1515 if (i == ib_vector_size(tokens)) {
1516 phrase->found = true;
1517 }
1518
1519 return (phrase->found);
1520 }
1521
1522 /** Callback function to count the number of words in position ranges,
1523 and see whether the word count is in specified "phrase->distance"
1524 @return true if the number of characters is less than the "distance" */
1525 static bool fts_proximity_is_word_in_range(
1526 const fts_phrase_t *phrase, /*!< in: phrase with the search info */
1527 byte *start, /*!< in: text to search */
1528 ulint total_len) /*!< in: length of text */
1529 {
1530 fts_proximity_t *proximity_pos = phrase->proximity_pos;
1531
1532 ut_ad(proximity_pos->n_pos == proximity_pos->min_pos.size());
1533 ut_ad(proximity_pos->n_pos == proximity_pos->max_pos.size());
1534
1535 /* Search each matched position pair (with min and max positions)
1536 and count the number of words in the range */
1537 for (ulint i = 0; i < proximity_pos->n_pos; i++) {
1538 ulint cur_pos = proximity_pos->min_pos[i];
1539 ulint n_word = 0;
1540
1541 ut_ad(proximity_pos->max_pos[i] <= total_len);
1542
1543 /* Walk through words in the range and count them */
1544 while (cur_pos <= proximity_pos->max_pos[i]) {
1545 ulint len;
1546 fts_string_t str;
1547
1548 len = innobase_mysql_fts_get_token(phrase->charset, start + cur_pos,
1549 start + total_len, &str);
1550
1551 if (len == 0) {
1552 break;
1553 }
1554
1555 /* Advances position with "len" bytes */
1556 cur_pos += len;
1557
1558 /* Record the number of words */
1559 if (str.f_n_char > 0) {
1560 n_word++;
1561 }
1562
1563 if (n_word > phrase->distance) {
1564 break;
1565 }
1566 }
1567
1568 /* Check if the number of words is less than specified
1569 "distance" */
1570 if (n_word && n_word <= phrase->distance) {
1571 return (true);
1572 }
1573 }
1574
1575 return (false);
1576 }
1577
1578 /** FTS plugin parser 'myql_add_word' callback function for phrase match
1579 Refer to 'MYSQL_FTPARSER_PARAM' for more detail.
1580 @return 0 if match, or return non-zero */
1581 static int fts_query_match_phrase_add_word_for_parser(
1582 MYSQL_FTPARSER_PARAM *param, /*!< in: parser param */
1583 char *word, /*!< in: token */
1584 int word_len, /*!< in: token length */
1585 MYSQL_FTPARSER_BOOLEAN_INFO *info [[maybe_unused]]) /*!< in: token info */
1586 {
1587 fts_phrase_param_t *phrase_param;
1588 fts_phrase_t *phrase;
1589 const ib_vector_t *tokens;
1590 fts_string_t match;
1591 fts_string_t cmp_str;
1592 const fts_string_t *token;
1593 int result;
1594 mem_heap_t *heap;
1595
1596 phrase_param = static_cast<fts_phrase_param_t *>(param->mysql_ftparam);
1597 heap = phrase_param->heap;
1598 phrase = phrase_param->phrase;
1599 tokens = phrase->tokens;
1600
1601 /* In case plugin parser doesn't check return value */
1602 if (phrase_param->token_index == ib_vector_size(tokens)) {
1603 return (1);
1604 }
1605
1606 match.f_str = reinterpret_cast<byte *>(word);
1607 match.f_len = word_len;
1608 match.f_n_char = fts_get_token_size(phrase->charset, word, word_len);
1609
1610 if (match.f_len > 0) {
1611 /* Get next token to match. */
1612 ut_a(phrase_param->token_index < ib_vector_size(tokens));
1613 token = static_cast<const fts_string_t *>(
1614 ib_vector_get_const(tokens, phrase_param->token_index));
1615
1616 fts_string_dup(&cmp_str, &match, heap);
1617
1618 result = innobase_fts_nocase_compare(phrase->charset, token, &cmp_str);
1619
1620 if (result == 0) {
1621 phrase_param->token_index++;
1622 } else {
1623 return (1);
1624 }
1625 }
1626
1627 /* Can't be greater than the number of elements. */
1628 ut_a(phrase_param->token_index <= ib_vector_size(tokens));
1629
1630 /* This is the case for multiple words. */
1631 if (phrase_param->token_index == ib_vector_size(tokens)) {
1632 phrase->found = true;
1633 }
1634
1635 return (static_cast<int>(phrase->found));
1636 }
1637
1638 /** Check whether the terms in the phrase match the text.
1639 @return true if matched else false */
1640 static bool fts_query_match_phrase_terms_by_parser(
1641 fts_phrase_param_t *phrase_param, /* in/out: phrase param */
1642 st_mysql_ftparser *parser, /* in: plugin fts parser */
1643 byte *text, /* in: text to check */
1644 ulint len) /* in: text length */
1645 {
1646 MYSQL_FTPARSER_PARAM param;
1647
1648 ut_a(parser);
1649
1650 /* Set parameters for param */
1651 param.mysql_parse = fts_tokenize_document_internal;
1652 param.mysql_add_word = fts_query_match_phrase_add_word_for_parser;
1653 param.mysql_ftparam = phrase_param;
1654 param.cs = phrase_param->phrase->charset;
1655 param.doc = reinterpret_cast<char *>(text);
1656 param.length = static_cast<int>(len);
1657 param.mode = MYSQL_FTPARSER_WITH_STOPWORDS;
1658
1659 PARSER_INIT(parser, &param);
1660 parser->parse(&param);
1661 PARSER_DEINIT(parser, &param);
1662
1663 return (phrase_param->phrase->found);
1664 }
1665
1666 /** Callback function to fetch and search the document.
1667 @param[in] phrase phrase to match
1668 @param[in] start text to search, we can't make this const because
1669 we need to first convert the string to
1670 lowercase
1671 @param[in] cur_len length of text
1672 @param[in] prev_len total length for searched doc fields
1673 @param[in] heap heap
1674 @return true if matched else false */
1675 static bool fts_query_match_phrase(fts_phrase_t *phrase, byte *start,
1676 ulint cur_len, ulint prev_len,
1677 mem_heap_t *heap) {
1678 ulint i;
1679 const fts_string_t *first;
1680 const byte *end = start + cur_len;
1681 const ib_vector_t *tokens = phrase->tokens;
1682 const ib_vector_t *positions = phrase->match->positions;
1683
1684 ut_a(!phrase->found);
1685 ut_a(phrase->match->doc_id > 0);
1686 ut_a(ib_vector_size(tokens) > 0);
1687 ut_a(ib_vector_size(positions) > 0);
1688
1689 first = static_cast<const fts_string_t *>(ib_vector_get_const(tokens, 0));
1690
1691 ut_a(phrase->match->start < ib_vector_size(positions));
1692
1693 for (i = phrase->match->start; i < ib_vector_size(positions); ++i) {
1694 ulint pos;
1695 byte *ptr = start;
1696
1697 pos = *(ulint *)ib_vector_get_const(positions, i);
1698
1699 if (pos == ULINT_UNDEFINED) {
1700 break;
1701 }
1702
1703 if (pos < prev_len) {
1704 continue;
1705 }
1706
1707 /* Document positions are calculated from the beginning
1708 of the first field, need to save the length for each
1709 searched field to adjust the doc position when search
1710 phrases. */
1711 pos -= prev_len;
1712 ptr = start + pos;
1713
1714 /* Within limits ? */
1715 if (ptr >= end) {
1716 break;
1717 }
1718
1719 if (phrase->parser) {
1720 fts_phrase_param_t phrase_param;
1721
1722 phrase_param.phrase = phrase;
1723 phrase_param.token_index = 0;
1724 phrase_param.heap = heap;
1725
1726 if (fts_query_match_phrase_terms_by_parser(&phrase_param, phrase->parser,
1727 ptr, (end - ptr))) {
1728 break;
1729 }
1730 } else {
1731 fts_string_t match;
1732 fts_string_t cmp_str;
1733 ulint ret;
1734
1735 match.f_str = ptr;
1736 ret = innobase_mysql_fts_get_token(phrase->charset, start + pos,
1737 const_cast<byte *>(end), &match);
1738
1739 if (match.f_len == 0) {
1740 break;
1741 }
1742
1743 fts_string_dup(&cmp_str, &match, heap);
1744
1745 if (innobase_fts_nocase_compare(phrase->charset, first, &cmp_str) == 0) {
1746 /* This is the case for the single word
1747 in the phrase. */
1748 if (ib_vector_size(phrase->tokens) == 1) {
1749 phrase->found = true;
1750 break;
1751 }
1752
1753 ptr += ret;
1754
1755 /* Match the remaining terms in the phrase. */
1756 if (fts_query_match_phrase_terms(phrase, &ptr, end, heap)) {
1757 break;
1758 }
1759 }
1760 }
1761 }
1762
1763 return (phrase->found);
1764 }
1765
1766 /** Callback function to fetch and search the document.
1767 @return whether the phrase is found */
1768 static bool fts_query_fetch_document(void *row, /*!< in: sel_node_t* */
1769 void *user_arg) /*!< in: fts_doc_t* */
1770 {
1771 que_node_t *exp;
1772 sel_node_t *node = static_cast<sel_node_t *>(row);
1773 fts_phrase_t *phrase = static_cast<fts_phrase_t *>(user_arg);
1774 ulint prev_len = 0;
1775 ulint total_len = 0;
1776 byte *document_text = nullptr;
1777
1778 exp = node->select_list;
1779
1780 phrase->found = false;
1781
1782 /* For proximity search, we will need to get the whole document
1783 from all fields, so first count the total length of the document
1784 from all the fields */
1785 if (phrase->proximity_pos) {
1786 while (exp) {
1787 ulint field_len;
1788 dfield_t *dfield = que_node_get_val(exp);
1789 byte *data = static_cast<byte *>(dfield_get_data(dfield));
1790
1791 if (dfield_is_ext(dfield)) {
1792 ulint local_len = dfield_get_len(dfield);
1793
1794 local_len -= BTR_EXTERN_FIELD_REF_SIZE;
1795
1796 field_len =
1797 mach_read_from_4(data + local_len + lob::BTR_EXTERN_LEN + 4);
1798 } else {
1799 field_len = dfield_get_len(dfield);
1800 }
1801
1802 if (field_len != UNIV_SQL_NULL) {
1803 total_len += field_len + 1;
1804 }
1805
1806 exp = que_node_get_next(exp);
1807 }
1808
1809 document_text =
1810 static_cast<byte *>(mem_heap_zalloc(phrase->heap, total_len));
1811
1812 if (!document_text) {
1813 return false;
1814 }
1815 }
1816
1817 exp = node->select_list;
1818
1819 while (exp) {
1820 dfield_t *dfield = que_node_get_val(exp);
1821 byte *data = static_cast<byte *>(dfield_get_data(dfield));
1822 ulint cur_len;
1823
1824 if (dfield_is_ext(dfield)) {
1825 data = lob::btr_copy_externally_stored_field(
1826 nullptr, nullptr, &cur_len, nullptr, data, phrase->page_size,
1827 dfield_get_len(dfield), false, phrase->heap);
1828 } else {
1829 cur_len = dfield_get_len(dfield);
1830 }
1831
1832 if (cur_len != UNIV_SQL_NULL && cur_len != 0) {
1833 if (phrase->proximity_pos) {
1834 ut_ad(prev_len + cur_len <= total_len);
1835 memcpy(document_text + prev_len, data, cur_len);
1836 } else {
1837 /* For phrase search */
1838 phrase->found = fts_query_match_phrase(
1839 phrase, static_cast<byte *>(data), cur_len, prev_len, phrase->heap);
1840 }
1841
1842 /* Document positions are calculated from the beginning
1843 of the first field, need to save the length for each
1844 searched field to adjust the doc position when search
1845 phrases. */
1846 prev_len += cur_len + 1;
1847 }
1848
1849 if (phrase->found) {
1850 break;
1851 }
1852
1853 exp = que_node_get_next(exp);
1854 }
1855
1856 if (phrase->proximity_pos) {
1857 ut_ad(prev_len <= total_len);
1858
1859 phrase->found =
1860 fts_proximity_is_word_in_range(phrase, document_text, total_len);
1861 }
1862
1863 return (phrase->found);
1864 }
1865
1866 #if 0
1867 /********************************************************************
1868 Callback function to check whether a record was found or not. */
1869 static
1870 bool
1871 fts_query_query_block(
1872 void* row, /*!< in: sel_node_t* */
1873 void* user_arg) /*!< in: fts_doc_t* */
1874 {
1875 int i;
1876 que_node_t* exp;
1877 sel_node_t* node = row;
1878 fts_select_t* select = user_arg;
1879
1880 ut_a(select->word_freq);
1881 ut_a(select->word_freq->doc_freqs);
1882
1883 exp = node->select_list;
1884
1885 for (i = 0; exp && !select->found; ++i) {
1886 dfield_t* dfield = que_node_get_val(exp);
1887 void* data = dfield_get_data(dfield);
1888 ulint len = dfield_get_len(dfield);
1889
1890 switch (i) {
1891 case 0: /* DOC_COUNT */
1892 if (len != UNIV_SQL_NULL && len != 0) {
1893
1894 select->word_freq->doc_count +=
1895 mach_read_from_4(data);
1896 }
1897 break;
1898
1899 case 1: /* ILIST */
1900 if (len != UNIV_SQL_NULL && len != 0) {
1901
1902 fts_query_find_doc_id(select, data, len);
1903 }
1904 break;
1905
1906 default:
1907 ut_error;
1908 }
1909
1910 exp = que_node_get_next(exp);
1911 }
1912
1913 return(false);
1914 }
1915
1916 /********************************************************************
1917 Read the rows from the FTS index, that match word and where the
1918 doc id is between first and last doc id.
1919 @return DB_SUCCESS if all go well else error code */
1920 [[nodiscard]] static
1921 dberr_t
1922 fts_query_find_term(
1923 fts_query_t* query, /*!< in: FTS query state */
1924 que_t** graph, /*!< in: prepared statement */
1925 const fts_string_t* word, /*!< in: the word to fetch */
1926 doc_id_t doc_id, /*!< in: doc id to match */
1927 ulint* min_pos,/*!< in/out: pos found must be
1928 greater than this minimum value. */
1929 bool* found) /*!< out: true if found else false */
1930 {
1931 pars_info_t* info;
1932 dberr_t error;
1933 fts_select_t select;
1934 doc_id_t match_doc_id;
1935 trx_t* trx = query->trx;
1936 char table_name[MAX_FULL_NAME_LEN];
1937
1938 trx->op_info = "fetching FTS index matching nodes";
1939
1940 if (*graph) {
1941 info = (*graph)->info;
1942 } else {
1943 ulint selected;
1944
1945 info = pars_info_create();
1946
1947 selected = fts_select_index(*word->f_str);
1948 query->fts_index_table.suffix = fts_get_suffix(selected);
1949
1950 fts_get_table_name(&query->fts_index_table, table_name);
1951 pars_info_bind_id(info, true, "index_table_name", table_name);
1952 }
1953
1954 select.found = false;
1955 select.doc_id = doc_id;
1956 select.min_pos = *min_pos;
1957 select.word_freq = fts_query_add_word_freq(query, word->f_str);
1958
1959 pars_info_bind_function(info, "my_func", fts_query_query_block, &select);
1960 pars_info_bind_varchar_literal(info, "word", word->f_str, word->f_len);
1961
1962 /* Convert to "storage" byte order. */
1963 fts_write_doc_id((byte*) &match_doc_id, doc_id);
1964
1965 fts_bind_doc_id(info, "min_doc_id", &match_doc_id);
1966
1967 fts_bind_doc_id(info, "max_doc_id", &match_doc_id);
1968
1969 if (!*graph) {
1970
1971 *graph = fts_parse_sql(
1972 &query->fts_index_table,
1973 info,
1974 "DECLARE FUNCTION my_func;\n"
1975 "DECLARE CURSOR c IS"
1976 " SELECT doc_count, ilist\n"
1977 " FROM $index_table_name\n"
1978 " WHERE word LIKE :word AND"
1979 " first_doc_id <= :min_doc_id AND"
1980 " last_doc_id >= :max_doc_id\n"
1981 " ORDER BY first_doc_id;\n"
1982 "BEGIN\n"
1983 "\n"
1984 "OPEN c;\n"
1985 "WHILE 1 = 1 LOOP\n"
1986 " FETCH c INTO my_func();\n"
1987 " IF c % NOTFOUND THEN\n"
1988 " EXIT;\n"
1989 " END IF;\n"
1990 "END LOOP;\n"
1991 "CLOSE c;");
1992 }
1993
1994 for (;;) {
1995 error = fts_eval_sql(trx, *graph);
1996
1997 if (error == DB_SUCCESS) {
1998
1999 break; /* Exit the loop. */
2000 } else {
2001
2002 if (error == DB_LOCK_WAIT_TIMEOUT) {
2003 ib::warn(ER_IB_MSG_506) << "lock wait timeout reading FTS"
2004 " index. Retrying!";
2005
2006 trx->error_state = DB_SUCCESS;
2007 } else {
2008 ib::error(ER_IB_MSG_507) << error
2009 << " while reading FTS index.";
2010
2011 break; /* Exit the loop. */
2012 }
2013 }
2014 }
2015
2016 /* Value to return */
2017 *found = select.found;
2018
2019 if (*found) {
2020 *min_pos = select.min_pos;
2021 }
2022
2023 return(error);
2024 }
2025
2026 /********************************************************************
2027 Callback aggregator for int columns. */
2028 static
2029 bool
2030 fts_query_sum(
2031 /*!< out: always returns true */
2032 void* row, /*!< in: sel_node_t* */
2033 void* user_arg) /*!< in: ulint* */
2034 {
2035
2036 que_node_t* exp;
2037 sel_node_t* node = row;
2038 ulint* total = user_arg;
2039
2040 exp = node->select_list;
2041
2042 while (exp) {
2043 dfield_t* dfield = que_node_get_val(exp);
2044 void* data = dfield_get_data(dfield);
2045 ulint len = dfield_get_len(dfield);
2046
2047 if (len != UNIV_SQL_NULL && len != 0) {
2048 *total += mach_read_from_4(data);
2049 }
2050
2051 exp = que_node_get_next(exp);
2052 }
2053
2054 return(true);
2055 }
2056
2057 /********************************************************************
2058 Calculate the total documents that contain a particular word (term).
2059 @return DB_SUCCESS if all go well else error code */
2060 [[nodiscard]] static
2061 dberr_t
2062 fts_query_total_docs_containing_term(
2063 fts_query_t* query, /*!< in: FTS query state */
2064 const fts_string_t* word, /*!< in: the word to check */
2065 ulint* total) /*!< out: documents containing word */
2066 {
2067 pars_info_t* info;
2068 dberr_t error;
2069 que_t* graph;
2070 ulint selected;
2071 trx_t* trx = query->trx;
2072 char table_name[MAX_FULL_NAME_LEN]
2073
2074 trx->op_info = "fetching FTS index document count";
2075
2076 *total = 0;
2077
2078 info = pars_info_create();
2079
2080 pars_info_bind_function(info, "my_func", fts_query_sum, total);
2081 pars_info_bind_varchar_literal(info, "word", word->f_str, word->f_len);
2082
2083 selected = fts_select_index(*word->f_str);
2084
2085 query->fts_index_table.suffix = fts_get_suffix(selected);
2086
2087 fts_get_table_name(&query->fts_index_table, table_name);
2088
2089 pars_info_bind_id(info, true, "index_table_name", table_name);
2090
2091 graph = fts_parse_sql(
2092 &query->fts_index_table,
2093 info,
2094 "DECLARE FUNCTION my_func;\n"
2095 "DECLARE CURSOR c IS"
2096 " SELECT doc_count\n"
2097 " FROM $index_table_name\n"
2098 " WHERE word = :word"
2099 " ORDER BY first_doc_id;\n"
2100 "BEGIN\n"
2101 "\n"
2102 "OPEN c;\n"
2103 "WHILE 1 = 1 LOOP\n"
2104 " FETCH c INTO my_func();\n"
2105 " IF c % NOTFOUND THEN\n"
2106 " EXIT;\n"
2107 " END IF;\n"
2108 "END LOOP;\n"
2109 "CLOSE c;");
2110
2111 for (;;) {
2112 error = fts_eval_sql(trx, graph);
2113
2114 if (error == DB_SUCCESS) {
2115
2116 break; /* Exit the loop. */
2117 } else {
2118
2119 if (error == DB_LOCK_WAIT_TIMEOUT) {
2120 ib::warn(ER_IB_MSG_508) << "lock wait timeout reading FTS"
2121 " index. Retrying!";
2122
2123 trx->error_state = DB_SUCCESS;
2124 } else {
2125 ib::error(ER_IB_MSG_509) << error
2126 << " while reading FTS index.";
2127
2128 break; /* Exit the loop. */
2129 }
2130 }
2131 }
2132
2133 fts_que_graph_free(graph);
2134
2135 return(error);
2136 }
2137
2138 /********************************************************************
2139 Get the total number of words in a documents.
2140 @return DB_SUCCESS if all go well else error code */
2141 [[nodiscard]] static
2142 dberr_t
2143 fts_query_terms_in_document(
2144 fts_query_t* query, /*!< in: FTS query state */
2145 doc_id_t doc_id, /*!< in: the word to check */
2146 ulint* total) /*!< out: total words in document */
2147 {
2148 pars_info_t* info;
2149 dberr_t error;
2150 que_t* graph;
2151 doc_id_t read_doc_id;
2152 trx_t* trx = query->trx;
2153 char table_name[MAX_FULL_NAME_LEN];
2154
2155 trx->op_info = "fetching FTS document term count";
2156
2157 *total = 0;
2158
2159 info = pars_info_create();
2160
2161 pars_info_bind_function(info, "my_func", fts_query_sum, total);
2162
2163 /* Convert to "storage" byte order. */
2164 fts_write_doc_id((byte*) &read_doc_id, doc_id);
2165 fts_bind_doc_id(info, "doc_id", &read_doc_id);
2166
2167 query->fts_index_table.suffix = "DOC_ID";
2168
2169 fts_get_table_name(&query->fts_index_table, table_name);
2170
2171 pars_info_bind_id(info, true, "index_table_name", table_name);
2172
2173 graph = fts_parse_sql(
2174 &query->fts_index_table,
2175 info,
2176 "DECLARE FUNCTION my_func;\n"
2177 "DECLARE CURSOR c IS"
2178 " SELECT count\n"
2179 " FROM $index_table_name\n"
2180 " WHERE doc_id = :doc_id"
2181 " BEGIN\n"
2182 "\n"
2183 "OPEN c;\n"
2184 "WHILE 1 = 1 LOOP\n"
2185 " FETCH c INTO my_func();\n"
2186 " IF c % NOTFOUND THEN\n"
2187 " EXIT;\n"
2188 " END IF;\n"
2189 "END LOOP;\n"
2190 "CLOSE c;");
2191
2192 for (;;) {
2193 error = fts_eval_sql(trx, graph);
2194
2195 if (error == DB_SUCCESS) {
2196
2197 break; /* Exit the loop. */
2198 } else {
2199
2200 if (error == DB_LOCK_WAIT_TIMEOUT) {
2201 ib::warn(ER_IB_MSG_510) << "lock wait timeout reading FTS"
2202 " doc id table. Retrying!";
2203
2204 trx->error_state = DB_SUCCESS;
2205 } else {
2206 ib::error(ER_IB_MSG_511) << error << " while reading FTS"
2207 " doc id table.";
2208
2209 break; /* Exit the loop. */
2210 }
2211 }
2212 }
2213
2214 fts_que_graph_free(graph);
2215
2216 return(error);
2217 }
2218 #endif
2219
2220 /** Retrieve the document and match the phrase tokens.
2221 @return DB_SUCCESS or error code */
2222 [[nodiscard]] static dberr_t fts_query_match_document(
2223 ib_vector_t *tokens, /*!< in: phrase tokens */
2224 fts_get_doc_t *get_doc, /*!< in: table and prepared statements */
2225 fts_match_t *match, /*!< in: doc id and positions */
2226 ulint distance, /*!< in: proximity distance */
2227 st_mysql_ftparser *parser, /*!< in: fts plugin parser */
2228 bool *found) /*!< out: true if phrase found */
2229 {
2230 dberr_t error;
2231 fts_phrase_t phrase(get_doc->index_cache->index->table);
2232
2233 phrase.match = match; /* Positions to match */
2234 phrase.tokens = tokens; /* Tokens to match */
2235 phrase.distance = distance;
2236 phrase.charset = get_doc->index_cache->charset;
2237 phrase.heap = mem_heap_create(512, UT_LOCATION_HERE);
2238 phrase.parser = parser;
2239
2240 *found = phrase.found = false;
2241
2242 error = fts_doc_fetch_by_doc_id(get_doc, match->doc_id, nullptr,
2243 FTS_FETCH_DOC_BY_ID_EQUAL,
2244 fts_query_fetch_document, &phrase);
2245
2246 if (error != DB_SUCCESS) {
2247 ib::error(ER_IB_MSG_512)
2248 << "(" << ut_strerr(error) << ") matching document.";
2249 } else {
2250 *found = phrase.found;
2251 }
2252
2253 mem_heap_free(phrase.heap);
2254
2255 return (error);
2256 }
2257
2258 /** This function fetches the original documents and count the
2259 words in between matching words to see that is in specified distance
2260 @return DB_SUCCESS if all OK */
2261 [[nodiscard]] static bool fts_query_is_in_proximity_range(
2262 const fts_query_t *query, /*!< in: query instance */
2263 fts_match_t **match, /*!< in: query instance */
2264 fts_proximity_t *qualified_pos) /*!< in: position info for
2265 qualified ranges */
2266 {
2267 fts_get_doc_t get_doc;
2268 fts_cache_t *cache = query->index->table->fts->cache;
2269 dberr_t err;
2270
2271 memset(&get_doc, 0x0, sizeof(get_doc));
2272
2273 rw_lock_x_lock(&cache->lock, UT_LOCATION_HERE);
2274 get_doc.index_cache = fts_find_index_cache(cache, query->index);
2275 rw_lock_x_unlock(&cache->lock);
2276 ut_a(get_doc.index_cache != nullptr);
2277
2278 fts_phrase_t phrase(get_doc.index_cache->index->table);
2279
2280 phrase.distance = query->distance;
2281 phrase.charset = get_doc.index_cache->charset;
2282 phrase.heap = mem_heap_create(512, UT_LOCATION_HERE);
2283 phrase.proximity_pos = qualified_pos;
2284 phrase.found = false;
2285
2286 err = fts_doc_fetch_by_doc_id(&get_doc, match[0]->doc_id, nullptr,
2287 FTS_FETCH_DOC_BY_ID_EQUAL,
2288 fts_query_fetch_document, &phrase);
2289
2290 if (err != DB_SUCCESS) {
2291 ib::error(ER_IB_MSG_513) << "(" << ut_strerr(err)
2292 << ") in verification"
2293 " phase of proximity search";
2294 }
2295
2296 /* Free the prepared statement. */
2297 if (get_doc.get_document_graph) {
2298 fts_que_graph_free(get_doc.get_document_graph);
2299 get_doc.get_document_graph = nullptr;
2300 }
2301
2302 mem_heap_free(phrase.heap);
2303
2304 return (err == DB_SUCCESS && phrase.found);
2305 }
2306
2307 /** Iterate over the matched document ids and search the for the
2308 actual phrase in the text.
2309 @return DB_SUCCESS if all OK */
2310 [[nodiscard]] static dberr_t fts_query_search_phrase(
2311 fts_query_t *query, /*!< in: query instance */
2312 ib_vector_t *orig_tokens, /*!< in: tokens to search,
2313 with any stopwords in the
2314 original phrase */
2315 ib_vector_t *tokens) /*!< in: tokens that does
2316 not include stopwords and
2317 can be used to calculate
2318 ranking */
2319 {
2320 ulint i;
2321 fts_get_doc_t get_doc;
2322 ulint n_matched;
2323 fts_cache_t *cache = query->index->table->fts->cache;
2324
2325 n_matched = ib_vector_size(query->matched);
2326
2327 /* Setup the doc retrieval infrastructure. */
2328 memset(&get_doc, 0x0, sizeof(get_doc));
2329
2330 rw_lock_x_lock(&cache->lock, UT_LOCATION_HERE);
2331
2332 get_doc.index_cache = fts_find_index_cache(cache, query->index);
2333
2334 /* Must find the index cache */
2335 ut_a(get_doc.index_cache != nullptr);
2336
2337 rw_lock_x_unlock(&cache->lock);
2338
2339 #ifdef FTS_INTERNAL_DIAG_PRINT
2340 ib::info(ER_IB_MSG_514) << "Start phrase search";
2341 #endif
2342
2343 /* Read the document from disk and do the actual
2344 match, matching documents will be added to the current
2345 doc id set. */
2346 for (i = 0; i < n_matched && query->error == DB_SUCCESS; ++i) {
2347 fts_match_t *match;
2348 bool found = false;
2349
2350 match = static_cast<fts_match_t *>(ib_vector_get(query->matched, i));
2351
2352 /* Skip the document ids that were filtered out by
2353 an earlier pass. */
2354 if (match->doc_id != 0) {
2355 query->error = fts_query_match_document(
2356 orig_tokens, &get_doc, match, query->distance, query->parser, &found);
2357
2358 if (query->error == DB_SUCCESS && found) {
2359 ulint z;
2360
2361 query->error = fts_query_process_doc_id(query, match->doc_id, 0);
2362 if (query->error != DB_SUCCESS) {
2363 goto func_exit;
2364 }
2365
2366 for (z = 0; z < ib_vector_size(tokens); z++) {
2367 fts_string_t *token;
2368 token = static_cast<fts_string_t *>(ib_vector_get(tokens, z));
2369 fts_query_add_word_to_document(query, match->doc_id, token);
2370 }
2371 }
2372 }
2373 }
2374
2375 func_exit:
2376 /* Free the prepared statement. */
2377 if (get_doc.get_document_graph) {
2378 fts_que_graph_free(get_doc.get_document_graph);
2379 get_doc.get_document_graph = nullptr;
2380 }
2381
2382 return (query->error);
2383 }
2384
2385 /** Split the phrase into tokens
2386 @param[in,out] query query instance
2387 @param[in] node query node to search
2388 @param[in,out] tokens token vector
2389 @param[in,out] orig_tokens original node tokens include stopword
2390 @param[in,out] heap mem heap */
2391 static void fts_query_phrase_split(fts_query_t *query,
2392 const fts_ast_node_t *node,
2393 ib_vector_t *tokens,
2394 ib_vector_t *orig_tokens, mem_heap_t *heap) {
2395 fts_string_t phrase;
2396 ulint len = 0;
2397 ulint cur_pos = 0;
2398 fts_ast_node_t *term_node = nullptr;
2399
2400 if (node->type == FTS_AST_TEXT) {
2401 phrase.f_str = node->text.ptr->str;
2402 phrase.f_len = node->text.ptr->len;
2403 len = phrase.f_len;
2404 } else {
2405 ut_ad(node->type == FTS_AST_PARSER_PHRASE_LIST);
2406 phrase.f_str = nullptr;
2407 phrase.f_len = 0;
2408 term_node = node->list.head;
2409 }
2410
2411 while (true) {
2412 fts_cache_t *cache = query->index->table->fts->cache;
2413 ulint cur_len;
2414 fts_string_t result_str;
2415
2416 if (node->type == FTS_AST_TEXT) {
2417 if (cur_pos >= len) {
2418 break;
2419 }
2420
2421 cur_len = innobase_mysql_fts_get_token(
2422 query->fts_index_table.charset,
2423 reinterpret_cast<const byte *>(phrase.f_str) + cur_pos,
2424 reinterpret_cast<const byte *>(phrase.f_str) + len, &result_str);
2425
2426 if (cur_len == 0) {
2427 break;
2428 }
2429
2430 cur_pos += cur_len;
2431 } else {
2432 ut_ad(node->type == FTS_AST_PARSER_PHRASE_LIST);
2433 /* Term node in parser phrase list */
2434 if (term_node == nullptr) {
2435 break;
2436 }
2437
2438 ut_a(term_node->type == FTS_AST_TERM);
2439 result_str.f_str = term_node->term.ptr->str;
2440 result_str.f_len = term_node->term.ptr->len;
2441 result_str.f_n_char = fts_get_token_size(
2442 query->fts_index_table.charset,
2443 reinterpret_cast<char *>(result_str.f_str), result_str.f_len);
2444
2445 term_node = term_node->next;
2446 }
2447
2448 if (result_str.f_n_char == 0) {
2449 continue;
2450 }
2451
2452 fts_string_t *token =
2453 static_cast<fts_string_t *>(ib_vector_push(tokens, nullptr));
2454 fts_string_dup(token, &result_str, heap);
2455
2456 if (fts_check_token(&result_str, cache->stopword_info.cached_stopword,
2457 query->index->is_ngram,
2458 query->fts_index_table.charset)) {
2459 /* Add the word to the RB tree so that we can
2460 calculate its frequency within a document. */
2461 fts_query_add_word_freq(query, token);
2462 } else {
2463 ib_vector_pop(tokens);
2464 }
2465
2466 /* we will start to store all words including stopwords
2467 in the "orig_tokens" vector, but skip any leading words
2468 that are stopwords */
2469 if (!ib_vector_is_empty(tokens)) {
2470 fts_string_t *orig_token =
2471 static_cast<fts_string_t *>(ib_vector_push(orig_tokens, nullptr));
2472
2473 orig_token->f_str = token->f_str;
2474 orig_token->f_len = token->f_len;
2475 }
2476 }
2477 }
2478
2479 /** Proximity/Phrase search.
2480 Used to perform searches which include multiple words.
2481 @return DB_SUCCESS or error code */
2482 [[nodiscard]] static dberr_t fts_query_multi_word_search(
2483 fts_query_t *query, /*!< in: query instance */
2484 const fts_ast_node_t *node) /*!< in: node to search */
2485 {
2486 ib_vector_t *tokens;
2487 ib_vector_t *orig_tokens;
2488 mem_heap_t *heap = mem_heap_create(sizeof(fts_string_t), UT_LOCATION_HERE);
2489 ib_alloc_t *heap_alloc;
2490 ulint num_token;
2491
2492 heap_alloc = ib_heap_allocator_create(heap);
2493
2494 tokens = ib_vector_create(heap_alloc, sizeof(fts_string_t), 4);
2495 orig_tokens = ib_vector_create(heap_alloc, sizeof(fts_string_t), 4);
2496
2497 if (query->distance != ULINT_UNDEFINED && query->distance > 0) {
2498 query->flags = FTS_PROXIMITY;
2499 } else {
2500 query->flags = FTS_PHRASE;
2501 }
2502
2503 /* Split the phrase into tokens. */
2504 fts_query_phrase_split(query, node, tokens, orig_tokens, heap);
2505
2506 num_token = ib_vector_size(tokens);
2507 if (num_token > MAX_PROXIMITY_ITEM) {
2508 query->error = DB_FTS_TOO_MANY_WORDS_IN_PHRASE;
2509 goto func_exit;
2510 }
2511
2512 ut_ad(ib_vector_size(orig_tokens) >= num_token);
2513
2514 /* Ignore empty strings. */
2515 if (num_token > 0) {
2516 fts_string_t *token = nullptr;
2517 fts_fetch_t fetch;
2518 trx_t *trx = query->trx;
2519 fts_ast_oper_t oper = query->oper;
2520 que_t *graph = nullptr;
2521 ulint i;
2522 dberr_t error;
2523
2524 /* Create the vector for storing matching document ids
2525 and the positions of the first token of the phrase. */
2526 if (!query->matched) {
2527 ib_alloc_t *heap_alloc;
2528
2529 heap_alloc = ib_heap_allocator_create(heap);
2530
2531 if (!(query->flags & FTS_PROXIMITY) && !(query->flags & FTS_PHRASE)) {
2532 query->matched = ib_vector_create(heap_alloc, sizeof(fts_match_t), 64);
2533 } else {
2534 ut_a(num_token <= MAX_PROXIMITY_ITEM);
2535 query->match_array = (ib_vector_t **)mem_heap_alloc(
2536 heap, num_token * sizeof(query->matched));
2537
2538 for (i = 0; i < num_token; i++) {
2539 query->match_array[i] =
2540 ib_vector_create(heap_alloc, sizeof(fts_match_t), 64);
2541 }
2542
2543 query->matched = query->match_array[0];
2544 }
2545 }
2546
2547 /* Setup the callback args for filtering and consolidating
2548 the ilist. */
2549 fetch.read_arg = query;
2550 fetch.read_record = fts_query_index_fetch_nodes;
2551
2552 for (i = 0; i < num_token; i++) {
2553 /* Search for the first word from the phrase. */
2554 token = static_cast<fts_string_t *>(ib_vector_get(tokens, i));
2555
2556 if (query->flags & FTS_PROXIMITY || query->flags & FTS_PHRASE) {
2557 query->matched = query->match_array[i];
2558 }
2559
2560 error = fts_index_fetch_nodes(trx, &graph, &query->fts_index_table, token,
2561 &fetch);
2562
2563 /* DB_FTS_EXCEED_RESULT_CACHE_LIMIT passed by 'query->error' */
2564 ut_ad(!(query->error != DB_SUCCESS && error != DB_SUCCESS));
2565 if (error != DB_SUCCESS) {
2566 query->error = error;
2567 }
2568
2569 fts_que_graph_free(graph);
2570 graph = nullptr;
2571
2572 fts_query_cache(query, token);
2573
2574 if (!(query->flags & FTS_PHRASE) && !(query->flags & FTS_PROXIMITY)) {
2575 break;
2576 }
2577
2578 /* If any of the token can't be found,
2579 no need to continue match */
2580 if (ib_vector_is_empty(query->match_array[i]) ||
2581 query->error != DB_SUCCESS) {
2582 goto func_exit;
2583 }
2584 }
2585
2586 /* Just a single word, no need to fetch the original
2587 documents to do phrase matching */
2588 if (ib_vector_size(orig_tokens) == 1 &&
2589 !ib_vector_is_empty(query->match_array[0])) {
2590 fts_match_t *match;
2591 ulint n_matched;
2592
2593 n_matched = ib_vector_size(query->match_array[0]);
2594
2595 for (i = 0; i < n_matched; i++) {
2596 match =
2597 static_cast<fts_match_t *>(ib_vector_get(query->match_array[0], i));
2598
2599 query->error = fts_query_process_doc_id(query, match->doc_id, 0);
2600 if (query->error != DB_SUCCESS) {
2601 goto func_exit;
2602 }
2603
2604 fts_query_add_word_to_document(query, match->doc_id, token);
2605 }
2606 query->oper = oper;
2607 goto func_exit;
2608 }
2609
2610 /* If we are doing proximity search, verify the distance
2611 between all words, and check they are in specified distance. */
2612 if (query->flags & FTS_PROXIMITY) {
2613 fts_search_docs_containing_all_tokens(query, tokens);
2614 } else {
2615 /* Phrase Search case:
2616 We filter out the doc ids that don't contain
2617 all the tokens in the phrase. It's cheaper to
2618 search the ilist than bringing the documents in
2619 and then doing a search through the text. Isolated
2620 testing shows this also helps in mitigating disruption
2621 of the buffer cache. */
2622 auto matched = fts_search_docs_containing_all_tokens(query, tokens);
2623 query->matched = query->match_array[0];
2624
2625 /* Read the actual text in and search for the phrase. */
2626 if (matched) {
2627 ut_ad(query->error == DB_SUCCESS);
2628 query->error = fts_query_search_phrase(query, orig_tokens, tokens);
2629 }
2630 }
2631
2632 /* Restore original operation. */
2633 query->oper = oper;
2634
2635 if (query->error != DB_SUCCESS) {
2636 goto func_exit;
2637 }
2638 }
2639
2640 func_exit:
2641 mem_heap_free(heap);
2642
2643 /* Don't need it anymore. */
2644 query->matched = nullptr;
2645
2646 return (query->error);
2647 }
2648
2649 /** Find the word and evaluate.
2650 @return DB_SUCCESS if all go well */
2651 [[nodiscard]] static dberr_t fts_query_execute(
2652 fts_query_t *query, /*!< in: query instance */
2653 fts_string_t *token) /*!< in: token to search */
2654 {
2655 switch (query->oper) {
2656 case FTS_NONE:
2657 case FTS_NEGATE:
2658 case FTS_INCR_RATING:
2659 case FTS_DECR_RATING:
2660 query->error = fts_query_union(query, token);
2661 break;
2662
2663 case FTS_EXIST:
2664 query->error = fts_query_intersect(query, token);
2665 break;
2666
2667 case FTS_IGNORE:
2668 query->error = fts_query_difference(query, token);
2669 break;
2670
2671 default:
2672 ut_error;
2673 }
2674
2675 return (query->error);
2676 }
2677
2678 /** Create a wildcard string. It's the responsibility of the caller to
2679 free the byte* pointer. It's allocated using
2680 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY).
2681 @return ptr to allocated memory */
2682 static byte *fts_query_get_token(
2683 fts_ast_node_t *node, /*!< in: the current sub tree */
2684 fts_string_t *token) /*!< in: token to create */
2685 {
2686 ulint str_len;
2687 byte *new_ptr = nullptr;
2688
2689 str_len = node->term.ptr->len;
2690
2691 ut_a(node->type == FTS_AST_TERM);
2692
2693 token->f_len = str_len;
2694 token->f_str = node->term.ptr->str;
2695
2696 if (node->term.wildcard) {
2697 token->f_str = static_cast<byte *>(
2698 ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, str_len + 2));
2699 token->f_len = str_len + 1;
2700
2701 memcpy(token->f_str, node->term.ptr->str, str_len);
2702
2703 token->f_str[str_len] = '%';
2704 token->f_str[token->f_len] = 0;
2705
2706 new_ptr = token->f_str;
2707 }
2708
2709 return (new_ptr);
2710 }
2711
2712 /** Visit every node of the AST. */
2713 static dberr_t fts_query_visitor(
2714 fts_ast_oper_t oper, /*!< in: current operator */
2715 fts_ast_node_t *node, /*!< in: The root of the current subtree*/
2716 void *arg) /*!< in: callback arg*/
2717 {
2718 byte *ptr;
2719 fts_string_t token;
2720 fts_query_t *query = static_cast<fts_query_t *>(arg);
2721
2722 ut_a(node);
2723 DBUG_TRACE;
2724 DBUG_PRINT("fts", ("nodetype: %s", fts_ast_node_type_get(node->type)));
2725
2726 token.f_n_char = 0;
2727 query->oper = oper;
2728 query->cur_node = node;
2729
2730 switch (node->type) {
2731 case FTS_AST_TEXT:
2732 case FTS_AST_PARSER_PHRASE_LIST:
2733
2734 if (query->oper == FTS_EXIST) {
2735 ut_ad(query->intersection == nullptr);
2736 query->intersection =
2737 rbt_create(sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
2738
2739 query->total_size += SIZEOF_RBT_CREATE;
2740 }
2741
2742 /* Set the current proximity distance. */
2743 query->distance = node->text.distance;
2744
2745 /* Force collection of doc ids and the positions. */
2746 query->collect_positions = true;
2747
2748 query->error = fts_query_multi_word_search(query, node);
2749
2750 query->collect_positions = false;
2751
2752 if (query->oper == FTS_EXIST) {
2753 fts_query_free_doc_ids(query, query->doc_ids);
2754 query->doc_ids = query->intersection;
2755 query->intersection = nullptr;
2756 }
2757
2758 break;
2759
2760 case FTS_AST_TERM:
2761 token.f_str = node->term.ptr->str;
2762 token.f_len = node->term.ptr->len;
2763
2764 /* Collect wildcard words for QUERY EXPANSION. */
2765 if (node->term.wildcard && query->wildcard_words != nullptr) {
2766 ib_rbt_bound_t parent;
2767
2768 if (rbt_search(query->wildcard_words, &parent, &token) != 0) {
2769 fts_string_t word;
2770
2771 fts_string_dup(&word, &token, query->heap);
2772 rbt_add_node(query->wildcard_words, &parent, &word);
2773 }
2774 }
2775
2776 /* Add the word to our RB tree that will be used to
2777 calculate this terms per document frequency. */
2778 fts_query_add_word_freq(query, &token);
2779
2780 ptr = fts_query_get_token(node, &token);
2781 query->error = fts_query_execute(query, &token);
2782
2783 if (ptr) {
2784 ut::free(ptr);
2785 }
2786
2787 break;
2788
2789 case FTS_AST_SUBEXP_LIST:
2790 query->error = fts_ast_visit_sub_exp(node, fts_query_visitor, arg);
2791 break;
2792
2793 default:
2794 ut_error;
2795 }
2796
2797 if (query->oper == FTS_EXIST) {
2798 query->multi_exist = true;
2799 }
2800
2801 return query->error;
2802 }
2803
2804 /** Process (nested) sub-expression, create a new result set to store the
2805 sub-expression result by processing nodes under current sub-expression
2806 list. Merge the sub-expression result with that of parent expression list.
2807 @param[in,out] node current root node
2808 @param[in,out] visitor callback function
2809 @param[in,out] arg argument for callback
2810 @return DB_SUCCESS if all go well */
2811 static dberr_t fts_ast_visit_sub_exp(fts_ast_node_t *node,
2812 fts_ast_callback visitor, void *arg) {
2813 fts_ast_oper_t cur_oper;
2814 fts_query_t *query = static_cast<fts_query_t *>(arg);
2815 ib_rbt_t *parent_doc_ids;
2816 ib_rbt_t *subexpr_doc_ids;
2817 dberr_t error = DB_SUCCESS;
2818 bool will_be_ignored = false;
2819 bool multi_exist;
2820
2821 DBUG_TRACE;
2822
2823 /* sub-expression list may contains sub-expressions.
2824 So we increase sub-expression depth counter.
2825 If this counter reaches to the threshold then
2826 we abort the search operation and report an error */
2827 if (query->nested_exp_count > FTS_MAX_NESTED_EXP) {
2828 query->error = DB_FTS_TOO_MANY_NESTED_EXP;
2829 return query->error;
2830 }
2831 query->nested_exp_count++;
2832
2833 ut_a(node->type == FTS_AST_SUBEXP_LIST);
2834
2835 cur_oper = query->oper;
2836
2837 /* Save current result set */
2838 parent_doc_ids = query->doc_ids;
2839
2840 /* Create new result set to store the sub-expression result. We
2841 will merge this result set with the parent after processing. */
2842 query->doc_ids = rbt_create(sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
2843
2844 query->total_size += SIZEOF_RBT_CREATE;
2845
2846 multi_exist = query->multi_exist;
2847 query->multi_exist = false;
2848 /* Process nodes in current sub-expression and store its
2849 result set in query->doc_ids we created above. */
2850 error = fts_ast_visit(FTS_NONE, node, visitor, arg, &will_be_ignored);
2851
2852 /* Reinstate parent node state */
2853 query->multi_exist = multi_exist;
2854 query->oper = cur_oper;
2855
2856 /* Merge the sub-expression result with the parent result set. */
2857 subexpr_doc_ids = query->doc_ids;
2858 query->doc_ids = parent_doc_ids;
2859 if (error == DB_SUCCESS) {
2860 error = fts_merge_doc_ids(query, subexpr_doc_ids);
2861 }
2862
2863 /* Free current result set. Result already merged into parent. */
2864 fts_query_free_doc_ids(query, subexpr_doc_ids);
2865
2866 return error;
2867 }
2868
2869 #if 0
2870 /*****************************************************************//***
2871 Check if the doc id exists in the ilist.
2872 @return true if doc id found */
2873 static
2874 ulint
2875 fts_query_find_doc_id(
2876 fts_select_t* select, /*!< in/out: contains the doc id to
2877 find, we update the word freq if
2878 document found */
2879 void* data, /*!< in: doc id ilist */
2880 ulint len) /*!< in: doc id ilist size */
2881 {
2882 byte* ptr = data;
2883 doc_id_t doc_id = 0;
2884 ulint decoded = 0;
2885
2886 /* Decode the ilist and search for selected doc_id. We also
2887 calculate the frequency of the word in the document if found. */
2888 while (decoded < len && !select->found) {
2889 ulint freq = 0;
2890 ulint min_pos = 0;
2891 ulint last_pos = 0;
2892 const uint64_t delta = fts_decode_vlc(&ptr);
2893
2894 /* Add the delta. */
2895 doc_id += delta;
2896
2897 while (*ptr) {
2898 ++freq;
2899 const uint64_t decoded_pos = fts_decode_vlc(&ptr);
2900 ut_ad(uint64_t(last_pos) + decoded_pos
2901 <= std::numeric_limits<ulint>::max());
2902 last_pos += static_cast<ulint>(decoded_pos);
2903
2904 /* Only if min_pos is not set and the current
2905 term exists in a position greater than the
2906 min_pos of the previous term. */
2907 if (min_pos == 0 && last_pos > select->min_pos) {
2908 min_pos = last_pos;
2909 }
2910 }
2911
2912 /* Skip the end of word position marker. */
2913 ++ptr;
2914
2915 /* Bytes decoded so far. */
2916 decoded = ptr - (byte*) data;
2917
2918 /* A word may exist in the document but we only consider a
2919 match if it exists in a position that is greater than the
2920 position of the previous term. */
2921 if (doc_id == select->doc_id && min_pos > 0) {
2922 fts_doc_freq_t* doc_freq;
2923
2924 /* Add the doc id to the doc freq rb tree, if
2925 the doc id doesn't exist it will be created. */
2926 doc_freq = fts_query_add_doc_freq(
2927 select->word_freq->doc_freqs, doc_id);
2928
2929 /* Avoid duplicating the frequency tally */
2930 if (doc_freq->freq == 0) {
2931 doc_freq->freq = freq;
2932 }
2933
2934 select->found = true;
2935 select->min_pos = min_pos;
2936 }
2937 }
2938
2939 return(select->found);
2940 }
2941 #endif
2942
2943 /** Read and filter nodes.
2944 @return DB_SUCCESS if all go well,
2945 or return DB_FTS_EXCEED_RESULT_CACHE_LIMIT */
2946 static dberr_t fts_query_filter_doc_ids(
2947 fts_query_t *query, /*!< in: query instance */
2948 const fts_string_t *word, /*!< in: the current word */
2949 fts_word_freq_t *word_freq, /*!< in/out: word frequency */
2950 const fts_node_t *node, /*!< in: current FTS node */
2951 void *data, /*!< in: doc id ilist */
2952 ulint len, /*!< in: doc id ilist size */
2953 bool calc_doc_count) /*!< in: whether to remember doc count */
2954 {
2955 byte *ptr = static_cast<byte *>(data);
2956 doc_id_t doc_id = 0;
2957 ulint decoded = 0;
2958 ib_rbt_t *doc_freqs = word_freq->doc_freqs;
2959
2960 if (query->limit != ULONG_UNDEFINED && query->n_docs >= query->limit) {
2961 return (DB_SUCCESS);
2962 }
2963
2964 /* Decode the ilist and add the doc ids to the query doc_id set. */
2965 while (decoded < len) {
2966 ulint freq = 0;
2967 fts_doc_freq_t *doc_freq;
2968 fts_match_t *match = nullptr;
2969 ulint last_pos = 0;
2970 const uint64_t delta = fts_decode_vlc(&ptr);
2971
2972 /* Some sanity checks. */
2973 if (doc_id == 0) {
2974 ut_a(delta == node->first_doc_id);
2975 }
2976
2977 /* Add the delta. */
2978 doc_id += delta;
2979
2980 if (calc_doc_count) {
2981 word_freq->doc_count++;
2982 }
2983
2984 /* We simply collect the matching instances here. */
2985 if (query->collect_positions) {
2986 ib_alloc_t *heap_alloc;
2987
2988 /* Create a new fts_match_t instance. */
2989 match =
2990 static_cast<fts_match_t *>(ib_vector_push(query->matched, nullptr));
2991
2992 match->start = 0;
2993 match->doc_id = doc_id;
2994 heap_alloc = ib_vector_allocator(query->matched);
2995
2996 /* Allocate from the same heap as the
2997 parent container. */
2998 match->positions = ib_vector_create(heap_alloc, sizeof(ulint), 64);
2999
3000 query->total_size +=
3001 sizeof(fts_match_t) + sizeof(ib_vector_t) + sizeof(ulint) * 64;
3002 }
3003
3004 /* Unpack the positions within the document. */
3005 while (*ptr) {
3006 const uint64_t pos_delta = fts_decode_vlc(&ptr);
3007 ut_ad(uint64_t(last_pos) + pos_delta <=
3008 std::numeric_limits<ulint>::max());
3009 last_pos += static_cast<ulint>(pos_delta);
3010
3011 /* Collect the matching word positions, for phrase
3012 matching later. */
3013 if (query->collect_positions) {
3014 ib_vector_push(match->positions, &last_pos);
3015 }
3016
3017 ++freq;
3018 }
3019
3020 /* End of list marker. */
3021 last_pos = (ulint)-1;
3022
3023 if (query->collect_positions) {
3024 ut_a(match != nullptr);
3025 ib_vector_push(match->positions, &last_pos);
3026 }
3027
3028 /* Add the doc id to the doc freq rb tree, if the doc id
3029 doesn't exist it will be created. */
3030 doc_freq = fts_query_add_doc_freq(query, doc_freqs, doc_id);
3031
3032 /* Avoid duplicating frequency tally. */
3033 if (doc_freq->freq == 0) {
3034 doc_freq->freq = freq;
3035 }
3036
3037 /* Skip the end of word position marker. */
3038 ++ptr;
3039
3040 /* Bytes decoded so far */
3041 decoded = ptr - (byte *)data;
3042
3043 /* We simply collect the matching documents and the
3044 positions here and match later. */
3045 if (!query->collect_positions) {
3046 /* We ignore error here and will check it later */
3047 fts_query_process_doc_id(query, doc_id, 0);
3048
3049 /* Add the word to the document's matched RB tree. */
3050 fts_query_add_word_to_document(query, doc_id, word);
3051 }
3052
3053 if (query->limit != ULONG_UNDEFINED && query->limit <= ++query->n_docs) {
3054 goto func_exit;
3055 }
3056 }
3057
3058 /* Some sanity checks. */
3059 ut_a(doc_id == node->last_doc_id);
3060
3061 func_exit:
3062 if (query->total_size > fts_result_cache_limit) {
3063 return (DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
3064 } else {
3065 query->n_docs = 0;
3066 return (DB_SUCCESS);
3067 }
3068 }
3069
3070 /** Read the FTS INDEX row.
3071 @return DB_SUCCESS if all go well. */
3072 static dberr_t fts_query_read_node(
3073 fts_query_t *query, /*!< in: query instance */
3074 const fts_string_t *word, /*!< in: current word */
3075 que_node_t *exp) /*!< in: query graph node */
3076 {
3077 int i;
3078 int ret;
3079 fts_node_t node;
3080 ib_rbt_bound_t parent;
3081 fts_word_freq_t *word_freq;
3082 bool skip = false;
3083 fts_string_t term;
3084 byte buf[FTS_MAX_WORD_LEN + 1];
3085 dberr_t error = DB_SUCCESS;
3086
3087 ut_a(query->cur_node->type == FTS_AST_TERM ||
3088 query->cur_node->type == FTS_AST_TEXT ||
3089 query->cur_node->type == FTS_AST_PARSER_PHRASE_LIST);
3090
3091 memset(&node, 0, sizeof(node));
3092 term.f_str = buf;
3093
3094 /* Need to consider the wildcard search case, the word frequency
3095 is created on the search string not the actual word. So we need
3096 to assign the frequency on search string behalf. */
3097 if (query->cur_node->type == FTS_AST_TERM && query->cur_node->term.wildcard) {
3098 term.f_len = query->cur_node->term.ptr->len;
3099 ut_ad(FTS_MAX_WORD_LEN >= term.f_len);
3100 memcpy(term.f_str, query->cur_node->term.ptr->str, term.f_len);
3101 } else {
3102 term.f_len = word->f_len;
3103 ut_ad(FTS_MAX_WORD_LEN >= word->f_len);
3104 memcpy(term.f_str, word->f_str, word->f_len);
3105 }
3106
3107 /* Lookup the word in our rb tree, it must exist. */
3108 ret = rbt_search(query->word_freqs, &parent, &term);
3109
3110 ut_a(ret == 0);
3111
3112 word_freq = rbt_value(fts_word_freq_t, parent.last);
3113
3114 /* Start from 1 since the first column has been read by the caller.
3115 Also, we rely on the order of the columns projected, to filter
3116 out ilists that are out of range and we always want to read
3117 the doc_count irrespective of the suitablility of the row. */
3118
3119 for (i = 1; exp && !skip; exp = que_node_get_next(exp), ++i) {
3120 dfield_t *dfield = que_node_get_val(exp);
3121 byte *data = static_cast<byte *>(dfield_get_data(dfield));
3122 ulint len = dfield_get_len(dfield);
3123
3124 ut_a(len != UNIV_SQL_NULL);
3125
3126 /* Note: The column numbers below must match the SELECT. */
3127
3128 switch (i) {
3129 case 1: /* DOC_COUNT */
3130 word_freq->doc_count += mach_read_from_4(data);
3131 break;
3132
3133 case 2: /* FIRST_DOC_ID */
3134 node.first_doc_id = fts_read_doc_id(data);
3135
3136 /* Skip nodes whose doc ids are out range. */
3137 if (query->oper == FTS_EXIST && query->upper_doc_id > 0 &&
3138 node.first_doc_id > query->upper_doc_id) {
3139 skip = true;
3140 }
3141 break;
3142
3143 case 3: /* LAST_DOC_ID */
3144 node.last_doc_id = fts_read_doc_id(data);
3145
3146 /* Skip nodes whose doc ids are out range. */
3147 if (query->oper == FTS_EXIST && query->lower_doc_id > 0 &&
3148 node.last_doc_id < query->lower_doc_id) {
3149 skip = true;
3150 }
3151 break;
3152
3153 case 4: /* ILIST */
3154
3155 error = fts_query_filter_doc_ids(query, &word_freq->word, word_freq,
3156 &node, data, len, false);
3157
3158 break;
3159
3160 default:
3161 ut_error;
3162 }
3163 }
3164
3165 if (!skip) {
3166 /* Make sure all columns were read. */
3167
3168 ut_a(i == 5);
3169 }
3170
3171 return error;
3172 }
3173
3174 /** Callback function to fetch the rows in an FTS INDEX record.
3175 @return always returns true */
3176 static bool fts_query_index_fetch_nodes(
3177 void *row, /*!< in: sel_node_t* */
3178 void *user_arg) /*!< in: pointer to fts_fetch_t */
3179 {
3180 fts_string_t key;
3181 sel_node_t *sel_node = static_cast<sel_node_t *>(row);
3182 fts_fetch_t *fetch = static_cast<fts_fetch_t *>(user_arg);
3183 fts_query_t *query = static_cast<fts_query_t *>(fetch->read_arg);
3184 que_node_t *exp = sel_node->select_list;
3185 dfield_t *dfield = que_node_get_val(exp);
3186 void *data = dfield_get_data(dfield);
3187 ulint dfield_len = dfield_get_len(dfield);
3188
3189 key.f_str = static_cast<byte *>(data);
3190 key.f_len = dfield_len;
3191
3192 ut_a(dfield_len <= FTS_MAX_WORD_LEN);
3193
3194 /* Note: we pass error out by 'query->error' */
3195 query->error = fts_query_read_node(query, &key, que_node_get_next(exp));
3196
3197 if (query->error != DB_SUCCESS) {
3198 ut_ad(query->error == DB_FTS_EXCEED_RESULT_CACHE_LIMIT);
3199 return false;
3200 } else {
3201 return true;
3202 }
3203 }
3204
3205 /** Calculate the inverse document frequency (IDF) for all the terms. */
3206 static void fts_query_calculate_idf(fts_query_t *query) /*!< in: Query state */
3207 {
3208 const ib_rbt_node_t *node;
3209 uint64_t total_docs = query->total_docs;
3210
3211 /* We need to free any instances of fts_doc_freq_t that we
3212 may have allocated. */
3213 for (node = rbt_first(query->word_freqs); node;
3214 node = rbt_next(query->word_freqs, node)) {
3215 fts_word_freq_t *word_freq;
3216
3217 word_freq = rbt_value(fts_word_freq_t, node);
3218
3219 if (word_freq->doc_count > 0) {
3220 if (total_docs == word_freq->doc_count) {
3221 /* QP assume ranking > 0 if we find
3222 a match. Since Log10(1) = 0, we cannot
3223 make IDF a zero value if do find a
3224 word in all documents. So let's make
3225 it an arbitrary very small number */
3226 word_freq->idf = log10(1.0001);
3227 } else {
3228 word_freq->idf = log10(total_docs / (double)word_freq->doc_count);
3229 }
3230 }
3231
3232 if (fts_enable_diag_print) {
3233 ib::info(ER_IB_MSG_515)
3234 << "'" << word_freq->word.f_str << "' -> " << query->total_docs << "/"
3235 << word_freq->doc_count << " " << std::setw(6) << std::setprecision(5)
3236 << word_freq->idf;
3237 }
3238 }
3239 }
3240
3241 /** Calculate the ranking of the document. */
3242 static void fts_query_calculate_ranking(
3243 const fts_query_t *query, /*!< in: query state */
3244 fts_ranking_t *ranking) /*!< in: Document to rank */
3245 {
3246 ulint pos = 0;
3247 fts_string_t word;
3248
3249 /* At this stage, ranking->rank should not exceed the 1.0
3250 bound */
3251 ut_ad(ranking->rank <= 1.0 && ranking->rank >= -1.0);
3252 ut_ad(rbt_size(query->word_map) == query->word_vector->size());
3253
3254 while (fts_ranking_words_get_next(query, ranking, &pos, &word)) {
3255 int ret;
3256 ib_rbt_bound_t parent;
3257 double weight;
3258 fts_doc_freq_t *doc_freq;
3259 fts_word_freq_t *word_freq;
3260
3261 ret = rbt_search(query->word_freqs, &parent, &word);
3262
3263 /* It must exist. */
3264 ut_a(ret == 0);
3265
3266 word_freq = rbt_value(fts_word_freq_t, parent.last);
3267
3268 ret = rbt_search(word_freq->doc_freqs, &parent, &ranking->doc_id);
3269
3270 /* It must exist. */
3271 ut_a(ret == 0);
3272
3273 doc_freq = rbt_value(fts_doc_freq_t, parent.last);
3274
3275 weight = (double)doc_freq->freq * word_freq->idf;
3276
3277 ranking->rank += (fts_rank_t)(weight * word_freq->idf);
3278 }
3279 }
3280
3281 /** Add ranking to the result set. */
3282 static void fts_query_add_ranking(
3283 fts_query_t *query, /*!< in: query state */
3284 ib_rbt_t *ranking_tree, /*!< in: ranking tree */
3285 const fts_ranking_t *new_ranking) /*!< in: ranking of a document */
3286 {
3287 ib_rbt_bound_t parent;
3288
3289 /* Lookup the ranking in our rb tree and add if it doesn't exist. */
3290 if (rbt_search(ranking_tree, &parent, new_ranking) == 0) {
3291 fts_ranking_t *ranking;
3292
3293 ranking = rbt_value(fts_ranking_t, parent.last);
3294
3295 ranking->rank += new_ranking->rank;
3296
3297 ut_a(ranking->words == nullptr);
3298 } else {
3299 rbt_add_node(ranking_tree, &parent, new_ranking);
3300
3301 query->total_size += SIZEOF_RBT_NODE_ADD + sizeof(fts_ranking_t);
3302 }
3303 }
3304
3305 /** Retrieve the FTS Relevance Ranking result for doc with doc_id
3306 @return the relevance ranking value, 0 if no ranking value
3307 present. */
3308 float fts_retrieve_ranking(
3309 fts_result_t *result, /*!< in: FTS result structure */
3310 doc_id_t doc_id) /*!< in: doc_id of the item to retrieve */
3311 {
3312 ib_rbt_bound_t parent;
3313 fts_ranking_t new_ranking;
3314
3315 DBUG_TRACE;
3316
3317 if (!result || !result->rankings_by_id) {
3318 return 0;
3319 }
3320
3321 new_ranking.doc_id = doc_id;
3322
3323 /* Lookup the ranking in our rb tree */
3324 if (rbt_search(result->rankings_by_id, &parent, &new_ranking) == 0) {
3325 fts_ranking_t *ranking;
3326
3327 ranking = rbt_value(fts_ranking_t, parent.last);
3328
3329 return ranking->rank;
3330 }
3331
3332 return 0;
3333 }
3334
3335 /** Create the result and copy the data to it. */
3336 static fts_result_t *fts_query_prepare_result(
3337 fts_query_t *query, /*!< in: Query state */
3338 fts_result_t *result) /*!< in: result this can contain
3339 data from a previous search on
3340 another FTS index */
3341 {
3342 const ib_rbt_node_t *node;
3343 bool result_is_null = false;
3344
3345 DBUG_TRACE;
3346
3347 if (result == nullptr) {
3348 result = static_cast<fts_result_t *>(
3349 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof(*result)));
3350
3351 result->rankings_by_id =
3352 rbt_create(sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
3353
3354 query->total_size += sizeof(fts_result_t) + SIZEOF_RBT_CREATE;
3355 result_is_null = true;
3356 }
3357
3358 if (query->flags == FTS_OPT_RANKING) {
3359 fts_word_freq_t *word_freq;
3360 ulint size = ib_vector_size(query->deleted->doc_ids);
3361 fts_update_t *array = (fts_update_t *)query->deleted->doc_ids->data;
3362
3363 node = rbt_first(query->word_freqs);
3364 ut_ad(node);
3365 word_freq = rbt_value(fts_word_freq_t, node);
3366
3367 for (node = rbt_first(word_freq->doc_freqs); node;
3368 node = rbt_next(word_freq->doc_freqs, node)) {
3369 fts_doc_freq_t *doc_freq;
3370 fts_ranking_t ranking;
3371
3372 doc_freq = rbt_value(fts_doc_freq_t, node);
3373
3374 /* Don't put deleted docs into result */
3375 if (fts_bsearch(array, 0, static_cast<int>(size), doc_freq->doc_id) >=
3376 0) {
3377 /* one less matching doc count */
3378 --word_freq->doc_count;
3379 continue;
3380 }
3381
3382 ranking.doc_id = doc_freq->doc_id;
3383 ranking.rank = static_cast<fts_rank_t>(doc_freq->freq);
3384 ranking.words = nullptr;
3385
3386 fts_query_add_ranking(query, result->rankings_by_id, &ranking);
3387
3388 if (query->total_size > fts_result_cache_limit) {
3389 query->error = DB_FTS_EXCEED_RESULT_CACHE_LIMIT;
3390 fts_query_free_result(result);
3391 return nullptr;
3392 }
3393 }
3394
3395 /* Calculate IDF only after we exclude the deleted items */
3396 fts_query_calculate_idf(query);
3397
3398 node = rbt_first(query->word_freqs);
3399 word_freq = rbt_value(fts_word_freq_t, node);
3400
3401 /* Calculate the ranking for each doc */
3402 for (node = rbt_first(result->rankings_by_id); node != nullptr;
3403 node = rbt_next(result->rankings_by_id, node)) {
3404 fts_ranking_t *ranking;
3405
3406 ranking = rbt_value(fts_ranking_t, node);
3407
3408 ranking->rank = static_cast<fts_rank_t>(ranking->rank * word_freq->idf *
3409 word_freq->idf);
3410 }
3411
3412 return result;
3413 }
3414
3415 ut_a(rbt_size(query->doc_ids) > 0);
3416
3417 for (node = rbt_first(query->doc_ids); node;
3418 node = rbt_next(query->doc_ids, node)) {
3419 fts_ranking_t *ranking;
3420
3421 ranking = rbt_value(fts_ranking_t, node);
3422 fts_query_calculate_ranking(query, ranking);
3423
3424 // FIXME: I think we may require this information to improve the
3425 // ranking of doc ids which have more word matches from
3426 // different FTS indexes.
3427
3428 /* We don't need these anymore free the resources. */
3429 ranking->words = nullptr;
3430
3431 if (!result_is_null) {
3432 fts_query_add_ranking(query, result->rankings_by_id, ranking);
3433
3434 if (query->total_size > fts_result_cache_limit) {
3435 query->error = DB_FTS_EXCEED_RESULT_CACHE_LIMIT;
3436 fts_query_free_result(result);
3437 return nullptr;
3438 }
3439 }
3440 }
3441
3442 if (result_is_null) {
3443 /* Use doc_ids directly */
3444 rbt_free(result->rankings_by_id);
3445 result->rankings_by_id = query->doc_ids;
3446 query->doc_ids = nullptr;
3447 }
3448
3449 return result;
3450 }
3451
3452 /** Get the result of the query. Calculate the similarity coefficient. */
3453 static fts_result_t *fts_query_get_result(
3454 fts_query_t *query, /*!< in: query instance */
3455 fts_result_t *result) /*!< in: result */
3456 {
3457 DBUG_TRACE;
3458
3459 if (rbt_size(query->doc_ids) > 0 || query->flags == FTS_OPT_RANKING) {
3460 /* Copy the doc ids to the result. */
3461 result = fts_query_prepare_result(query, result);
3462 } else {
3463 /* Create an empty result instance. */
3464 result = static_cast<fts_result_t *>(
3465 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof(*result)));
3466 }
3467
3468 return result;
3469 }
3470
3471 /** FTS Query free resources and reset. */
3472 static void fts_query_free(fts_query_t *query) /*!< in: query instance to free*/
3473 {
3474 if (query->read_nodes_graph) {
3475 fts_que_graph_free(query->read_nodes_graph);
3476 }
3477
3478 if (query->root) {
3479 fts_ast_free_node(query->root);
3480 }
3481
3482 if (query->deleted) {
3483 fts_doc_ids_free(query->deleted);
3484 }
3485
3486 if (query->intersection) {
3487 fts_query_free_doc_ids(query, query->intersection);
3488 query->intersection = nullptr;
3489 }
3490
3491 if (query->doc_ids) {
3492 fts_query_free_doc_ids(query, query->doc_ids);
3493 }
3494
3495 if (query->word_freqs) {
3496 const ib_rbt_node_t *node;
3497
3498 /* We need to free any instances of fts_doc_freq_t that we
3499 may have allocated. */
3500 for (node = rbt_first(query->word_freqs); node;
3501 node = rbt_next(query->word_freqs, node)) {
3502 fts_word_freq_t *word_freq;
3503
3504 word_freq = rbt_value(fts_word_freq_t, node);
3505
3506 /* We need to cast away the const. */
3507 rbt_free(word_freq->doc_freqs);
3508 }
3509
3510 rbt_free(query->word_freqs);
3511 }
3512
3513 if (query->wildcard_words != nullptr) {
3514 rbt_free(query->wildcard_words);
3515 }
3516
3517 ut_a(!query->intersection);
3518
3519 if (query->word_map) {
3520 rbt_free(query->word_map);
3521 }
3522
3523 if (query->word_vector != nullptr) {
3524 ut::delete_(query->word_vector);
3525 }
3526
3527 if (query->heap) {
3528 mem_heap_free(query->heap);
3529 }
3530
3531 memset(query, 0, sizeof(*query));
3532 }
3533
3534 /** Parse the query using flex/bison or plugin parser.
3535 @return parse tree node. */
3536 static fts_ast_node_t *fts_query_parse(
3537 fts_query_t *query, /*!< in: query instance */
3538 byte *query_str, /*!< in: query string */
3539 ulint query_len) /*!< in: query string length */
3540 {
3541 int error;
3542 fts_ast_state_t state;
3543 bool mode = query->boolean_mode;
3544 DBUG_TRACE;
3545
3546 memset(&state, 0x0, sizeof(state));
3547
3548 state.charset = query->fts_index_table.charset;
3549
3550 DBUG_EXECUTE_IF("fts_instrument_query_disable_parser",
3551 query->parser = nullptr;);
3552
3553 if (query->parser) {
3554 state.root = state.cur_node = fts_ast_create_node_list(&state, nullptr);
3555 error =
3556 fts_parse_by_parser(mode, query_str, query_len, query->parser, &state);
3557 } else {
3558 /* Setup the scanner to use, this depends on the mode flag. */
3559 state.lexer = fts_lexer_create(mode, query_str, query_len);
3560 state.charset = query->fts_index_table.charset;
3561 error = fts_parse(&state);
3562 fts_lexer_free(state.lexer);
3563 state.lexer = nullptr;
3564 }
3565
3566 /* Error during parsing ? */
3567 if (error) {
3568 /* Free the nodes that were allocated during parsing. */
3569 fts_ast_state_free(&state);
3570 } else {
3571 query->root = state.root;
3572
3573 if (fts_enable_diag_print && query->root != nullptr) {
3574 fts_ast_node_print(query->root);
3575 }
3576 }
3577
3578 return state.root;
3579 }
3580
3581 /** FTS Query optimization
3582 Set FTS_OPT_RANKING if it is a simple term query */
3583 static void fts_query_can_optimize(
3584 fts_query_t *query, /*!< in/out: query instance */
3585 uint flags) /*!< In: FTS search mode */
3586 {
3587 fts_ast_node_t *node = query->root;
3588
3589 if (flags & FTS_EXPAND) {
3590 return;
3591 }
3592
3593 /* Check if it has only a term without oper */
3594 ut_ad(node->type == FTS_AST_LIST);
3595 node = node->list.head;
3596 if (node != nullptr && node->type == FTS_AST_TERM && node->next == nullptr) {
3597 query->flags = FTS_OPT_RANKING;
3598 }
3599 }
3600
3601 /** FTS Query entry point.
3602 @param[in] trx transaction
3603 @param[in] index fts index to search
3604 @param[in] flags FTS search mode
3605 @param[in] query_str FTS query
3606 @param[in] query_len FTS query string len in bytes
3607 @param[in,out] result result doc ids
3608 @param[in] limit limit value
3609 @return DB_SUCCESS if successful otherwise error code */
3610 dberr_t fts_query(trx_t *trx, dict_index_t *index, uint flags,
3611 const byte *query_str, ulint query_len, fts_result_t **result,
3612 ulonglong limit) {
3613 fts_query_t query;
3614 dberr_t error = DB_SUCCESS;
3615 byte *lc_query_str;
3616 ulint lc_query_str_len;
3617 ulint result_len;
3618 bool boolean_mode;
3619 trx_t *query_trx;
3620 CHARSET_INFO *charset;
3621 bool will_be_ignored = false;
3622
3623 boolean_mode = flags & FTS_BOOL;
3624
3625 *result = nullptr;
3626 memset(&query, 0x0, sizeof(query));
3627 query_trx = trx_allocate_for_background();
3628 query_trx->op_info = "FTS query";
3629
3630 const auto start_time = std::chrono::steady_clock::now();
3631
3632 query.trx = query_trx;
3633 query.index = index;
3634 query.boolean_mode = boolean_mode;
3635 query.deleted = fts_doc_ids_create();
3636 query.cur_node = nullptr;
3637
3638 query.fts_common_table.type = FTS_COMMON_TABLE;
3639 query.fts_common_table.table_id = index->table->id;
3640 query.fts_common_table.parent = index->table->name.m_name;
3641 query.fts_common_table.table = index->table;
3642
3643 charset = fts_index_get_charset(index);
3644
3645 query.fts_index_table.type = FTS_INDEX_TABLE;
3646 query.fts_index_table.index_id = index->id;
3647 query.fts_index_table.table_id = index->table->id;
3648 query.fts_index_table.parent = index->table->name.m_name;
3649 query.fts_index_table.charset = charset;
3650 query.fts_index_table.table = index->table;
3651
3652 query.word_map =
3653 rbt_create_arg_cmp(sizeof(fts_string_t), innobase_fts_text_cmp, charset);
3654 query.word_vector = ut::new_withkey<word_vector_t>(UT_NEW_THIS_FILE_PSI_KEY);
3655 query.error = DB_SUCCESS;
3656
3657 /* Setup the RB tree that will be used to collect per term
3658 statistics. */
3659 query.word_freqs = rbt_create_arg_cmp(sizeof(fts_word_freq_t),
3660 innobase_fts_text_cmp, charset);
3661
3662 if (flags & FTS_EXPAND) {
3663 query.wildcard_words = rbt_create_arg_cmp(sizeof(fts_string_t),
3664 innobase_fts_text_cmp, charset);
3665 }
3666
3667 query.total_size += SIZEOF_RBT_CREATE;
3668
3669 query.total_docs = dict_table_get_n_rows(index->table);
3670
3671 query.limit = limit;
3672
3673 query.n_docs = 0;
3674
3675 query.fts_common_table.suffix = FTS_SUFFIX_DELETED;
3676
3677 /* Read the deleted doc_ids, we need these for filtering. */
3678 error =
3679 fts_table_fetch_doc_ids(nullptr, &query.fts_common_table, query.deleted);
3680
3681 if (error != DB_SUCCESS) {
3682 goto func_exit;
3683 }
3684
3685 query.fts_common_table.suffix = FTS_SUFFIX_DELETED_CACHE;
3686
3687 error =
3688 fts_table_fetch_doc_ids(nullptr, &query.fts_common_table, query.deleted);
3689
3690 if (error != DB_SUCCESS) {
3691 goto func_exit;
3692 }
3693
3694 /* Get the deleted doc ids that are in the cache. */
3695 fts_cache_append_deleted_doc_ids(index->table->fts->cache,
3696 query.deleted->doc_ids);
3697 DEBUG_SYNC_C("fts_deleted_doc_ids_append");
3698
3699 /* Sort the vector so that we can do a binary search over the ids. */
3700 ib_vector_sort(query.deleted->doc_ids, fts_doc_id_field_cmp<fts_update_t>);
3701
3702 /* Convert the query string to lower case before parsing. We own
3703 the ut_malloc'ed result and so remember to free it before return. */
3704
3705 lc_query_str_len = query_len * charset->casedn_multiply + charset->mbmaxlen;
3706 lc_query_str = static_cast<byte *>(
3707 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, lc_query_str_len));
3708
3709 /* For binary collations, a case sensitive search is
3710 performed. Hence don't convert to lower case. */
3711 if (my_binary_compare(charset)) {
3712 memcpy(lc_query_str, query_str, query_len);
3713 lc_query_str[query_len] = 0;
3714 result_len = query_len;
3715 } else {
3716 result_len =
3717 innobase_fts_casedn_str(charset, (char *)query_str, query_len,
3718 (char *)lc_query_str, lc_query_str_len);
3719 }
3720 ut_ad(result_len < lc_query_str_len);
3721
3722 lc_query_str[result_len] = 0;
3723
3724 query.heap = mem_heap_create(128, UT_LOCATION_HERE);
3725
3726 /* Create the rb tree for the doc id (current) set. */
3727 query.doc_ids = rbt_create(sizeof(fts_ranking_t), fts_ranking_doc_id_cmp);
3728 query.parser = index->parser;
3729
3730 query.total_size += SIZEOF_RBT_CREATE;
3731
3732 /* Parse the input query string. */
3733 if (fts_query_parse(&query, lc_query_str, result_len)) {
3734 fts_ast_node_t *ast = query.root;
3735 ast->trx = trx;
3736 /* Optimize query to check if it's a single term */
3737 fts_query_can_optimize(&query, flags);
3738
3739 DBUG_EXECUTE_IF("fts_instrument_result_cache_limit",
3740 fts_result_cache_limit = 2048;);
3741
3742 /* Optimisation is allowed for limit value
3743 when
3744 i) No ranking involved
3745 ii) Only FTS Union operations involved. */
3746 if (query.limit != ULONG_UNDEFINED && !fts_ast_node_check_union(ast)) {
3747 query.limit = ULONG_UNDEFINED;
3748 }
3749
3750 DBUG_EXECUTE_IF("fts_union_limit_off", query.limit = ULONG_UNDEFINED;);
3751
3752 /* Traverse the Abstract Syntax Tree (AST) and execute
3753 the query. */
3754 query.error = fts_ast_visit(FTS_NONE, ast, fts_query_visitor, &query,
3755 &will_be_ignored);
3756 if (query.error == DB_INTERRUPTED) {
3757 ut::free(lc_query_str);
3758 error = DB_INTERRUPTED;
3759 goto func_exit;
3760 }
3761 /* If query expansion is requested, extend the search
3762 with first search pass result */
3763 if (query.error == DB_SUCCESS && (flags & FTS_EXPAND)) {
3764 query.error = fts_expand_query(index, &query);
3765 }
3766
3767 /* Calculate the inverse document frequency of the terms. */
3768 if (query.error == DB_SUCCESS && query.flags != FTS_OPT_RANKING) {
3769 fts_query_calculate_idf(&query);
3770 }
3771
3772 /* Copy the result from the query state, so that we can
3773 return it to the caller. */
3774 if (query.error == DB_SUCCESS) {
3775 *result = fts_query_get_result(&query, *result);
3776 }
3777 if (trx_is_interrupted(trx)) {
3778 ut::free(lc_query_str);
3779 if (result != nullptr) {
3780 fts_query_free_result(*result);
3781 }
3782 error = DB_INTERRUPTED;
3783 goto func_exit;
3784 }
3785 error = query.error;
3786 } else {
3787 /* still return an empty result set */
3788 *result = static_cast<fts_result_t *>(
3789 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, sizeof(**result)));
3790 }
3791
3792 ut::free(lc_query_str);
3793
3794 if (fts_enable_diag_print && (*result)) {
3795 const auto diff_time =
3796 std::chrono::duration_cast<std::chrono::milliseconds>(
3797 std::chrono::steady_clock::now() - start_time)
3798 .count();
3799
3800 ib::info(ER_IB_MSG_516)
3801 << "FTS Search Processing time: " << diff_time / 1000
3802 << " secs: " << diff_time % 1000 << " millisec: row(s) "
3803 << ((*result)->rankings_by_id ? rbt_size((*result)->rankings_by_id)
3804 : -1);
3805
3806 /* Log memory consumption & result size */
3807 ib::info(ER_IB_MSG_517)
3808 << "Full Search Memory: " << query.total_size << " (bytes), Row: "
3809 << ((*result)->rankings_by_id ? rbt_size((*result)->rankings_by_id) : 0)
3810 << ".";
3811 }
3812
3813 func_exit:
3814 fts_query_free(&query);
3815
3816 trx_free_for_background(query_trx);
3817
3818 return (error);
3819 }
3820
3821 /** FTS Query free result, returned by fts_query(). */
3822 void fts_query_free_result(
3823 fts_result_t *result) /*!< in: result instance to free.*/
3824 {
3825 if (result) {
3826 if (result->rankings_by_id != nullptr) {
3827 rbt_free(result->rankings_by_id);
3828 result->rankings_by_id = nullptr;
3829 }
3830 if (result->rankings_by_rank != nullptr) {
3831 rbt_free(result->rankings_by_rank);
3832 result->rankings_by_rank = nullptr;
3833 }
3834
3835 ut::free(result);
3836 result = nullptr;
3837 }
3838 }
3839
3840 /** FTS Query sort result, returned by fts_query() on fts_ranking_t::rank. */
3841 void fts_query_sort_result_on_rank(
3842 fts_result_t *result) /*!< out: result instance to sort.*/
3843 {
3844 const ib_rbt_node_t *node;
3845 ib_rbt_t *ranked;
3846
3847 ut_a(result->rankings_by_id != nullptr);
3848 if (result->rankings_by_rank) {
3849 rbt_free(result->rankings_by_rank);
3850 }
3851
3852 ranked = rbt_create(sizeof(fts_ranking_t), fts_query_compare_rank);
3853
3854 /* We need to free any instances of fts_doc_freq_t that we
3855 may have allocated. */
3856 for (node = rbt_first(result->rankings_by_id); node;
3857 node = rbt_next(result->rankings_by_id, node)) {
3858 fts_ranking_t *ranking;
3859
3860 ranking = rbt_value(fts_ranking_t, node);
3861
3862 ut_a(ranking->words == nullptr);
3863
3864 rbt_insert(ranked, ranking, ranking);
3865 }
3866
3867 /* Reset the current node too. */
3868 result->current = nullptr;
3869 result->rankings_by_rank = ranked;
3870 }
3871
3872 /** A debug function to print result doc_id set. */
3873 static void fts_print_doc_id(
3874 fts_query_t *query) /*!< in : tree that stores doc_ids.*/
3875 {
3876 const ib_rbt_node_t *node;
3877
3878 /* Iterate each member of the doc_id set */
3879 for (node = rbt_first(query->doc_ids); node;
3880 node = rbt_next(query->doc_ids, node)) {
3881 fts_ranking_t *ranking;
3882 ranking = rbt_value(fts_ranking_t, node);
3883
3884 ib::info(ER_IB_MSG_518) << "doc_ids info, doc_id: " << ranking->doc_id;
3885
3886 ulint pos = 0;
3887 fts_string_t word;
3888
3889 while (fts_ranking_words_get_next(query, ranking, &pos, &word)) {
3890 ib::info(ER_IB_MSG_519) << "doc_ids info, value: " << word.f_str;
3891 }
3892 }
3893 }
3894
3895 /** This function implements a simple "blind" query expansion search:
3896 words in documents found in the first search pass will be used as
3897 search arguments to search the document again, thus "expand"
3898 the search result set.
3899 @return DB_SUCCESS if success, otherwise the error code */
3900 [[nodiscard]] static dberr_t fts_expand_query(
3901 dict_index_t *index, /*!< in: FTS index to search */
3902 fts_query_t *query) /*!< in: FTS query instance */
3903 {
3904 const ib_rbt_node_t *node;
3905 const ib_rbt_node_t *token_node;
3906 fts_doc_t result_doc;
3907 dberr_t error = DB_SUCCESS;
3908 const fts_index_cache_t *index_cache;
3909
3910 /* If no doc is found in first search pass, return */
3911 if (!rbt_size(query->doc_ids)) {
3912 return (error);
3913 }
3914
3915 /* Init "result_doc", to hold words from the first search pass */
3916 fts_doc_init(&result_doc);
3917
3918 rw_lock_x_lock(&index->table->fts->cache->lock, UT_LOCATION_HERE);
3919 index_cache = fts_find_index_cache(index->table->fts->cache, index);
3920 rw_lock_x_unlock(&index->table->fts->cache->lock);
3921
3922 ut_a(index_cache);
3923
3924 result_doc.tokens = rbt_create_arg_cmp(
3925 sizeof(fts_token_t), innobase_fts_text_cmp, index_cache->charset);
3926
3927 result_doc.charset = index_cache->charset;
3928 result_doc.parser = index_cache->index->parser;
3929 result_doc.is_ngram = index_cache->index->is_ngram;
3930
3931 query->total_size += SIZEOF_RBT_CREATE;
3932
3933 if (fts_enable_diag_print) {
3934 fts_print_doc_id(query);
3935 }
3936
3937 for (node = rbt_first(query->doc_ids); node;
3938 node = rbt_next(query->doc_ids, node)) {
3939 fts_ranking_t *ranking;
3940 ulint prev_token_size;
3941 ulint estimate_size;
3942
3943 prev_token_size = rbt_size(result_doc.tokens);
3944
3945 ranking = rbt_value(fts_ranking_t, node);
3946
3947 /* Fetch the documents with the doc_id from the
3948 result of first search pass. Since we do not
3949 store document-to-word mapping, we need to
3950 fetch the original document and parse them.
3951 Future optimization could be done here if we
3952 support some forms of document-to-word mapping */
3953 fts_doc_fetch_by_doc_id(nullptr, ranking->doc_id, index,
3954 FTS_FETCH_DOC_BY_ID_EQUAL,
3955 fts_query_expansion_fetch_doc, &result_doc);
3956
3957 /* Estimate memory used, see fts_process_token and fts_token_t.
3958 We ignore token size here. */
3959 estimate_size = (rbt_size(result_doc.tokens) - prev_token_size) *
3960 (SIZEOF_RBT_NODE_ADD + sizeof(fts_token_t) +
3961 sizeof(ib_vector_t) + sizeof(ulint) * 32);
3962 query->total_size += estimate_size;
3963
3964 if (query->total_size > fts_result_cache_limit) {
3965 error = DB_FTS_EXCEED_RESULT_CACHE_LIMIT;
3966 goto func_exit;
3967 }
3968 }
3969
3970 /* Remove words that have already been searched in the first pass */
3971 for (ulint i = 0; i < query->word_vector->size(); i++) {
3972 fts_string_t word = query->word_vector->at(i);
3973 ib_rbt_bound_t parent;
3974
3975 if (query->wildcard_words &&
3976 rbt_search(query->wildcard_words, &parent, &word) == 0) {
3977 /* If it's a wildcard word, remove words having
3978 it as prefix. */
3979 while (rbt_search_cmp(result_doc.tokens, &parent, &word, nullptr,
3980 innobase_fts_text_cmp_prefix) == 0) {
3981 ut::free(rbt_remove_node(result_doc.tokens, parent.last));
3982 }
3983 } else {
3984 /* We don't check return value, because the word may
3985 have been deleted by a previous wildcard word as its
3986 prefix, e.g. ('g * good'). */
3987 rbt_delete(result_doc.tokens, &word);
3988 }
3989 }
3990
3991 /* Search the table the second time with expanded search list */
3992 for (token_node = rbt_first(result_doc.tokens); token_node;
3993 token_node = rbt_next(result_doc.tokens, token_node)) {
3994 fts_token_t *mytoken;
3995 mytoken = rbt_value(fts_token_t, token_node);
3996
3997 /* '%' in the end is treated as prefix search,
3998 it can cause assert failure, so we skip it. */
3999 if (mytoken->text.f_str[mytoken->text.f_len - 1] == '%') {
4000 continue;
4001 }
4002
4003 ut_ad(mytoken->text.f_str[mytoken->text.f_len] == 0);
4004 fts_query_add_word_freq(query, &mytoken->text);
4005 error = fts_query_union(query, &mytoken->text);
4006
4007 if (error != DB_SUCCESS) {
4008 break;
4009 }
4010 }
4011
4012 func_exit:
4013 fts_doc_free(&result_doc);
4014
4015 return (error);
4016 }
4017
4018 /** This function finds documents that contain all words in a
4019 phrase or proximity search. And if proximity search, verify
4020 the words are close enough to each other, as in specified distance.
4021 This function is called for phrase and proximity search.
4022 Expects the match list for each token (query->match_array),
4023 to be sorted in increasing order of doc_id.
4024 @return true if documents are found, false if otherwise */
4025 static bool fts_search_docs_containing_all_tokens(
4026 fts_query_t *query, /*!< in/out: query instance.
4027 query->doc_ids might be instantiated
4028 with qualified doc IDs.
4029 For phrase search,
4030 query->match_array[0] will be modified.
4031 Documents matching only the 0th token but
4032 not the others (i.e. document doesn't match)
4033 will have their doc_id set to FTS_NULL_DOC_ID. */
4034 ib_vector_t *tokens) /*!< in: Tokens contain words */
4035 {
4036 bool matched = false;
4037 const Vector_wrapper<fts_string_t> tokens_v(*tokens);
4038 const size_t num_tokens = tokens_v.size();
4039 fts_match_t *match[MAX_PROXIMITY_ITEM];
4040
4041 Vector_wrapper<fts_match_t> matches_of_0th_token(*query->match_array[0]);
4042
4043 for (size_t j = 0; j < num_tokens; ++j) {
4044 match[j] = Vector_wrapper<fts_match_t>(*query->match_array[j]).begin();
4045 }
4046
4047 /* We have a set of match list for each word, and we expect
4048 these lists to be sorted in increasing order of doc_id, we shall
4049 walk through the list and find common documents that
4050 contain all the matching words. */
4051 for (; match[0] < matches_of_0th_token.end(); match[0]++) {
4052 ulint j;
4053 fts_proximity_t qualified_pos;
4054
4055 /* For remaining match list for the token(word), we
4056 try to see if there is a document with the same
4057 doc id */
4058 for (j = 1; j < num_tokens; j++) {
4059 Vector_wrapper<fts_match_t> matches_of_jth_token(*query->match_array[j]);
4060
4061 /* Loop until we exhaust the list or find a doc_id which
4062 is equal or greater than match[0]->doc_id */
4063 while (match[j] < matches_of_jth_token.end() &&
4064 match[0]->doc_id > match[j]->doc_id) {
4065 match[j]++;
4066 }
4067
4068 /* Once we reach end of any of the word list, we will not
4069 find any greater doc_id which will contain this word.
4070 We can stop our search at this point. */
4071 if (match[j] == matches_of_jth_token.end()) {
4072 if (query->flags & FTS_PHRASE) {
4073 /* The i-th doc_id from match_array[0] is greater than any in
4074 match_array[j]. As the arrays are sorted it guarantees no further
4075 match. */
4076 while (match[0] < matches_of_0th_token.end()) {
4077 match[0]->doc_id = FTS_NULL_DOC_ID;
4078 match[0]++;
4079 }
4080 }
4081
4082 return matched;
4083 }
4084
4085 if (match[0]->doc_id < match[j]->doc_id) {
4086 /* no match */
4087 if (query->flags & FTS_PHRASE) {
4088 match[0]->doc_id = FTS_NULL_DOC_ID;
4089 }
4090 break;
4091 }
4092 }
4093
4094 if (j != num_tokens) {
4095 continue;
4096 }
4097
4098 /* For this matching doc, we need to further
4099 verify whether the words in the doc are close
4100 to each other, and within the distance specified
4101 in the proximity search */
4102 if (query->flags & FTS_PHRASE) {
4103 matched = true;
4104 } else if (fts_proximity_get_positions(match, num_tokens, ULINT_MAX,
4105 &qualified_pos)) {
4106 /* Fetch the original documents and count the
4107 words in between matching words to see that is in
4108 specified distance */
4109 if (fts_query_is_in_proximity_range(query, match, &qualified_pos)) {
4110 /* If so, mark we find a matching doc */
4111 query->error = fts_query_process_doc_id(query, match[0]->doc_id, 0);
4112 if (query->error != DB_SUCCESS) {
4113 return false;
4114 }
4115
4116 matched = true;
4117 for (const auto &token : tokens_v) {
4118 fts_query_add_word_to_document(query, match[0]->doc_id, &token);
4119 }
4120 }
4121 }
4122 }
4123 return (matched);
4124 }
4125
4126 /** This function checks whether words in result documents are close to
4127 each other (within proximity range as specified by "distance").
4128 If "distance" is MAX_ULINT, then it will find all combinations of
4129 positions of matching words and store min and max positions
4130 in the "qualified_pos" for later verification.
4131 @return true if words are close to each other, false if otherwise */
4132 static bool fts_proximity_get_positions(
4133 fts_match_t **match, /*!< in: query instance */
4134 ulint num_match, /*!< in: number of matching
4135 items */
4136 ulint distance, /*!< in: distance value
4137 for proximity search */
4138 fts_proximity_t *qualified_pos) /*!< out: the position info
4139 records ranges containing
4140 all matching words. */
4141 {
4142 ulint i;
4143 ulint idx[MAX_PROXIMITY_ITEM];
4144 ulint num_pos[MAX_PROXIMITY_ITEM];
4145 ulint min_idx;
4146
4147 qualified_pos->n_pos = 0;
4148
4149 ut_a(num_match <= MAX_PROXIMITY_ITEM);
4150
4151 /* Each word could appear multiple times in a doc. So
4152 we need to walk through each word's position list, and find
4153 closest distance between different words to see if
4154 they are in the proximity distance. */
4155
4156 /* Assume each word's position list is sorted, we
4157 will just do a walk through to all words' lists
4158 similar to a the merge phase of a merge sort */
4159 for (i = 0; i < num_match; i++) {
4160 /* idx is the current position we are checking
4161 for a particular word */
4162 idx[i] = 0;
4163
4164 /* Number of positions for this word */
4165 num_pos[i] = ib_vector_size(match[i]->positions);
4166 }
4167
4168 /* Start with the first word */
4169 min_idx = 0;
4170
4171 while (idx[min_idx] < num_pos[min_idx]) {
4172 ulint position[MAX_PROXIMITY_ITEM];
4173 ulint min_pos = ULINT_MAX;
4174 ulint max_pos = 0;
4175
4176 /* Check positions in each word position list, and
4177 record the max/min position */
4178 for (i = 0; i < num_match; i++) {
4179 position[i] = *(ulint *)ib_vector_get_const(match[i]->positions, idx[i]);
4180
4181 if (position[i] == ULINT_UNDEFINED) {
4182 break;
4183 }
4184
4185 if (position[i] < min_pos) {
4186 min_pos = position[i];
4187 min_idx = i;
4188 }
4189
4190 if (position[i] > max_pos) {
4191 max_pos = position[i];
4192 }
4193 }
4194
4195 /* If max and min position are within range, we
4196 find a good match */
4197 if (max_pos - min_pos <= distance &&
4198 (i >= num_match || position[i] != ULINT_UNDEFINED)) {
4199 /* The charset has variable character
4200 length encoding, record the min_pos and
4201 max_pos, we will need to verify the actual
4202 number of characters */
4203 qualified_pos->min_pos.push_back(min_pos);
4204 qualified_pos->max_pos.push_back(max_pos);
4205 qualified_pos->n_pos++;
4206 }
4207
4208 /* Otherwise, move to the next position is the
4209 list for the word with the smallest position */
4210 idx[min_idx]++;
4211 }
4212
4213 return (qualified_pos->n_pos != 0);
4214 }