]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: add help for patchid: prefix
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files or flags
4 #
5 # Read-only search interface for use by the web and NNTP interfaces
6 package PublicInbox::Search;
7 use strict;
8 use v5.10.1;
9 use parent qw(Exporter);
10 our @EXPORT_OK = qw(retry_reopen int_val get_pct xap_terms);
11 use List::Util qw(max);
12 use POSIX qw(strftime);
13 use Carp ();
14
15 # values for searching, changing the numeric value breaks
16 # compatibility with old indices (so don't change them it)
17 use constant {
18         TS => 0, # Received: in Unix time (IMAP INTERNALDATE, JMAP receivedAt)
19         YYYYMMDD => 1, # redundant with DT below
20         DT => 2, # Date: YYYYMMDDHHMMSS (IMAP SENT*, JMAP sentAt)
21
22         # added for public-inbox 1.6.0+
23         BYTES => 3, # IMAP RFC822.SIZE
24         UID => 4, # IMAP UID == NNTP article number == Xapian docid
25         THREADID => 5, # RFC 8474, RFC 8621
26
27         # TODO
28         # REPLYCNT => ?, # IMAP ANSWERED
29
30         # SCHEMA_VERSION history
31         # 0 - initial
32         # 1 - subject_path is lower-cased
33         # 2 - subject_path is id_compress in the index, only
34         # 3 - message-ID is compressed if it includes '%' (hack!)
35         # 4 - change "Re: " normalization, avoid circular Reference ghosts
36         # 5 - subject_path drops trailing '.'
37         # 6 - preserve References: order in document data
38         # 7 - remove references and inreplyto terms
39         # 8 - remove redundant/unneeded document data
40         # 9 - disable Message-ID compression (SHA-1)
41         # 10 - optimize doc for NNTP overviews
42         # 11 - merge threads when vivifying ghosts
43         # 12 - change YYYYMMDD value column to numeric
44         # 13 - fix threading for empty References/In-Reply-To
45         #      (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
46         # 14 - fix ghost root vivification
47         # 15 - see public-inbox-v2-format(5)
48         #      further bumps likely unnecessary, we'll suggest in-place
49         #      "--reindex" use for further fixes and tweaks:
50         #
51         #      public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
52         #      * "lid:" and "l:" for List-Id searches
53         #
54         #      v1.6.0 adds BYTES, UID and THREADID values
55         SCHEMA_VERSION => 15,
56 };
57
58 use PublicInbox::Smsg;
59 use PublicInbox::Over;
60 our $QP_FLAGS;
61 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire QueryParser Stem Query);
62 our $Xap; # 'Search::Xapian' or 'Xapian'
63 our $NVRP; # '$Xap::'.('NumberValueRangeProcessor' or 'NumberRangeProcessor')
64
65 # ENQ_DESCENDING and ENQ_ASCENDING weren't in SWIG Xapian.pm prior to 1.4.16,
66 # let's hope the ABI is stable
67 our $ENQ_DESCENDING = 0;
68 our $ENQ_ASCENDING = 1;
69
70 sub load_xapian () {
71         return 1 if defined $Xap;
72         # n.b. PI_XAPIAN is intended for development use only.  We still
73         # favor Search::Xapian since that's what's available in current
74         # Debian stable (10.x) and derived distros.
75         for my $x (($ENV{PI_XAPIAN} // 'Search::Xapian'), 'Xapian') {
76                 eval "require $x";
77                 next if $@;
78
79                 $x->import(qw(:standard));
80                 $Xap = $x;
81
82                 # `version_string' was added in Xapian 1.1
83                 my $xver = eval('v'.eval($x.'::version_string()')) //
84                                 eval('v'.eval($x.'::xapian_version_string()'));
85
86                 # NumberRangeProcessor was added in Xapian 1.3.6,
87                 # NumberValueRangeProcessor was removed for 1.5.0+,
88                 # favor the older /Value/ variant since that's what our
89                 # (currently) preferred Search::Xapian supports
90                 $NVRP = $x.'::'.($x eq 'Xapian' && $xver ge v1.5 ?
91                         'NumberRangeProcessor' : 'NumberValueRangeProcessor');
92                 $X{$_} = $Xap.'::'.$_ for (keys %X);
93
94                 *sortable_serialise = $x.'::sortable_serialise';
95                 *sortable_unserialise = $x.'::sortable_unserialise';
96                 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
97                 # website as it could become a denial-of-service vector
98                 # FLAG_PHRASE also seems to cause performance problems chert
99                 # (and probably earlier Xapian DBs).  glass seems fine...
100                 # TODO: make this an option, maybe?
101                 # or make indexlevel=medium as default
102                 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
103                                 FLAG_WILDCARD();
104                 return 1;
105         }
106         undef;
107 }
108
109 # This is English-only, everything else is non-standard and may be confused as
110 # a prefix common in patch emails
111 our $LANG = 'english';
112
113 # note: the non-X term prefix allocations are shared with
114 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
115 my %bool_pfx_external = (
116         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
117         lid => 'G', # newsGroup (or similar entity), just inside <>
118         dfpre => 'XDFPRE',
119         dfpost => 'XDFPOST',
120         dfblob => 'XDFPRE XDFPOST',
121         patchid => 'XDFID',
122 );
123
124 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST XDFID';
125 my %prob_prefix = (
126         # for mairix compatibility
127         s => 'S',
128         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
129         l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
130         f => 'A',
131         t => 'XTO',
132         tc => 'XTO XCC',
133         c => 'XCC',
134         tcf => 'XTO XCC A',
135         a => 'XTO XCC A',
136         b => $non_quoted_body . ' XQUOT',
137         bs => $non_quoted_body . ' XQUOT S',
138         n => 'XFN',
139
140         q => 'XQUOT',
141         nq => $non_quoted_body,
142         dfn => 'XDFN',
143         dfa => 'XDFA',
144         dfb => 'XDFB',
145         dfhh => 'XDFHH',
146         dfctx => 'XDFCTX',
147
148         # default:
149         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
150 );
151
152 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
153 # not documenting lid: for now, either, it is probably redundant with l:,
154 # especially since we don't offer boolean searches for To/Cc/From
155 # headers, either
156 our @HELP = (
157         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
158         'd:' => <<EOF,
159 match date-time range, git "approxidate" formats supported
160 Open-ended ranges such as `d:last.week..' and
161 `d:..2.days.ago' are supported
162 EOF
163         'b:' => 'match within message body, including text attachments',
164         'nq:' => 'match non-quoted text within message body',
165         'q:' => 'match quoted text within message body',
166         'n:' => 'match filename of attachment(s)',
167         't:' => 'match within the To header',
168         'c:' => 'match within the Cc header',
169         'f:' => 'match within the From header',
170         'a:' => 'match within the To, Cc, and From headers',
171         'tc:' => 'match within the To and Cc headers',
172         'l:' => 'match contents of the List-Id header',
173         'bs:' => 'match within the Subject and body',
174         'dfn:' => 'match filename from diff',
175         'dfa:' => 'match diff removed (-) lines',
176         'dfb:' => 'match diff added (+) lines',
177         'dfhh:' => 'match diff hunk header context (usually a function name)',
178         'dfctx:' => 'match diff context lines',
179         'dfpre:' => 'match pre-image git blob ID',
180         'dfpost:' => 'match post-image git blob ID',
181         'dfblob:' => 'match either pre or post-image git blob ID',
182         'patchid:' => "match `git patch-id --stable' output",
183         'rt:' => <<EOF,
184 match received time, like `d:' if sender's clock was correct
185 EOF
186 );
187 chomp @HELP;
188
189 sub xdir ($;$) {
190         my ($self, $rdonly) = @_;
191         if ($rdonly || !defined($self->{shard})) {
192                 $self->{xpfx};
193         } else { # v2 + extindex only:
194                 "$self->{xpfx}/$self->{shard}";
195         }
196 }
197
198 # returns all shards as separate Xapian::Database objects w/o combining
199 sub xdb_shards_flat ($) {
200         my ($self) = @_;
201         my $xpfx = $self->{xpfx};
202         my (@xdb, $slow_phrase);
203         load_xapian();
204         $self->{qp_flags} //= $QP_FLAGS;
205         if ($xpfx =~ m!/xapian[0-9]+\z!) {
206                 @xdb = ($X{Database}->new($xpfx));
207                 $self->{qp_flags} |= FLAG_PHRASE() if !-f "$xpfx/iamchert";
208         } else {
209                 opendir(my $dh, $xpfx) or return (); # not initialized yet
210                 # We need numeric sorting so shard[0] is first for reading
211                 # Xapian metadata, if needed
212                 my $last = max(grep(/\A[0-9]+\z/, readdir($dh))) // return ();
213                 for (0..$last) {
214                         my $shard_dir = "$self->{xpfx}/$_";
215                         push @xdb, $X{Database}->new($shard_dir);
216                         $slow_phrase ||= -f "$shard_dir/iamchert";
217                 }
218                 $self->{qp_flags} |= FLAG_PHRASE() if !$slow_phrase;
219         }
220         @xdb;
221 }
222
223 # v2 Xapian docids don't conflict, so they're identical to
224 # NNTP article numbers and IMAP UIDs.
225 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
226 sub mdocid {
227         my ($nshard, $mitem) = @_;
228         my $docid = $mitem->get_docid;
229         int(($docid - 1) / $nshard) + 1;
230 }
231
232 sub mset_to_artnums {
233         my ($self, $mset) = @_;
234         my $nshard = $self->{nshard};
235         [ map { mdocid($nshard, $_) } $mset->items ];
236 }
237
238 sub xdb ($) {
239         my ($self) = @_;
240         $self->{xdb} // do {
241                 my @xdb = $self->xdb_shards_flat or return;
242                 $self->{nshard} = scalar(@xdb);
243                 my $xdb = shift @xdb;
244                 $xdb->add_database($_) for @xdb;
245                 $self->{xdb} = $xdb;
246         };
247 }
248
249 sub new {
250         my ($class, $ibx) = @_;
251         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
252         my $xap = $ibx->version > 1 ? 'xap' : 'public-inbox/xapian';
253         my $xpfx = "$ibx->{inboxdir}/$xap".SCHEMA_VERSION;
254         my $self = bless { xpfx => $xpfx }, $class;
255         $self->{altid} = $ibx->{altid} if defined($ibx->{altid});
256         $self;
257 }
258
259 sub reopen {
260         my ($self) = @_;
261         if (my $xdb = $self->{xdb}) {
262                 $xdb->reopen;
263         }
264         $self; # make chaining easier
265 }
266
267 # Convert git "approxidate" ranges to something usable with our
268 # Xapian indices.  At the moment, Xapian only offers a C++-only API
269 # and neither the SWIG nor XS bindings allow us to use custom code
270 # to parse dates (and libgit2 doesn't expose git__date_parse, either,
271 # so we're running git-rev-parse(1)).
272 # This replaces things we need to send to $git->date_parse with
273 # "\0".$strftime_format.['+'|$idx]."\0" placeholders
274 sub date_parse_prepare {
275         my ($to_parse, $pfx, $range) = @_;
276         # are we inside a parenthesized statement?
277         my $end = $range =~ s/([\)\s]*)\z// ? $1 : '';
278         my @r = split(/\.\./, $range, 2);
279
280         # expand "d:20101002" => "d:20101002..20101003" and like
281         # n.b. git doesn't do YYYYMMDD w/o '-', it needs YYYY-MM-DD
282         # We upgrade "d:" to "dt:" to iff using approxidate
283         if ($pfx eq 'd') {
284                 my $fmt = "\0%Y%m%d";
285                 if (!defined($r[1])) {
286                         if ($r[0] =~ /\A([0-9]{4})([0-9]{2})([0-9]{2})\z/) {
287                                 push @$to_parse, "$1-$2-$3";
288                                 # we could've handled as-is, but we need
289                                 # to parse anyways for "d+" below
290                         } else {
291                                 push @$to_parse, $r[0];
292                                 if ($r[0] !~ /\A[0-9]{4}-[0-9]{2}-[0-9]{2}\z/) {
293                                         $pfx = 'dt';
294                                         $fmt = "\0%Y%m%d%H%M%S";
295                                 }
296                         }
297                         $r[0] = "$fmt+$#$to_parse\0";
298                         $r[1] = "$fmt+\0";
299                 } else {
300                         for my $x (@r) {
301                                 next if $x eq '' || $x =~ /\A[0-9]{8}\z/;
302                                 push @$to_parse, $x;
303                                 if ($x !~ /\A[0-9]{4}-[0-9]{2}-[0-9]{2}\z/) {
304                                         $pfx = 'dt';
305                                 }
306                                 $x = "$fmt$#$to_parse\0";
307                         }
308                         if ($pfx eq 'dt') {
309                                 for (@r) {
310                                         s/\0%Y%m%d/\0%Y%m%d%H%M%S/;
311                                         s/\A([0-9]{8})\z/${1}000000/;
312                                 }
313                         }
314                 }
315         } elsif ($pfx eq 'dt') {
316                 if (!defined($r[1])) { # git needs gaps and not /\d{14}/
317                         if ($r[0] =~ /\A([0-9]{4})([0-9]{2})([0-9]{2})
318                                         ([0-9]{2})([0-9]{2})([0-9]{2})\z/x) {
319                                 push @$to_parse, "$1-$2-$3 $4:$5:$6";
320                         } else {
321                                 push @$to_parse, $r[0];
322                         }
323                         $r[0] = "\0%Y%m%d%H%M%S$#$to_parse\0";
324                         $r[1] = "\0%Y%m%d%H%M%S+\0";
325                 } else {
326                         for my $x (@r) {
327                                 next if $x eq '' || $x =~ /\A[0-9]{14}\z/;
328                                 push @$to_parse, $x;
329                                 $x = "\0%Y%m%d%H%M%S$#$to_parse\0";
330                         }
331                 }
332         } else { # "rt", let git interpret "YYYY", deal with Y10K later :P
333                 for my $x (@r) {
334                         next if $x eq '' || $x =~ /\A[0-9]{5,}\z/;
335                         push @$to_parse, $x;
336                         $x = "\0%s$#$to_parse\0";
337                 }
338                 $r[1] //= "\0%s+\0"; # add 1 day
339         }
340         "$pfx:".join('..', @r).$end;
341 }
342
343 sub date_parse_finalize {
344         my ($git, $to_parse) = @_;
345         # git-rev-parse can handle any number of args up to system
346         # limits (around (4096*32) bytes on Linux).
347         my @r = $git->date_parse(@$to_parse);
348         # n.b. git respects TZ, times stored in SQLite/Xapian are always UTC,
349         # and gmtime doesn't seem to do the right thing when TZ!=UTC
350         my ($i, $t);
351         $_[2] =~ s/\0(%[%YmdHMSs]+)([0-9\+]+)\0/
352                 $t = $2 eq '+' ? ($r[$i]+86400) : $r[$i=$2+0];
353                 $1 eq '%s' ? $t : strftime($1, gmtime($t))/sge;
354 }
355
356 # n.b. argv never has NUL, though we'll need to filter it out
357 # if this $argv isn't from a command execution
358 sub query_argv_to_string {
359         my (undef, $git, $argv) = @_;
360         my $to_parse;
361         my $tmp = join(' ', map {;
362                 if (s!\b(d|rt|dt):(\S+)\z!date_parse_prepare(
363                                                 $to_parse //= [], $1, $2)!sge) {
364                         $_;
365                 } elsif (/\s/) {
366                         s/(.*?)\b(\w+:)// ? qq{$1$2"$_"} : qq{"$_"};
367                 } else {
368                         $_
369                 }
370         } @$argv);
371         date_parse_finalize($git, $to_parse, $tmp) if $to_parse;
372         $tmp
373 }
374
375 # this is for the WWW "q=" query parameter and "lei q --stdin"
376 # it can't do d:"5 days ago", but it will do d:5.days.ago
377 sub query_approxidate {
378         my (undef, $git) = @_; # $_[2] = $query_string (modified in-place)
379         my $DQ = qq<"\x{201c}\x{201d}>; # Xapian can use curly quotes
380         $_[2] =~ tr/\x00/ /; # Xapian doesn't do NUL, we use it as a placeholder
381         my ($terms, $phrase, $to_parse);
382         $_[2] =~ s{([^$DQ]*)([$DQ][^$DQ]*[$DQ])?}{
383                 ($terms, $phrase) = ($1, $2);
384                 $terms =~ s!\b(d|rt|dt):(\S+)!
385                         date_parse_prepare($to_parse //= [], $1, $2)!sge;
386                 $terms.($phrase // '');
387                 }sge;
388         date_parse_finalize($git, $to_parse, $_[2]) if $to_parse;
389 }
390
391 # read-only
392 sub mset {
393         my ($self, $query_string, $opts) = @_;
394         $opts ||= {};
395         my $qp = $self->{qp} //= $self->qparse_new;
396         my $query = $qp->parse_query($query_string, $self->{qp_flags});
397         _do_enquire($self, $query, $opts);
398 }
399
400 sub retry_reopen {
401         my ($self, $cb, @arg) = @_;
402         for my $i (1..10) {
403                 if (wantarray) {
404                         my @ret = eval { $cb->($self, @arg) };
405                         return @ret unless $@;
406                 } else {
407                         my $ret = eval { $cb->($self, @arg) };
408                         return $ret unless $@;
409                 }
410                 # Exception: The revision being read has been discarded -
411                 # you should call Xapian::Database::reopen()
412                 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
413                         reopen($self);
414                 } else {
415                         # let caller decide how to spew, because ExtMsg queries
416                         # get wonky and trigger:
417                         # "something terrible happened at .../Xapian/Enquire.pm"
418                         Carp::croak($@);
419                 }
420         }
421         Carp::croak("Too many Xapian database modifications in progress\n");
422 }
423
424 sub _do_enquire {
425         my ($self, $query, $opts) = @_;
426         retry_reopen($self, \&_enquire_once, $query, $opts);
427 }
428
429 # returns true if all docs have the THREADID value
430 sub has_threadid ($) {
431         my ($self) = @_;
432         (xdb($self)->get_metadata('has_threadid') // '') eq '1';
433 }
434
435 sub _enquire_once { # retry_reopen callback
436         my ($self, $query, $opts) = @_;
437         my $xdb = xdb($self);
438         if (defined(my $eidx_key = $opts->{eidx_key})) {
439                 $query = $X{Query}->new(OP_FILTER(), $query, 'O'.$eidx_key);
440         }
441         if (defined(my $uid_range = $opts->{uid_range})) {
442                 my $range = $X{Query}->new(OP_VALUE_RANGE(), UID,
443                                         sortable_serialise($uid_range->[0]),
444                                         sortable_serialise($uid_range->[1]));
445                 $query = $X{Query}->new(OP_FILTER(), $query, $range);
446         }
447         my $enquire = $X{Enquire}->new($xdb);
448         $enquire->set_query($query);
449         $opts ||= {};
450         my $rel = $opts->{relevance} // 0;
451         if ($rel == -2) { # ORDER BY docid/UID (highest first)
452                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
453                 $enquire->set_docid_order($ENQ_DESCENDING);
454         } elsif ($rel == -1) { # ORDER BY docid/UID (lowest first)
455                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
456                 $enquire->set_docid_order($ENQ_ASCENDING);
457         } elsif ($rel == 0) {
458                 $enquire->set_sort_by_value_then_relevance(TS, !$opts->{asc});
459         } else { # rel > 0
460                 $enquire->set_sort_by_relevance_then_value(TS, !$opts->{asc});
461         }
462
463         # `mairix -t / --threads' or JMAP collapseThreads
464         if ($opts->{threads} && has_threadid($self)) {
465                 $enquire->set_collapse_key(THREADID);
466         }
467         $enquire->get_mset($opts->{offset} || 0, $opts->{limit} || 50);
468 }
469
470 sub mset_to_smsg {
471         my ($self, $ibx, $mset) = @_;
472         my $nshard = $self->{nshard};
473         my $i = 0;
474         my %order = map { mdocid($nshard, $_) => ++$i } $mset->items;
475         my @msgs = sort {
476                 $order{$a->{num}} <=> $order{$b->{num}}
477         } @{$ibx->over->get_all(keys %order)};
478         wantarray ? ($mset->get_matches_estimated, \@msgs) : \@msgs;
479 }
480
481 # read-write
482 sub stemmer { $X{Stem}->new($LANG) }
483
484 # read-only
485 sub qparse_new {
486         my ($self) = @_;
487
488         my $xdb = xdb($self);
489         my $qp = $X{QueryParser}->new;
490         $qp->set_default_op(OP_AND());
491         $qp->set_database($xdb);
492         $qp->set_stemmer(stemmer($self));
493         $qp->set_stemming_strategy(STEM_SOME());
494         my $cb = $qp->can('set_max_wildcard_expansion') //
495                 $qp->can('set_max_expansion'); # Xapian 1.5.0+
496         $cb->($qp, 100);
497         $cb = $qp->can('add_valuerangeprocessor') //
498                 $qp->can('add_rangeprocessor'); # Xapian 1.5.0+
499         $cb->($qp, $NVRP->new(YYYYMMDD, 'd:'));
500         $cb->($qp, $NVRP->new(DT, 'dt:'));
501
502         # for IMAP, undocumented for WWW and may be split off go away
503         $cb->($qp, $NVRP->new(BYTES, 'z:'));
504         $cb->($qp, $NVRP->new(TS, 'rt:'));
505         $cb->($qp, $NVRP->new(UID, 'uid:'));
506
507         while (my ($name, $prefix) = each %bool_pfx_external) {
508                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
509         }
510
511         # we do not actually create AltId objects,
512         # just parse the spec to avoid the extra DB handles for now.
513         if (my $altid = $self->{altid}) {
514                 my $user_pfx = $self->{-user_pfx} = [];
515                 for (@$altid) {
516                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
517                         # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
518                         # and '_' with prefixes matching \w+
519                         /\Aserial:(\w+):/ or next;
520                         my $pfx = $1;
521                         push @$user_pfx, "$pfx:", <<EOF;
522 alternate serial number  e.g. $pfx:12345 (boolean)
523 EOF
524                         # gmane => XGMANE
525                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
526                 }
527                 chomp @$user_pfx;
528         }
529
530         while (my ($name, $prefix) = each %prob_prefix) {
531                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
532         }
533         $qp;
534 }
535
536 sub help {
537         my ($self) = @_;
538         $self->{qp} //= $self->qparse_new; # parse altids
539         my @ret = @HELP;
540         if (my $user_pfx = $self->{-user_pfx}) {
541                 push @ret, @$user_pfx;
542         }
543         \@ret;
544 }
545
546 sub int_val ($$) {
547         my ($doc, $col) = @_;
548         my $val = $doc->get_value($col) or return; # undefined is '' in Xapian
549         sortable_unserialise($val) + 0; # PV => IV conversion
550 }
551
552 sub get_pct ($) { # mset item
553         # Capped at "99%" since "100%" takes an extra column in the
554         # thread skeleton view.  <xapian/mset.h> says the value isn't
555         # very meaningful, anyways.
556         my $n = $_[0]->get_percent;
557         $n > 99 ? 99 : $n;
558 }
559
560 sub xap_terms ($$;@) {
561         my ($pfx, $xdb_or_doc, @docid) = @_; # @docid may be empty ()
562         my %ret;
563         my $end = $xdb_or_doc->termlist_end(@docid);
564         my $cur = $xdb_or_doc->termlist_begin(@docid);
565         for (; $cur != $end; $cur++) {
566                 $cur->skip_to($pfx);
567                 last if $cur == $end;
568                 my $tn = $cur->get_termname;
569                 $ret{substr($tn, length($pfx))} = undef if !index($tn, $pfx);
570         }
571         wantarray ? sort(keys(%ret)) : \%ret;
572 }
573
574 # get combined docid from over.num:
575 # (not generic Xapian, only works with our sharding scheme)
576 sub num2docid ($$) {
577         my ($self, $num) = @_;
578         my $nshard = $self->{nshard};
579         ($num - 1) * $nshard + $num % $nshard + 1;
580 }
581
582 1;