xapian-core  1.4.27
termgenerator_internal.cc
Go to the documentation of this file.
1 
4 /* Copyright (C) 2007-2023 Olly Betts
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include <config.h>
22 
23 #include "termgenerator_internal.h"
24 
25 #include "api/omenquireinternal.h"
26 #include "api/queryinternal.h"
27 
28 #include <xapian/document.h>
29 #include <xapian/queryparser.h>
30 #include <xapian/stem.h>
31 #include <xapian/unicode.h>
32 
33 #include "stringutils.h"
34 
35 #include <algorithm>
36 #include <cmath>
37 #include <deque>
38 #include <limits>
39 #include <list>
40 #include <string>
41 #include <unordered_map>
42 #include <vector>
43 
44 #include "word-breaker.h"
45 
46 using namespace std;
47 
48 namespace Xapian {
49 
50 static inline bool
51 U_isupper(unsigned ch)
52 {
53  return ch < 128 && C_isupper(static_cast<unsigned char>(ch));
54 }
55 
56 static inline unsigned
57 check_wordchar(unsigned ch)
58 {
59  if (Unicode::is_wordchar(ch)) return Unicode::tolower(ch);
60  return 0;
61 }
62 
63 static inline bool
64 should_stem(const std::string & term)
65 {
66  const unsigned int SHOULD_STEM_MASK =
70  (1 << Unicode::OTHER_LETTER);
71  Utf8Iterator u(term);
72  return ((SHOULD_STEM_MASK >> Unicode::get_category(*u)) & 1);
73 }
74 
78 static const unsigned UNICODE_IGNORE = numeric_limits<unsigned>::max();
79 
80 static inline unsigned
81 check_infix(unsigned ch)
82 {
83  if (ch == '\'' || ch == '&' || ch == 0xb7 || ch == 0x5f4 || ch == 0x2027) {
84  // Unicode includes all these except '&' in its word boundary rules,
85  // as well as 0x2019 (which we handle below) and ':' (for Swedish
86  // apparently, but we ignore this for now as it's problematic in
87  // real world cases).
88  return ch;
89  }
90  // 0x2019 is Unicode apostrophe and single closing quote.
91  // 0x201b is Unicode single opening quote with the tail rising.
92  if (ch == 0x2019 || ch == 0x201b) return '\'';
93  if (ch >= 0x200b && (ch <= 0x200d || ch == 0x2060 || ch == 0xfeff))
94  return UNICODE_IGNORE;
95  return 0;
96 }
97 
98 static inline unsigned
99 check_infix_digit(unsigned ch)
100 {
101  // This list of characters comes from Unicode's word identifying algorithm.
102  switch (ch) {
103  case ',':
104  case '.':
105  case ';':
106  case 0x037e: // GREEK QUESTION MARK
107  case 0x0589: // ARMENIAN FULL STOP
108  case 0x060D: // ARABIC DATE SEPARATOR
109  case 0x07F8: // NKO COMMA
110  case 0x2044: // FRACTION SLASH
111  case 0xFE10: // PRESENTATION FORM FOR VERTICAL COMMA
112  case 0xFE13: // PRESENTATION FORM FOR VERTICAL COLON
113  case 0xFE14: // PRESENTATION FORM FOR VERTICAL SEMICOLON
114  return ch;
115  }
116  if (ch >= 0x200b && (ch <= 0x200d || ch == 0x2060 || ch == 0xfeff))
117  return UNICODE_IGNORE;
118  return 0;
119 }
120 
121 static inline bool
122 is_digit(unsigned ch) {
124 }
125 
126 static inline unsigned
127 check_suffix(unsigned ch)
128 {
129  if (ch == '+' || ch == '#') return ch;
130  // FIXME: what about '-'?
131  return 0;
132 }
133 
140 template<typename ACTION>
141 static void
142 parse_terms(Utf8Iterator itor, bool try_word_break, bool with_positions,
143  ACTION action)
144 {
145  while (true) {
146  // Advance to the start of the next term.
147  unsigned ch;
148  while (true) {
149  if (itor == Utf8Iterator()) return;
150  ch = check_wordchar(*itor);
151  if (ch) break;
152  ++itor;
153  }
154 
155  string term;
156  // Look for initials separated by '.' (e.g. P.T.O., U.N.C.L.E).
157  // Don't worry if there's a trailing '.' or not.
158  if (U_isupper(*itor)) {
159  const Utf8Iterator end;
160  Utf8Iterator p = itor;
161  do {
163  } while (p != end && *p == '.' && ++p != end && U_isupper(*p));
164  // One letter does not make an acronym! If we handled a single
165  // uppercase letter here, we wouldn't catch M&S below.
166  if (term.size() > 1) {
167  // Check there's not a (lower case) letter or digit
168  // immediately after it.
169  if (p == end || !Unicode::is_wordchar(*p)) {
170  itor = p;
171  goto endofterm;
172  }
173  }
174  term.resize(0);
175  }
176 
177  while (true) {
178  if (try_word_break &&
179  is_unbroken_script(*itor) &&
180  Unicode::is_wordchar(*itor)) {
181  NgramIterator tk(itor);
182  while (tk != NgramIterator()) {
183  const string& ngram = *tk;
184  if (!action(ngram, with_positions && tk.unigram(),
185  tk.get_utf8iterator()))
186  return;
187  ++tk;
188  }
189  // Update itor to end of CJK text span.
190  itor = tk.get_utf8iterator();
191  while (true) {
192  if (itor == Utf8Iterator()) return;
193  ch = check_wordchar(*itor);
194  if (ch) break;
195  ++itor;
196  }
197  continue;
198  }
199  unsigned prevch;
200  do {
201  Unicode::append_utf8(term, ch);
202  prevch = ch;
203  if (++itor == Utf8Iterator() ||
204  (try_word_break && is_unbroken_script(*itor)))
205  goto endofterm;
206  ch = check_wordchar(*itor);
207  } while (ch);
208 
209  Utf8Iterator next(itor);
210  ++next;
211  if (next == Utf8Iterator()) break;
212  unsigned nextch = check_wordchar(*next);
213  if (!nextch) break;
214  unsigned infix_ch = *itor;
215  if (is_digit(prevch) && is_digit(*next)) {
216  infix_ch = check_infix_digit(infix_ch);
217  } else {
218  // Handle things like '&' in AT&T, apostrophes, etc.
219  infix_ch = check_infix(infix_ch);
220  }
221  if (!infix_ch) break;
222  if (infix_ch != UNICODE_IGNORE)
223  Unicode::append_utf8(term, infix_ch);
224  ch = nextch;
225  itor = next;
226  }
227 
228  {
229  size_t len = term.size();
230  unsigned count = 0;
231  while ((ch = check_suffix(*itor))) {
232  if (++count > 3) {
233  term.resize(len);
234  break;
235  }
236  Unicode::append_utf8(term, ch);
237  if (++itor == Utf8Iterator()) goto endofterm;
238  }
239  // Don't index fish+chips as fish+ chips.
240  if (Unicode::is_wordchar(*itor))
241  term.resize(len);
242  }
243 
244 endofterm:
245  if (!action(term, with_positions, itor))
246  return;
247  }
248 }
249 
250 void
251 TermGenerator::Internal::index_text(Utf8Iterator itor, termcount wdf_inc,
252  const string & prefix, bool with_positions)
253 {
254  bool try_word_break = (flags & FLAG_NGRAMS) || is_ngram_enabled();
255 
256  stop_strategy current_stop_mode;
257  if (!stopper.get()) {
258  current_stop_mode = TermGenerator::STOP_NONE;
259  } else {
260  current_stop_mode = stop_mode;
261  }
262 
263  parse_terms(itor, try_word_break, with_positions,
264  [=
265 #if __cplusplus >= 201907L
266 // C++20 no longer supports implicit `this` in lambdas but older C++ versions
267 // don't allow `this` here.
268  , this
269 #endif
270  ](const string & term, bool positional, const Utf8Iterator &) {
271  if (term.size() > max_word_length) return true;
272 
273  if (current_stop_mode == TermGenerator::STOP_ALL &&
274  (*stopper)(term)) {
275  return true;
276  }
277 
278  if (strategy == TermGenerator::STEM_SOME ||
279  strategy == TermGenerator::STEM_NONE ||
280  strategy == TermGenerator::STEM_SOME_FULL_POS) {
281  if (positional) {
282  doc.add_posting(prefix + term, ++cur_pos, wdf_inc);
283  } else {
284  doc.add_term(prefix + term, wdf_inc);
285  }
286  }
287 
288  // MSVC seems to need "this->" on member variables in this
289  // situation.
290  if ((this->flags & FLAG_SPELLING) && prefix.empty())
291  db.add_spelling(term);
292 
293  if (strategy == TermGenerator::STEM_NONE || stemmer.is_none())
294  return true;
295 
296  if (strategy == TermGenerator::STEM_SOME ||
297  strategy == TermGenerator::STEM_SOME_FULL_POS) {
298  if (current_stop_mode == TermGenerator::STOP_STEMMED &&
299  (*stopper)(term))
300  return true;
301 
302  // Note, this uses the lowercased term, but that's OK as we
303  // only want to avoid stemming terms starting with a digit.
304  if (!should_stem(term)) return true;
305  }
306 
307  // Add stemmed form without positional information.
308  const string& stem = stemmer(term);
309  if (rare(stem.empty())) return true;
310  string stemmed_term;
311  if (strategy != TermGenerator::STEM_ALL) {
312  stemmed_term += "Z";
313  }
314  stemmed_term += prefix;
315  stemmed_term += stem;
316  if (strategy != TermGenerator::STEM_SOME && with_positions) {
317  if (strategy != TermGenerator::STEM_SOME_FULL_POS) ++cur_pos;
318  doc.add_posting(stemmed_term, cur_pos, wdf_inc);
319  } else {
320  doc.add_term(stemmed_term, wdf_inc);
321  }
322  return true;
323  });
324 }
325 
326 struct Sniplet {
327  double* relevance;
328 
329  size_t term_end;
330 
331  size_t highlight;
332 
333  Sniplet(double* r, size_t t, size_t h)
334  : relevance(r), term_end(t), highlight(h) { }
335 };
336 
337 class SnipPipe {
338  deque<Sniplet> pipe;
339  deque<Sniplet> best_pipe;
340 
341  // Requested length for snippet.
342  size_t length;
343 
344  // Position in text of start of current pipe contents.
345  size_t begin = 0;
346 
347  // Rolling sum of the current pipe contents.
348  double sum = 0;
349 
350  size_t phrase_len = 0;
351 
352  public:
353  size_t best_begin = 0;
354 
355  size_t best_end = 0;
356 
357  double best_sum = 0;
358 
359  // Add one to length to allow for inter-word space.
360  // FIXME: We ought to correctly allow for multiple spaces.
361  explicit SnipPipe(size_t length_) : length(length_ + 1) { }
362 
363  bool pump(double* r, size_t t, size_t h, unsigned flags);
364 
365  void done();
366 
367  bool drain(const string & input,
368  const string & hi_start,
369  const string & hi_end,
370  const string & omit,
371  string & output);
372 };
373 
374 #define DECAY 2.0
375 
376 inline bool
377 SnipPipe::pump(double* r, size_t t, size_t h, unsigned flags)
378 {
379  if (h > 1) {
380  if (pipe.size() >= h - 1) {
381  // The final term of a phrase is entering the window. Peg the
382  // phrase's relevance onto the first term of the phrase, so it'll
383  // be removed from `sum` when the phrase starts to leave the
384  // window.
385  auto & phrase_start = pipe[pipe.size() - (h - 1)];
386  if (phrase_start.relevance) {
387  *phrase_start.relevance *= DECAY;
388  sum -= *phrase_start.relevance;
389  }
390  sum += *r;
391  phrase_start.relevance = r;
392  phrase_start.highlight = h;
393  *r /= DECAY;
394  }
395  r = NULL;
396  h = 0;
397  }
398  pipe.emplace_back(r, t, h);
399  if (r) {
400  sum += *r;
401  *r /= DECAY;
402  }
403 
404  // If necessary, discard words from the start of the pipe until it has the
405  // desired length.
406  // FIXME: Also shrink the window past words with relevance < 0?
407  while (t - begin > length /* || pipe.front().relevance < 0.0 */) {
408  const Sniplet& word = pipe.front();
409  if (word.relevance) {
410  *word.relevance *= DECAY;
411  sum -= *word.relevance;
412  }
413  begin = word.term_end;
414  if (best_end >= begin)
415  best_pipe.push_back(word);
416  pipe.pop_front();
417  // E.g. can happen if the current term is longer than the requested
418  // length!
419  if (rare(pipe.empty())) break;
420  }
421 
422  // Using > here doesn't work well, as we don't extend a snippet over terms
423  // with 0 weight.
424  if (sum >= best_sum) {
425  // Discard any part of `best_pipe` which is before `begin`.
426  if (begin >= best_end) {
427  best_pipe.clear();
428  } else {
429  while (!best_pipe.empty() &&
430  best_pipe.front().term_end <= begin) {
431  best_pipe.pop_front();
432  }
433  }
434  best_sum = sum;
435  best_begin = begin;
436  best_end = t;
437  } else if ((flags & Xapian::MSet::SNIPPET_EXHAUSTIVE) == 0) {
438  if (best_sum > 0 && best_end < begin) {
439  // We found something, and we aren't still looking near it.
440  // FIXME: Benchmark this and adjust if necessary.
441  return false;
442  }
443  }
444  return true;
445 }
446 
447 inline void
448 SnipPipe::done()
449 {
450  // Discard any part of `pipe` which is after `best_end`.
451  if (begin >= best_end) {
452  pipe.clear();
453  } else {
454  // We should never empty the pipe (as that case should be handled
455  // above).
456  while (rare(!pipe.empty()) &&
457  pipe.back().term_end > best_end) {
458  pipe.pop_back();
459  }
460  }
461 }
462 
463 // Check if a non-word character is should be included at the start of the
464 // snippet. We want to include certain leading non-word characters, but not
465 // others.
466 static inline bool
468  if (Unicode::is_currency(ch) ||
471  return true;
472  }
473  switch (ch) {
474  case '"':
475  case '#':
476  case '%':
477  case '&':
478  case '\'':
479  case '+':
480  case '-':
481  case '/':
482  case '<':
483  case '@':
484  case '\\':
485  case '`':
486  case '~':
487  case 0x00A1: // INVERTED EXCLAMATION MARK
488  case 0x00A7: // SECTION SIGN
489  case 0x00BF: // INVERTED QUESTION MARK
490  return true;
491  }
492  return false;
493 }
494 
495 // Check if a non-word character is should be included at the end of the
496 // snippet. We want to include certain trailing non-word characters, but not
497 // others.
498 static inline bool
500  if (Unicode::is_currency(ch) ||
503  return true;
504  }
505  switch (ch) {
506  case '"':
507  case '%':
508  case '\'':
509  case '+':
510  case '-':
511  case '/':
512  case '>':
513  case '@':
514  case '\\':
515  case '`':
516  case '~':
517  return true;
518  }
519  return false;
520 }
521 
522 static inline void
523 append_escaping_xml(const char* p, const char* end, string& output)
524 {
525  while (p != end) {
526  char ch = *p++;
527  switch (ch) {
528  case '&':
529  output += "&amp;";
530  break;
531  case '<':
532  output += "&lt;";
533  break;
534  case '>':
535  output += "&gt;";
536  break;
537  default:
538  output += ch;
539  }
540  }
541 }
542 
543 inline bool
544 SnipPipe::drain(const string & input,
545  const string & hi_start,
546  const string & hi_end,
547  const string & omit,
548  string & output)
549 {
550  if (best_pipe.empty() && !pipe.empty()) {
551  swap(best_pipe, pipe);
552  }
553 
554  if (best_pipe.empty()) {
555  size_t tail_len = input.size() - best_end;
556  if (tail_len == 0) return false;
557 
558  // See if this is the end of a sentence.
559  // FIXME: This is quite simplistic - look at the Unicode rules:
560  // https://unicode.org/reports/tr29/#Sentence_Boundaries
561  bool sentence_end = false;
562  Utf8Iterator i(input.data() + best_end, tail_len);
563  while (i != Utf8Iterator()) {
564  unsigned ch = *i;
565  if (sentence_end && Unicode::is_whitespace(ch)) break;
566 
567  // Allow "...", "!!", "!?!", etc...
568  sentence_end = (ch == '.' || ch == '?' || ch == '!');
569 
570  if (Unicode::is_wordchar(ch)) break;
571  ++i;
572  }
573 
574  if (sentence_end) {
575  // Include end of sentence punctuation.
576  append_escaping_xml(input.data() + best_end, i.raw(), output);
577  return false;
578  }
579 
580  // Include trailing punctuation which includes meaning or context.
581  i.assign(input.data() + best_end, tail_len);
582  int trailing_punc = 0;
583  while (i != Utf8Iterator() && snippet_check_trailing_nonwordchar(*i)) {
584  // But limit how much trailing punctuation we include.
585  if (++trailing_punc > 4) {
586  trailing_punc = 0;
587  break;
588  }
589  ++i;
590  }
591  if (trailing_punc) {
592  append_escaping_xml(input.data() + best_end, i.raw(), output);
593  if (i == Utf8Iterator()) return false;
594  }
595 
596  // Append "..." or equivalent as this doesn't seem to be the start
597  // of a sentence.
598  output += omit;
599 
600  return false;
601  }
602 
603  const Sniplet & word = best_pipe.front();
604 
605  if (output.empty()) {
606  // Start of the snippet.
607  enum { NO, PUNC, YES } sentence_boundary = (best_begin == 0) ? YES : NO;
608 
609  Utf8Iterator i(input.data() + best_begin, word.term_end - best_begin);
610  while (i != Utf8Iterator()) {
611  unsigned ch = *i;
612  switch (sentence_boundary) {
613  case NO:
614  if (ch == '.' || ch == '?' || ch == '!') {
615  sentence_boundary = PUNC;
616  }
617  break;
618  case PUNC:
619  if (Unicode::is_whitespace(ch)) {
620  sentence_boundary = YES;
621  } else if (ch == '.' || ch == '?' || ch == '!') {
622  // Allow "...", "!!", "!?!", etc...
623  } else {
624  sentence_boundary = NO;
625  }
626  break;
627  case YES:
628  break;
629  }
630 
631  // Start the snippet at the start of the first word, but include
632  // certain punctuation too.
633  if (Unicode::is_wordchar(ch)) {
634  // But limit how much leading punctuation we include.
635  size_t word_begin = i.raw() - input.data();
636  if (word_begin - best_begin > 4) {
637  best_begin = word_begin;
638  }
639  break;
640  }
641  ++i;
643  best_begin = i.raw() - input.data();
644  }
645  }
646 
647  // Add "..." or equivalent if this doesn't seem to be the start of a
648  // sentence.
649  if (sentence_boundary != YES) {
650  output += omit;
651  }
652  }
653 
654  if (word.highlight) {
655  // Don't include inter-word characters in the highlight.
656  Utf8Iterator i(input.data() + best_begin, input.size() - best_begin);
657  while (i != Utf8Iterator()) {
658  unsigned ch = *i;
659  if (Unicode::is_wordchar(ch)) {
660  append_escaping_xml(input.data() + best_begin, i.raw(), output);
661  best_begin = i.raw() - input.data();
662  break;
663  }
664  ++i;
665  }
666  }
667 
668  if (!phrase_len) {
669  phrase_len = word.highlight;
670  if (phrase_len) output += hi_start;
671  }
672 
673  const char* p = input.data();
674  append_escaping_xml(p + best_begin, p + word.term_end, output);
675  best_begin = word.term_end;
676 
677  if (phrase_len && --phrase_len == 0) output += hi_end;
678 
679  best_pipe.pop_front();
680  return true;
681 }
682 
683 static void
685  list<vector<string>> & exact_phrases,
686  unordered_map<string, double> & loose_terms,
687  list<string> & wildcards,
688  size_t & longest_phrase)
689 {
690  // FIXME: OP_NEAR, non-tight OP_PHRASE, OP_PHRASE with non-term subqueries
691  size_t n_subqs = query.get_num_subqueries();
692  Xapian::Query::op op = query.get_type();
693  if (op == query.LEAF_TERM) {
694  const Xapian::Internal::QueryTerm & qt =
695  *static_cast<const Xapian::Internal::QueryTerm *>(query.internal.get());
696  loose_terms.insert(make_pair(qt.get_term(), 0));
697  } else if (op == query.OP_WILDCARD) {
699  *static_cast<const Xapian::Internal::QueryWildcard *>(query.internal.get());
700  wildcards.push_back(qw.get_pattern());
701  } else if (op == query.OP_PHRASE) {
702  const Xapian::Internal::QueryPhrase & phrase =
703  *static_cast<const Xapian::Internal::QueryPhrase *>(query.internal.get());
704  if (phrase.get_window() == n_subqs) {
705  // Tight phrase.
706  for (size_t i = 0; i != n_subqs; ++i) {
707  if (query.get_subquery(i).get_type() != query.LEAF_TERM)
708  goto non_term_subquery;
709  }
710 
711  // Tight phrase of terms.
712  exact_phrases.push_back(vector<string>());
713  vector<string> & terms = exact_phrases.back();
714  terms.reserve(n_subqs);
715  for (size_t i = 0; i != n_subqs; ++i) {
716  Xapian::Query q = query.get_subquery(i);
717  const Xapian::Internal::QueryTerm & qt =
718  *static_cast<const Xapian::Internal::QueryTerm *>(q.internal.get());
719  terms.push_back(qt.get_term());
720  }
721  if (n_subqs > longest_phrase) longest_phrase = n_subqs;
722  return;
723  }
724  }
725 non_term_subquery:
726  for (size_t i = 0; i != n_subqs; ++i)
727  check_query(query.get_subquery(i), exact_phrases, loose_terms,
728  wildcards, longest_phrase);
729 }
730 
731 static double*
732 check_term(unordered_map<string, double> & loose_terms,
733  const Xapian::Weight::Internal * stats,
734  const string & term,
735  double max_tw)
736 {
737  auto it = loose_terms.find(term);
738  if (it == loose_terms.end()) return NULL;
739 
740  if (it->second == 0.0) {
741  double relevance;
742  if (!stats->get_termweight(term, relevance)) {
743  // FIXME: Assert?
744  loose_terms.erase(it);
745  return NULL;
746  }
747 
748  it->second = relevance + max_tw;
749  }
750  return &it->second;
751 }
752 
753 string
754 MSet::Internal::snippet(const string & text,
755  size_t length,
756  const Xapian::Stem & stemmer,
757  unsigned flags,
758  const string & hi_start,
759  const string & hi_end,
760  const string & omit) const
761 {
762  if (hi_start.empty() && hi_end.empty() && text.size() <= length) {
763  // Too easy!
764  return text;
765  }
766 
767  bool try_word_break = (flags & MSet::SNIPPET_CJK_NGRAM);
768  if (!try_word_break) {
769  try_word_break = true;
770  }
771 
772  size_t term_start = 0;
773  double min_tw = 0, max_tw = 0;
774  if (stats) stats->get_max_termweight(min_tw, max_tw);
775  if (max_tw == 0.0) {
776  max_tw = 1.0;
777  } else {
778  // Scale up by (1 + 1/64) so that highlighting works better for terms
779  // with termweight 0 (which happens for terms not in the database, and
780  // also with some weighting schemes for terms which occur in almost all
781  // documents.
782  max_tw *= 1.015625;
783  }
784 
786  if (enquire.get()) {
787  query = enquire->query;
788  }
789  SnipPipe snip(length);
790 
791  list<vector<string>> exact_phrases;
792  unordered_map<string, double> loose_terms;
793  list<string> wildcards;
794  size_t longest_phrase = 0;
795  check_query(query, exact_phrases, loose_terms,
796  wildcards, longest_phrase);
797 
798  vector<double> exact_phrases_relevance;
799  exact_phrases_relevance.reserve(exact_phrases.size());
800  for (auto&& terms : exact_phrases) {
801  // FIXME: What relevance to use?
802  exact_phrases_relevance.push_back(max_tw * terms.size());
803  }
804 
805  vector<double> wildcards_relevance;
806  wildcards_relevance.reserve(exact_phrases.size());
807  for (auto&& pattern : wildcards) {
808  // FIXME: What relevance to use?
809  (void)pattern;
810  wildcards_relevance.push_back(max_tw + min_tw);
811  }
812 
813  // Background relevance is the same for a given MSet, so cache it
814  // between calls to MSet::snippet() on the same object.
815  unordered_map<string, double>& background = snippet_bg_relevance;
816 
817  vector<string> phrase;
818  if (longest_phrase) phrase.resize(longest_phrase - 1);
819  size_t phrase_next = 0;
820  bool matchfound = false;
821  parse_terms(Utf8Iterator(text), try_word_break, true,
822  [&](const string & term, bool positional, const Utf8Iterator & it) {
823  // FIXME: Don't hardcode this here.
824  const size_t max_word_length = 64;
825 
826  if (!positional) return true;
827  if (term.size() > max_word_length) return true;
828 
829  // We get segments with any "inter-word" characters in front of
830  // each word, e.g.:
831  // [The][ cat][ sat][ on][ the][ mat]
832  size_t term_end = text.size() - it.left();
833 
834  double* relevance = 0;
835  size_t highlight = 0;
836  if (stats) {
837  size_t i = 0;
838  for (auto&& terms : exact_phrases) {
839  if (term == terms.back()) {
840  size_t n = terms.size() - 1;
841  bool match = true;
842  while (n--) {
843  if (terms[n] != phrase[(n + phrase_next) % (longest_phrase - 1)]) {
844  match = false;
845  break;
846  }
847  }
848  if (match) {
849  // FIXME: Sort phrases, highest score first!
850  relevance = &exact_phrases_relevance[i];
851  highlight = terms.size();
852  goto relevance_done;
853  }
854  }
855  ++i;
856  }
857 
858  relevance = check_term(loose_terms, stats, term, max_tw);
859  if (relevance) {
860  // Matched unstemmed term.
861  highlight = 1;
862  goto relevance_done;
863  }
864 
865  string stem = "Z";
866  stem += stemmer(term);
867  relevance = check_term(loose_terms, stats, stem, max_tw);
868  if (relevance) {
869  // Matched stemmed term.
870  highlight = 1;
871  goto relevance_done;
872  }
873 
874  // Check wildcards.
875  // FIXME: Sort wildcards, shortest pattern first or something?
876  i = 0;
877  for (auto&& pattern : wildcards) {
878  if (startswith(term, pattern)) {
879  relevance = &wildcards_relevance[i];
880  highlight = 1;
881  goto relevance_done;
882  }
883  ++i;
884  }
885 
887  // Background document model.
888  auto bgit = background.find(term);
889  if (bgit == background.end()) bgit = background.find(stem);
890  if (bgit == background.end()) {
891  Xapian::doccount tf = enquire->db.get_termfreq(term);
892  if (!tf) {
893  tf = enquire->db.get_termfreq(stem);
894  } else {
895  stem = term;
896  }
897  double r = 0.0;
898  if (tf) {
899  // Add one to avoid log(0) when a term indexes all
900  // documents.
901  Xapian::doccount num_docs = stats->collection_size + 1;
902  r = max_tw * log((num_docs - tf) / double(tf));
903  r /= (length + 1) * log(double(num_docs));
904 #if 0
905  if (r <= 0) {
906  Utf8Iterator i(text.data() + term_start, text.data() + term_end);
907  while (i != Utf8Iterator()) {
909  r = max_tw * 0.05;
910  }
911  }
912  }
913 #endif
914  }
915  bgit = background.emplace(make_pair(stem, r)).first;
916  }
917  relevance = &bgit->second;
918  }
919  } else {
920 #if 0
921  // In the absence of weight information, assume longer terms
922  // are more relevant, and that unstemmed matches are a bit more
923  // relevant than stemmed matches.
924  if (queryterms.find(term) != queryterms.end()) {
925  relevance = term.size() * 3;
926  } else {
927  string stem = "Z";
928  stem += stemmer(term);
929  if (queryterms.find(stem) != queryterms.end()) {
930  relevance = term.size() * 2;
931  }
932  }
933 #endif
934  }
935 
936  // FIXME: Allow Enquire without a DB set or an empty MSet() to be
937  // used if you don't want the collection model?
938 
939 #if 0
940  // FIXME: Punctuation should somehow be included in the model, but this
941  // approach is problematic - we don't want the first word of a sentence
942  // to be favoured when it's at the end of the window.
943 
944  // Give first word in each sentence a relevance boost.
945  if (term_start == 0) {
946  relevance += 10;
947  } else {
948  for (size_t i = term_start; i + term.size() < term_end; ++i) {
949  if (text[i] == '.' && Unicode::is_whitespace(text[i + 1])) {
950  relevance += 10;
951  break;
952  }
953  }
954  }
955 #endif
956 
957 relevance_done:
958  if (longest_phrase) {
959  phrase[phrase_next] = term;
960  phrase_next = (phrase_next + 1) % (longest_phrase - 1);
961  }
962 
963  if (highlight) matchfound = true;
964 
965  if (!snip.pump(relevance, term_end, highlight, flags)) return false;
966 
967  term_start = term_end;
968  return true;
969  });
970 
971  snip.done();
972 
973  // Put together the snippet.
974  string result;
975  if (matchfound || (flags & SNIPPET_EMPTY_WITHOUT_MATCH) == 0) {
976  while (snip.drain(text, hi_start, hi_end, omit, result)) { }
977  }
978 
979  return result;
980 }
981 
982 }
Unicode and UTF-8 related classes and functions.
bool is_none() const
Return true if this is a no-op stemmer.
Definition: stem.h:166
The Xapian namespace contains public interfaces for the Xapian library.
Definition: compactor.cc:80
void append_utf8(std::string &s, unsigned ch)
Append the UTF-8 representation of a single Unicode character to a std::string.
Definition: unicode.h:332
Wildcard expansion.
Definition: query.h:255
Exhaustively evaluate candidate snippets in MSet::snippet().
Definition: mset.h:179
Letter, modifier (Lm)
Definition: unicode.h:225
const Query get_subquery(size_t n) const
Read a top level subquery.
Definition: query.cc:226
static unsigned check_suffix(unsigned ch)
const char * raw() const
Return the raw const char* pointer for the current position.
Definition: unicode.h:54
const Xapian::Utf8Iterator & get_utf8iterator() const
Definition: word-breaker.h:86
unsigned tolower(unsigned ch)
Convert a Unicode character to lowercase.
Definition: unicode.h:376
bool drain(const string &input, const string &hi_start, const string &hi_end, const string &omit, string &output)
Letter, other (Lo)
Definition: unicode.h:226
Xapian::Query internals.
static double * check_term(unordered_map< string, double > &loose_terms, const Xapian::Weight::Internal *stats, const string &term, double max_tw)
size_t left() const
Return the number of bytes left in the iterator&#39;s buffer.
Definition: unicode.h:59
bool is_digit(unsigned ch)
Class representing a stemming algorithm.
Definition: stem.h:62
bool U_isupper(unsigned ch)
op
Query operators.
Definition: query.h:78
bool is_currency(unsigned ch)
Test if a given Unicode character is a currency symbol.
Definition: unicode.h:371
Number, decimal digit (Nd)
Definition: unicode.h:230
bool is_unbroken_script(unsigned p)
Definition: word-breaker.cc:71
Definition: header.h:63
STL namespace.
deque< Sniplet > best_pipe
Xapian::Internal::intrusive_ptr< Internal > internal
Definition: query.h:49
static Xapian::Stem stemmer
Definition: stemtest.cc:41
#define DECAY
#define rare(COND)
Definition: config.h:575
static void check_query(const Xapian::Query &query, list< vector< string >> &exact_phrases, unordered_map< string, double > &loose_terms, list< string > &wildcards, size_t &longest_phrase)
Iterator returning unigrams and bigrams.
Definition: word-breaker.h:52
Letter, lowercase (Ll)
Definition: unicode.h:223
static unsigned check_wordchar(unsigned ch)
TermGenerator class internals.
unsigned XAPIAN_TERMCOUNT_BASE_TYPE termcount
A counts of terms.
Definition: types.h:72
const std::string & get_pattern() const
const std::string & get_term() const
Definition: queryinternal.h:55
stop_strategy
Stopper strategies, for use with set_stopper_strategy().
Letter, titlecase (Lt)
Definition: unicode.h:224
static void append_escaping_xml(const char *p, const char *end, string &output)
Match only documents where all subqueries match near and in order.
Definition: query.h:152
const unsigned UNICODE_IGNORE
Value representing "ignore this" when returned by check_infix() or check_infix_digit().
Class to hold statistics for a given collection.
Letter, uppercase (Lu)
Definition: unicode.h:222
Punctuation, close (Pe)
Definition: unicode.h:243
Punctuation, open (Ps)
Definition: unicode.h:242
Model the relevancy of non-query terms in MSet::snippet().
Definition: mset.h:172
static bool snippet_check_leading_nonwordchar(unsigned ch)
bool startswith(const std::string &s, char pfx)
Definition: stringutils.h:51
int flags
For backward compatibility with Xapian 1.2.
Definition: termgenerator.h:98
bool pump(double *r, size_t t, size_t h, unsigned flags)
bool get_termweight(const std::string &term, double &termweight) const
Get the termweight.
unsigned check_infix_digit(unsigned ch)
Handle text without explicit word breaks.
bool should_stem(const string &term)
An iterator which returns Unicode character values from a UTF-8 encoded string.
Definition: unicode.h:38
static Xapian::Query query(Xapian::Query::op op, const string &t1=string(), const string &t2=string(), const string &t3=string(), const string &t4=string(), const string &t5=string(), const string &t6=string(), const string &t7=string(), const string &t8=string(), const string &t9=string(), const string &t10=string())
Definition: api_anydb.cc:63
static bool snippet_check_trailing_nonwordchar(unsigned ch)
bool is_wordchar(unsigned ch)
Test if a given Unicode character is "word character".
Definition: unicode.h:343
size_t get_num_subqueries() const
Get the number of subqueries of the top level query.
Definition: query.cc:220
unsigned XAPIAN_DOCID_BASE_TYPE doccount
A count of documents.
Definition: types.h:38
static void parse_terms(Utf8Iterator itor, bool try_word_break, bool with_positions, ACTION action)
Templated framework for processing terms.
Value returned by get_type() for a term.
Definition: query.h:266
Various handy helpers which std::string really should provide.
bool is_whitespace(unsigned ch)
Test if a given Unicode character is a whitespace character.
Definition: unicode.h:361
Punctuation, initial quote (Pi)
Definition: unicode.h:244
Sniplet(double *r, size_t t, size_t h)
op get_type() const
Get the type of the top level of the query.
Definition: query.cc:212
category get_category(int info)
Definition: unicode.h:271
Punctuation, final quote (Pf)
Definition: unicode.h:245
bool is_ngram_enabled()
Should we use the n-gram code?
Definition: word-breaker.cc:41
Class representing a query.
Definition: query.h:46
API for working with documents.
unsigned check_infix(unsigned ch)
stemming algorithms
bool unigram() const
Is this a unigram?
Definition: word-breaker.h:84
parsing a user query string to build a Xapian::Query object